I am trying to collect a string that returns a .php file by making an Ajax call. But it always goes into success, however the data it returns is always null. For what is this?? I'm learning and I don't know very well what I'm doing wrong...
The code I have tried:
jQuery.ajax({
url: '/administrator/components/views/response.php',
method: "POST",
dataType: "json",
data: {
request: result.id
}
}).success(function (data) {
console.log("Success. Data: "+ data);
}).error(function (error, responseText) {
console.log("Error. "+ error);
});
The response.php file only contains:
return "Texto de prueba";
Actually I need the .php file to do some calculations and return them, but first I need to solve the problem that it doesn't even return some example...
Something very important to keep in mind when you launch requests to the server through Ajax is what
dataType
you indicate.If you indicate that it is
json
, then whatever happens on the server, the response from the server should only be a json result , since if you send another type of response, the code will not work as expected.Your program could then look like this:
JS/jQuery
I've taken advantage of using
done
andfail
, sincesuccess
anderror
are deprecated since jQuery 3.PHP
Here I create a variable
$arrRespuesta
that will collect information about the result of what happened and at the end I will print that variable in json form, just as Ajax is expecting.Another important thing is to put a header with the data type and encoding. If this is not there the code could fail, for example if there are special characters in the data which would result in invalid json.
Note that in this example the array that is returned will always have a key
status
and that in thedone
Ajax one I have added anotherconsole.log
, to show that you can access the message inside the json key, through its propertystatus
:) .I hope it is useful for you.
I am sending you another way of working with ajax requests... for me, perhaps more comfortable.
"index.php" don't forget to add the jquery.
"response.php"
$.post("response.php?op=XXX" You send the requests you want throughout the project.
switch ($_GET['op']) { case XXXX: collect the variable you send, and proceed to develop the code for each of the requests sent break; }