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

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.

Related

Meteor HTTP call is different from jquery ajax?

I have the same call in Meteor HTTP and in jQuery ajax. But the response from server is different.
Meteor:
HTTP.call("POST", url, {
params: data
}, function (error, result) {
//My works....
})
jQuery:
$.ajax({
"url": url,
"method": "POST",
"data": data,
success: function(data_res) {
//My works...
}
})
I would expect the same result, but jquery is executed correctly, while meteor returns an error.
Are calls not identical?
In Meteor method call, Use 'data' field instead of 'params' as it's a POST request.
Try this in Meteor :
HTTP.post( URL, {data:dataToBePosted,headers:{key:value}}//if headers needed use headers field
,function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response);
}
});

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.
}
},

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 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 $.post success function never fires

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.

Categories

Resources