How to add onSuccess and onFailure to getJSON()? - javascript

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
});

Related

AJAX error is returned as Success

AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "#Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready. You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
From the docs (scroll down to the error section):
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 cross-domain JSONP requests. This is an Ajax Event.
The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.
success: function(data) {
if (data.success) { //as you are passing true/false from server side.
// Code if success.
} else {
// Code if error.
}
},

Should you check ajax return data or let javascript throw a error on empty data?

So when handling, for example, the success data in jquery, should you check if the return data has the necessary data like this:
success: function (data) {
if (data.new_rank !== undefined) {
$('._user_rank').html(data.new_rank);
}
}
Or let it fail when it is not present?
success: function (data) {
$('._user_rank').html(data.new_rank);
}
in the previous example you can check if something has changed and needs to be fixt because of the error.
What approach is the best?
It's better you check it, for other code that may be you have in complete or other event. If you didn't, they will not run after error. You can check it this too:
success: function (data) {
if (data.new_rank) {
$('._user_rank').html(data.new_rank);
}
}
jQuery ajax requests provide you a way to handle request errors.
$.ajax(url, {
success: function(data) {
// success
},
error: function() {
// error
}
});
If it's not a request error that you are trying to catch you still should handle error by yourself and not let javascript throw them all the way.
One solution I would say is follow strict data type in $.ajax like dataType: json.
Use success and error handler. And if the return data is anything other than json type it will be handled through error handler.
$.ajax(url, {
dataType: 'json'
success: function(data) {
// success
},
error: function() {
// error
}
});

How to call an exception with post method (AJAX)?

If the post method is unsuccessful I want to throw an exception and write to an error log? Basically if this method returns no results I want to throw an exception and write to file.
Post method:
$.post("ip.php", function( data ){
$("#ip").val(data.ip);
$("#country").val(data.country);
$('#campaignID').val(data.campaignID);
}, "json");
Just add the fail(); method.
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
For the part of the question:
If the post method is unsuccessful I want to throw an exception (...)
You could chain a .fail() callback method to the $.post() request as mentioned by #Grimbode
Or use $.ajax() instead, where is an error option - function to be called if the request fails.
The $.ajax() equivalent to your $.post() method would be:
$.ajax({
type : "POST",
url : "ip.php",
dataType : 'json',
success : function(data){
$("#ip").val(data.ip);
$("#country").val(data.country);
$('#campaignID').val(data.campaignID);
},
error : function(jqXHR/*object*/, textStatus/*string*/, errorThrown/*object*/){
// throw an error ...
// console.log('Type of error: ' + textStatus);
},
});
As for that part:
(...) write to an error log
It's not possible to write any file with javascript. Since it's a client side scripting language that executes in a client browser, it has no access to the server. Well, that's how it works.

how to determine jquery ajax return value or null

I am using jquery post ajax request to do something. the page submit.php return json value and sometime if fatal error occure it return nothing.
I cant determine the ajax return value or not. So how can this possible.
Here are the code i use:-
$.post( 'submitVoice.php', $('#frmVerify').serialize(), function( data ) {
//some code
}, 'json');
Thanks.
You can add .done and .fail handlers (or .then) in a chain after your $.post call:
$.post(...)
.done(function(data, testStatus, jqXHR) { /* use data here */ })
.fail(function(jqXHR, textStatus, errorThrown ) { /* error handling here */ });
Note that in neither case can you return a value to the caller. If you need to do this, return the result of $.post instead.
Instead use ajax call which has success and error callback as shown:
$.ajax({
url : 'submitVoice.php' ,
data: $('#frmVerify').serialize() ,
type: 'POST',
dataType :'JSON',
error: function() {
alert("error");
},
success: function(data) {
alert(data);
}
});
$.post is a shorthand way of using $.ajax for POST requests, so no difference.
$.ajax is generally better to use if you need some advanced configuration.
see reference here.
You can use error callback to know exact error.
$.post('wrong.html', {}, function(data) { })
.fail(function(xhr) { alert('Internal Server Error'); console.log(xhr)});
FIDDLE

jQuery ajax error when sending data

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

Categories

Resources