To create an AJAX web service, you need two files:
- Javascript caller sending data as POST (maybe as GET) using jQuery AJAX
- PHP web service that returns a JSON object (it is convenient to return arrays or a large amount of data).
So, first you call your web service using this jQuery syntax in your JavaScript file:
$.ajax({ url : 'mywebservice.php', type : 'POST', data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php dataType : 'json', success: function (data) { alert("The file is "+data.fichierZIP); }, error: function(data) { //console.log(data); var responseText=JSON.parse(data.responseText); alert("Error(s) while building the ZIP file:\n"+responseText.messages); } });
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this at the end in order to return the correct success or error status:
<?php //... //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename" //$errors is a string that may contain an error message while preparing the ZIP file //In the end, I check if there has been an error, and if so, I return an error object //... if ($errors==''){ //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript header('Content-Type: application/json; charset=UTF-8'); $result=array(); $result['ZIPFILENAME'] = basename($filename); print json_encode($result); } else { //if there is an error, you should return a special header, followed by another JSON object header('HTTP/1.1 500 Internal Server Booboo'); header('Content-Type: application/json; charset=UTF-8'); $result=array(); $result['messages'] = $errors; //feel free to add other information like $result['errorcode'] die(json_encode($result)); } ?>
philippe Nov 28 '16 at 23:16 2016-11-28 23:16
source share