I am having a problem with a simple callback function in jQuery ajax. Google won't help and stack overflow wouldn't either, so I guess this might not be something specific but rather something I am too ignorant to see. To me the code looks exactly like it should.
So, here's the code:
function sendMessage(message)
{
//Establish connection to php script
$.ajax({
type: 'POST',
url: 'action/chat/test.php',
success: function(feedback){
alert(feedback);
}
}).error(function(){
//Do some error handling here
});
}
In test.php it simply says
<?php
echo "called";
?>
As far as I am concerned "called" should be alerted - but it isn't. I have checked already that the function sendMessage() is called (and the parameter message doesn't matter for now).
Does anyone have any idea?
Update: One thing to note also, make sure you use some kind of debugger like firebug. Then you can go to the network tab and look at the request url and response manually to see if its getting a 200 response or internal server error, etc.
Try adding a console.log(data);
in your success function to see if anything is being returned.
You could also use .always(data)
:
function sendMessage(message)
{
//Establish connection to php script
$.ajax({
type: 'POST',
url: 'action/chat/test.php'
}).done(function(data) { console.log(data); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
}
From the docs:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Just for the reference, there is a behavior that may end up like this (ie done() not called).
Here it is:
In this case done() is never called, but always() will be. And in always() you will get the "badly" formatted answer as pure text.
It's probably the error handling. If you want to handle errors, there's another attribute you can give the object you pass in to ajax, it's "error", and also "timeout" for handling page timeouts. Look up the $.ajax function and you'll find these attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With