Background:
Using jQuery 1.7 client side
PHP server side
Using json responses with json_encode php function
The content-type header is correct, any of these works: text/plain,text/x-json,application/json.
There's no errors thrown from my php code
Am working on Firefox 11
Am using the js console and the other web's developer tools
HTTP/1.1 200 OK
In this Javascript code, the success event is never fired:
$.ajaxSetup({cache:false,
success:function(d) {
console.log("ok from setup with data "+d.toSource())
},
complete:function(xhr,ts){
console.log("Ajax finished reponse:"+xhr.responseText)
},
error:function(jqXHR, textStatus, errorThrown){
console.log("Error")
}
});
$.getJSON("test2.php",{},function(data){
//some code here
});
When I do it this way, it works:
$.ajaxSetup({cache:false,
complete:function(xhr,ts){
console.log("Ajax completado con:"+xhr.responseText)
},
error:function(jqXHR, textStatus, errorThrown){
console.log("Error")
}
});
$.getJSON("test2.php",{},
function(data){
//some code here
}).success(function(d){
console.log("success applied directly, data "+d.toSource())
}
);
In both cases the complete event is always fired and the error one never.
However, in the second code the success is fired.
Obviously for .get() method it's the same.
PHP code:
<?php header("Content-Type:application/json;charset=utf-8");
//or whatever text/x-json text/plain, even text/html, jquery do the dirty job
echo json_encode(array("stat"=>"1")) ?>
My objectives:
I want to fire the same success event to all ajax requests
I want to use the json data returned by the request in my success event, and if it is possible, without convert the raw jqXHR responseText to a json again
The problem is strange, any ideas?
I read all these questions:
Ajax success event not working
AjaxSetup never execute the success function
Does jQuery ajaxSetup method not work with $.get or $.post?
$.ajax function's success: not firing
And I'm pretty sure none of them are my problem.
Take a look at the ajaxSetup documentation: http://api.jquery.com/jQuery.ajaxSetup/
Note: Global callback functions should be set with their respective
global Ajax event handler methods—.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than
within the options object for $.ajaxSetup().
I think that's your problem right there.
UPDATE
If you want your ajax handlers to be global for any ajax request on the page, do something like this:
$(document).ajaxSuccess(function(d){
console.log("ok from setup with data "+d.toSource());
});
Related
I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes
So I have a jquery ajax call like so:
$.ajax({
url: 'delete.php',
data : {
'prd_id': <prd-id-number>
},
success: function(data) {
//show success here
},
error : function(error) {
//show error here
}
});
My doubt is about the success and error handlers. Is the error handler only used for "ajax level" error? I mean - my application can have its own error, for.e.g. the passed product id does not exist or is incorrect. Now, currently what I am passing a message back, which goes into success() then I have to do some internal logic to see if the message is an application error or truly success - and based on that I show the message.
is there any way I can send the message to error() - is that the proper way to trap and handle ajax errors?
Ajax error can be triggered several different ways. The most common ones are , http status not being 200, timeout and data parsing errors such as incorrectly formatted json.
You can trigger the error yourself from server by returning an http response code header.
For example assume you have an API that looks up users by ID and you send an invalid ID. You can return a 404 response code header with data included that can be used in your app from within the error callback.
This allows you to set up the application code to handle both types of errors using the error callback
Well i think you need to recall some concepts.
ajax success and error handlers are called depending upon the success or failure of the axaj call send.
success handler is called whenever the ajax call has successfully completed while error handler is called whenever the ajax call could not be completed due to any sort of error.
For your case you will have to manipulate the success handler and show the required message.
There is no way to call error handler when your ajax call has been successfully completed.
This is my $.ajax function. volunteerDist is an array in a previous function and it calls myAjax(volunteerDis);However, the program always calls the error and complete functions, with an error message of undefined. What should I do? Thanks
admin-view-available-volunteeers.php is the filename where this is located
volunteerDist is an array that contains floats
function myAjax(volunteerDist){
$.ajax({
type:'POST',
url: 'admin-view-available-volunteeers.php',
data : ({
distance:volunteerDist
}),
success: function(){
alert('worked');
},
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
complete : function(){
alert('thanks');
}
});
}
If your error: handler is being called, then the remote script returned an error.
Fix the script, not the JS code!
To get better debugging on error you need to update your code, this
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
will not work - as err is a jqXHR object!
change it to this :
error: function(jqXHR, textStatus, errorThrown) {
alert("Error : " + errorThrown);
}
This will output the message sent by the server.
All the details for the params of .ajax() are documentation here
Update
Check the name of your PHP file ...
admin-view-available-volunteeers.php
has 3 es in the word volunteer ... is this the problem ?
I always get this a lot. In your admin-view-available-volunteers.php you need to make sure that you're outputting the right headers.
To do that you need to put this in your php before anything is output:
header("HTTP/1.01 200 OK");
header("Content-type: text/html");
Otherwise it is returned as a 404 to jQuery's ajax and then goes into the error and complete bits.
You may wish to try loading a different test file first, something simple that way you can test the js separately and ensure that when you hit the php script directly in your browser that there are no errors shown.
Also in the future make sure you have all these ajax calls on the same domain as your php scripts(like you do now), otherwise ajax won't work across domains without adding a "Access-Control-Allow-Origin", "*" header.
A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.
I'm using jQuery.getJSON() on a URL (different domain) which may not exist. Is there a way for me to catch the error "Failed to load resource"? It seems that try/catch doesn't work because of the asynchronous nature of this call.
I can't use jQuery.ajax()'s "error:" either. From the documetation:
Note: This handler is not called for cross-domain script and JSONP requests.
If you have an idea of the worst case delay of a successful result returning from the remote service, you can use a timeout mechanism to determine if there was an error or not.
var cbSuccess = false;
$.ajax({
url: 'http://example.com/.../service.php?callback=?',
type: 'get',
dataType: 'json',
success: function(data) {
cbSuccess = true;
}
});
setTimeout(function(){
if(!cbSuccess) { alert("failed"); }
}, 2000); // assuming 2sec is the max wait time for results
This works:
j.ajaxSetup({
"error":function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}});
Deferred objects (new in jQuery 1.5) sound like exactly what you're looking for:
jQuery.Deferred, introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
http://api.jquery.com/category/deferred-object/
EDIT:
The following code works fine for me:
function jsonError(){
$("#test").text("error");
}
$.getJSON("json.php",function(data){
$("#test").text(data.a);
}).fail(jsonError);
json.php looks like this:
print '{"a":"1"}';
The error function fires for me if the path to json.php is incorrect or if the JSON is malformed. For example:
print '{xxx"a":"1"}';
What your complaining about is a client-side error saying that you tried to download a resource from the server.
This is build into the browser and it allows your browser to tell the client or the developers that the downloading of a resource from the internet failed. This has nothing to do with JavaScript and is a more low level error thrown on the HTTP that is caught by the browser.
If you want any hope of catching it your going to need to drop 3rd party ajax libraries and deal with the XMLHTTPRequest object on a much lower level, even then I doubt you can do anything about it.
Basically when you see this error then find out what object your trying to get that doesn't exist or couldn't be accessed. Then either stop accessing it or make it accessible.