I'm new to web development, so please pardon any silly mistakes!
I'm using the following code send a jQuery Ajax request:
var d = "email=" + email + "&password=" + password;
$.ajax({
url: 'login/c_login_form.php',
data: d,
dataType: "text", //expected type from server
type: "POST",
success: function(str, status) {
console.log(str + ": " + status);
},
error: function(obj) {
alert("Fatal error. Failed to send Ajax request.");
}
});
For simplicity, let us assume that login/c_login_form.php is currently blank (but has the php tags, of course) and is to return a set data every time.
I was under the impression that whatever I echo from the server will be passed to the success function, but it's not working that way. What is the way to send data from PHP script back to Ajax? Although I've used text datatype, I'd be happy if somebody can tell me how to return JS objects.
2 Answers 2
To summarize comments in a concrete answer:
<?php
header('Content-Type: application/json');
$data = array("status" => 1, "err" => "example_error_code");
echo json_encode($data);
?>
Please note, as Anthony Grist suggests, that you need, on your Javascript:
dataType: "json"
instead of:
dataType: "text"
See also jQuery ajax docs:
...
dataType (default: Intelligent Guess (xml, json, script, or html))
...
3 Comments
You can refer this answer for Ajax post request.
To send back data from PHP file to JS you need to use echo.
If you are passing more than one variable then you can use echo json_encode($array_of _variables);. If there is only one variable than please you can use just echo $variable.
echo "1, 2, 3";?dataType: 'json',and encode php response$data=array( "status"=>1, "err"=>"example_error_code", ); echo json_encode($data);echodo?