jQuery ajax error when sending data - javascript

I am trying to debug an error which is coming up when u run the following code. The ajax call simply carries a variable destroy which is a String. However, I am getting an error alert(xhr.status); which is return 0 and statusText is returning "error". Can anyone see a problem in this?
The new updated code is:
function logout() {
var destroy = "session_destroy"
FB.logout(function(response) {
$.post("setUser.php", { destroy: destroy }, function (data) {
alert(data);
window.location.href = "signup.php";
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
}
Note: This ajax calls intends to destory session whose code exists in setUser.php

I don't see any problem with your code. What is it the response setUser.php is giving you?
NOTE:
To see what is being logged in CHrome or IE >9 press F12, and go to console.
But why aren't you using the shorthand version?
$.post("setUser.php", { destroy: destroy }, function (data) {
alert(data);
window.location.href = "signup.php";
})
.fail(function(e, status, error) {
console.log(e);
console.log(status);
console.log(error);
alert(error);
})
.always(function() {
alert("finished");
});
DOCS

Related

Why can't I wrap js promise resolve in a jquery object?

I wanted to be able to send the data from a successful jquery ajax call to other methods in my application because its quite large and it made coding sense to have one api method to work from, so I opted to try out promises. This is my first shot. I am getting some good results but clearly I am still a bit confused on context and timing.
When I run the following code, I am unable to wrap my return data from the ajax call as a jquery object without getting an error:
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
var $selectTarget = $(this),
widgetid = $(this).data('widgetid');
apiRequestData = widgetSystem.makeApiRequestForSingleWidget(widgetid);
apiRequestData.then(function(result) {
widgetSystem.showWidget(result);
}).catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
$.ajax({
method: "POST",
url: "localhost",
dataType: 'json',
data: {
data: {
widgetId: widgetid
},
action: 'apiMethod'
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
reject();
},
success: function (data) {
resolve(data);
}
});
});
},
showWidget: function(data){
$(data).appendTo('body');
//this causes an exception in my apiRequestData.then function in listenForClick
}
}
I am running un minified jquery and getting the following error in my console:
no way big error TypeError: context is undefined
I don't know exactly what your HTML looks like or how the API is set up, but assuming that the API is working correctly and the data sent via POST is correct, I was able to get it working using jsonplaceholder api with the following code (you can find it on JSbin).
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
console.log('clicked');
var $selectTarget = $(this);
var widgetid = $(this).data('widgetid');
widgetSystem.makeApiRequest(widgetid)
.then(function(result) {
widgetSystem.showWidget(result);
return result;
})
.catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
method: "POST",
url: root+'/posts/',
dataType: 'json',
data: {
userId:1,
title:"Havanagila",
body:"Testing the greatness"
},
success: function(xData, status){
resolve(xData);
//reject('whoops');
},
error: function(xhr, status, error){
reject(status);
}
});
});
},
showWidget: function(data){
$('#space').append(document.createTextNode(JSON.stringify(data)));
}
}
widgetSystem.listenForClick()
I don't think there is an issue which how you are calling resolve(data) within the ajax success callback. There may be an issue with the data being sent to your API such that the error callback is called, which in turn calls reject and causes the callback passed to .catch to be called instead of the intended callback passed to .then.

How to add onSuccess and onFailure to getJSON()?

The following code makes a API call to the server and gets the response as JSON. Then it turns the JSON object to a string and parse the same using respective jQuery functions and store it to the local storage and load a page. I want to do this on success and throw an error message on failure. I tried .done() and .fail() functions but it throws an uncaught expression error.
$.getJSON(apiURL,
{'call':'login','email':uname, 'pwd':password},
function(data){
localStorage.setItem('testObject', data.id);
$.ui.loadContent("home", null, null, "fade");
}
);
Can someone how can I add onSuccess and onFailure to this code ?
I tried .done() and .fail() functions but it throws an uncaught expression error.**
.done and .fail are indeed how you would do this, it sounds like your code trying to use them had a syntax error.
$.getJSON(apiURL, { 'call': 'login', 'email': uname, 'pwd': password })
.done(function() {
// Handle success
var obj = JSON.stringify(data); // <=== These lines are
var parsed = JSON.parse(obj); // <=== completely pointless
localStorage.setItem('testObject', parsed.id);
//alert(localStorage.getItem('testObject'));
$.ui.loadContent("home", null, null, "fade");
})
.fail(function() {
// Handle failure
});
Try using
$.getJSON(apiURL, { 'call': 'login', 'email': uname, 'pwd': password })
.done(function() {
var data = JSON.stringify(data);
//...
});
.fail(function(){
console.log('failure');
});
You can also do
result = $.get('url',{param1:'param'});
result.done(function(data){
//handle success
});
result.done(function(){
//handle failure
});

How to read a property from a JSON response when the HTTP response has a failure code?

I have this code:
$.post(Routing.generate('parMarcaModelo'), {
"marcaId": currBranch,
"modeloId": currModel,
"marcaNombre": currBranchName,
"modeloNombre": currModelName
}, 'json').done(function (data, textStatus, jqXHR) {
// do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
// Catch error from server and logs to console
var err = eval("(" + jqXHR.responseText + ")");
colose.log('Error', err.Message, 20000);
return false;
});
The server side returns a JSON like this one:
{
"success":false,
"error":"El par Marca2-Modelo1 ya existe. Por favor escoja otra combinaci\u00f3n.",
}
But also returns a 400 code so Ajax call will go through .fail() callback insted of .done(). Having this information, how I can catch the error key from the JSON in the .fail() to show to users?
I have found this code:
$.get('http://localhost/api').then(function(res) {
var filter $.Deferred()
if (res.success) {
filter.resolve(res.data)
} else {
filter.reject(res.error)
}
return filter.promise()
}).done(function(data) {
console.log('Name:', data.name) // Outputs: Foo
}).fail(function(error) {
console.log('Error:', error) // Outputs: Something bad happened.
})
On this topic at SO but does not know if is right and also if will affect my code in someway.
Any help or advice?
You are sending in 'json' as the success callback function to $.post().
This is the correct function signature:
jQuery.post( url [, data ] [, success ] [, dataType ] )
Clarification
This code will work, since it passes in an empty function in place of the 'success'.
$.post('rest.php', {data : 'data'}, function(){},'json').done(
function (data, textStatus, jqXHR) {
// do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
// Catch error from server and logs to console
console.log('Error', jqXHR.responseJSON, 20000);
return false;
});
However, this code will not:
$.post('rest.php', {data : 'data'}, 'json').done(
function (data, textStatus, jqXHR) {
// do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
// Catch error from server and logs to console
console.log('Error', jqXHR.responseJSON, 20000);
return false;
});
For proof, look at line 781-798 in the jQuery source code. If the data parameter is a function, e.g. the success callback, the items will get shifted. However, since this is not the case, every parameter will be put in by the position they appear in the function.
In the second version, Ajax.succees will be set to the string 'json' and the Ajax.dataType is set to undefined. The jqXHR.responseJSON of that version will return a undefined, since it's not parsed as JSON.
The first version, however, returns a JSON object.
Also, you wrote colose.log instead of console.log in your code. That might be why couldn't get the data.

How to capture the 500 error message using jquery?

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.
Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

Trapping Function not defined error in Javascript and jQuery

Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});

Categories

Resources