track ajax error and alert it - php

I am using ajax call in jquery to handle some database operations, in ajax code I have a alert on error property, which gives my error message, but I want to know what the error was?
here is my ajax code
$.ajax(
{
type: "POST",
url: "server/assign_gifts_get_usr_details.php",
data: "",
success: function(xml)
{
alert(xml);
},
error: function()
{
alert("Error, Please try again");
}
});
this alert is popping up, alert("Error, Please try again");
but I want to know the error.

Well if it is getting to the error part of your code then the page was not able to load correctly.
That is basically the error.
There are also arguments that are passed to the error callback which you can use as well.
See the docs
The error callback gets the following arguments passed in: (jqXHR, textStatus, errorThrown)
From the docs:
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.

Do it like this, to get error details.
error: function(jqXHR, textStatus, errorThrown)
{
alert("Error: "+errorThrown+" , Please try again");
}

Related

How to get HTTP error response code 403 in jQuery UI Autocomplete Ajax?

I am using the jQuery UI autocomplete feature for some <input type='text'> boxes where it should return some selections depending on the input. This is working fine but now I need to add a check if the user even is allowed to do this lookup and if not, the user should be alerted.
This is my current code (or some of it at least):
$(this).autocomplete({
source: function(request,response) {
$.ajax({
url: 'search.json',
data: { field: thisName,
search: request.term }
}).done(function(data) {
response(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.dir(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
},
minLength: 1,
...[CUT]...
If I inside my search.json only has this http_response_code(403); I will receive this in the console (I hope the picture is readable):
So my question is - how can I report back an error to the autocomplete script so it acts correctly? For example it could alert the user in some way.
Currently I want to report back with a 403 Forbidden code but there could be other errors too - e.g. the user session could expire or alike. It doesn't necessarily needs to be a HTTP response code but this is what I see as the most correct to use in this scenario?
Please see the JSFiddle demo for my code.
I am using jQuery 1.11.0 and jQuery-UI 1.10.4 together with PHP 5.4 on an IIS 7.5. The IIS will pass .json files as normal PHP files - just to clarify if important.
Using AjaxSetup seems to be an option:
$.ajaxSetup({
error: function (x, status, error) {
if (x.status == 403) {
alert("Sorry, your session has expired. Please login again to continue");
window.location.href ="/Account/Login";
}
else {
alert("An error occurred: " + status + "nError: " + error);
}
}
});
Source: http://cypressnorth.com/programming/global-ajax-error-handling-with-jquery/
Since $.ajax() also supports the error method, it might also work for $.ajax() itself.
I actually found out that this was caused by me having my own error pages defined in the IIS. When changing the errorcode 403 to someting else (e.g. 999) I will get the 403 error to my Ajax script:
I have answered this myself in case others are having a similar problem and not being aware that their selfdefined HTML error messages/pages will give a HTTP response code of 200 in the Ajax.

AJAX Call Not Sending Success Response

//MAKE AJAX CALL TO REPOPULATE TABLE
var newData = 'page_number=1&type=2';
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'http://www.myurl.net/form_validate.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
//REFORMAT UPON SUCCESSFUL AJAX CALL
alert(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
All I've put in my PHP file is:
<?php echo "test"; ?>
When I go straight to that file, it echoes 'test.' When I try to run the AJAX function on the click of a button it gives me the error:
[object Object] error
in an alert window. I've put the absolute URL to the file because I was thinking that the relative linking I was using was wrong but it now seems like it's some other issue. Am I overlooking a simple syntax error? Sorry if this is super basic but I can't seem to figure this out after working on it for a really long time. Thanks for your help.
The problem is your absolute url . Some browsers have problems dealing with absolute urls, consider it as a cross-domain request and block it even if it's not a cross-domain request. You should try with relative url instead
The problem might be in the url, try with relative path instead of absolute.
You named the file was in the same folder as the .js file, so try
url: '/directory_path_to_the_same_folder_as_the_JS_file/form_validate.php',
Try using done with jQuery.post instead.
For example:
jQuery.post('form_validate.php', data).done(
function(data, textStatus, jqXHR) {
alert(jqXHR.responseText);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}).complete(function() {
// Common code when request completes
});
If your error is [object Object] error NOT FOUND then the reason is
the specified url in AJAX is not correct.
If your error is [object Object] error INTERNAL SERVER ERROR , its
because of the error in your server file ie the php file ,error like variables not defined correctly etc..
Some times error may occur due to cross domain, if you have not
specified headers when in case your php file is not in the same
domain
Hope this helps
Thank you
function abc(){
var ret=true;
$.ajax({
type: 'POST',
url: 'send_password.php',
data: 'mail_to=mymail&new_password=pwd',
async:false,
success: function(response){
},
error: function(r){
ret=false;
}
});
return ret;
}
alert(abc());
Have a look at this testfiddle

jquery ajax php call not working correctly

I copied this ajax call from another one that works and I can't figure out why it's not successfull. Here is the code:
$.ajax({
type: "POST",
url: "addTune.php",
data: {
database: setlist,
name: tune,
orderno: orderno,
midi: midi
},
error: function (e) {
alert("The PHP Call failed! hmmm");
alert(e.status);
},
success: function (response) {
alert(response);
}
});
I get the error function every time. Are there any blaring typos or other stupid mistakes?
Edit: trying to chase down the error with:
$.ajax({
type: "POST",
url: 'addTune.php',
data: {database : setlist, name : tune, orderno : orderno, midi : midi},
error: function(e){
alert("The PHP Call failed! hmmm");
alert(e.status);
$.ajaxSetup({
"error": function(jqXHR, status, thrownError) {
alert('error');
var responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(responseText);
}
});
},
success: function(response){
alert(response);
}
});
});
Update: I was just able to add a row with the command line. any thoughts as to what I can do to try and narrow this down further?
i am no pro at this but maybe using single quote instead of double quotes? because i'm working on a project were i also have to do ajax calls and i use single quotes
i'm just suggesting something, not really good at this
If you get into the error callback then you have an error with the page you are calling and not with the js code. Check if the php page is reached. If it is check the php code if it returns a valid result.
From jquery DOCS.
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.

Adding a condition for success or error using jQuery ajax + Wordpress

When using the Wordpress "nonce" system to authenticate an AJAX request, a response of "-1" is returned if the authentication fails. Rather than doing something like this in every jQuery.ajax success function:
success: function(msg){
if (msg == '-1')
console.debug('error')
else {
// ...
}
}
is it possible to somehow augment jQuery and add a condition for my application that error: rather than success: is fired when the message returned is "-1"? Obviously much cleaner than a bunch of the same if statements.
I realize the normal response is to have the controller return a 4xx header, but would rather not have the Wordpress plugin change the default behaviour of the ajax handler and possibly mess up other Wordpress plugins.
Thanks!
There is also an error callback
http://api.jquery.com/jQuery.ajax/
Example
$.ajax({
url: 'http://somewhere.com/index.html'
success: function(data, textStatus, jqXHR) {
//do stuff
},
error: function(jqXHR, textStatus, errorThrown) {
//do stuff
}
});

Is that possible to call to external PHP script from Ajax?

I'm trying to call to external PHP script using Ajax like this:
$(function() {
$.ajax({'url': 'http://stokes.chop.edu/web/zscore/result.php',
'type': 'POST',
'success': function(response, textStatus, XMLHttpRequest) {
alert('[' + response + ']');
},
'error': function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error');
}
});
});
The result is: [] (i.e. success function is called!),
but I see the following error in HTTPFOX plugin for FireFox:
Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)
What's wrong with my code ?
You cannot load contents from pages that does not have the same domain name as the one from which the ajax request is called from. This is a well known security feature call the Same Origin Policy.

Categories