jQuery $.post success function never fires - javascript

I have a $.post which using Fiddler I can see always posts successfully but my success function is never fired.
A successful post to the url returns a 1 or failure returns a 0, on each occasion I have tested it returns the expected value of 1 so I'm at a lost as to what I'm doing wrong?
if ($('#mycheckbox').prop('checked')) {
$.post('/base/MailingList/Subscribe/',
{
listId: $('#mycheckbox').val(),
name: $('#subscriber-name').val(),
email: $("#subscriber-email").val()
},
function(response) {
console.log(response);
});
}

Stick another function as a final callback. That function will run in the failure case.
The way jquery recommends doing it is this:
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});

I'm not sure if this will help or not, but I always use fully qualified urls when I do any asynchronous calls. You may want to try:
$.post('http://mydomain.com/base/MailingList/Suscribe/', ...
Additionally, you will likely want your handling function to recieve all three argument from the callback (data, textStatus, jqXHR). This way, you can look at the txtStatus to verify if you have success or not.

In my case the problem was header with wrong MIME type ("application/json" instead of "text") in php file on server. If you send header that doesn't match type of data cause an error and $.post calls fail function.

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

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