Reputation: 614
I have a function for making a post request.
$('#save').click( function() {
...
$.ajax({
type: 'POST',
url: 'logic/save.php',
data: { 'json': JSON.stringify( post ) },
dataType: 'jsonp',
success: function( data ) {
console.log('success!')
}
});
}
The request handler is written in php, as you can see, and performs operations with mysql. Because of my poor knowledge of php and requests, I do not see any success! output in the console. Php code runs fine, and the mysql queries runs with no errors.
What I want is to be able to write something in php code at the end so that my code in js could receive it as a positive response (like 200, OK) and the success! line in the console will then (I believe) appears.
What code should I add to the php file?
UPDATE: since many of people requested the php code, here's the link to it. Thank you for fast replies, guys.
Upvotes: 0
Views: 2123
Reputation: 13348
First, you should switch from jsonp to json, as you have no need for jsonp in this case. The following instructions assume you have made that change.
The bug is in your PHP code when you respond back to the client. You do so with this line:
print_r( "New item inserted.\n" );
However, jQuery is expecting you to be returning JSON back from your endpoint (and, truthfully, it should, because sending back plaintext to an ajax client is almost never the right way). We can make this work with jQuery by changing the line above to something like this:
print json_encode( array('success' => true, 'message' => "New item inserted." ) );
You should find yourself in the success callback in your client. This code would work for your success handler:
{ // ...,
success: function(response) {
if (response.success) {
alert(response.message);
}
}
}
You'll probably want to use something other than an alert, though. But that's up to you.
Upvotes: 4