I am looking to integrate a feature onto my website that reads the data from a JSON file and then outputs that data, all via AJAX.
A bit of background is that I am creating a specific online tool where users can upload and view a JSON file without needing software installed on their PC to do so. The goal is for the user to drag and drop their JSON file into my web page, or click a file select button on the page and choose the JSON file. The background JSON decode would then translate all information from that file, perform some math calculations and output it directly below the file box/select via AJAX without a page load.
The process would be;
- Form on my website where user selects a JSON file from their computer (file not uploaded to site, just read)
- The file is then read, decoded using the following or similar code
$json = file_get_contents($url, false, stream_context_create($arrContextOptions)); // Get content from JSON file
$data = json_decode($json); // Decode the JSON setup file
- That code is then outputted to the page just below the form using code similar to the below
<script>
function formsubmit() {
event.preventDefault();
//AJAX Output
sendData = {
action: 'query_ajax_function',
final_output: final_output,
};
//AJAX Request
jQuery.ajax({
url: ajaxadminurl.ajaxurl,
type: "POST",
data: sendData,
dataType: "html",
cache: false,
success: function(data) {
$('.response').html(data);
}
})
});
}
</script>
How would I go about implementing the upload button and set this up to acheive my desired result. I don’t want to upload the file that is being read, just have a way of the user adding the JSON file to this reader to read the output.
I have successfully created all math equations to read the JSON data from a specific URL using the below code. However, this code allows me to choose a file via a specific URL (in this case, via an ACF custom field).
<?php
$url = get_field('json_file'); // Gets the custom uploaded JSON setup file from URL
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$json = file_get_contents($url, false, stream_context_create($arrContextOptions)); // Get content from JSON file
$data = json_decode($json); // Decode the JSON setup file
?>
I am not sure how to change this to allow the user to choose a file from their computer, and then perform the same JSON decode and file output that I have already created via AJAX. This is the part I need help with.
Thanks
RichRBX is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.