dantheman
dantheman

Reputation: 273

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

Upvotes: 0

Views: 61

Answers (2)

Artur Filipiak
Artur Filipiak

Reputation: 9157

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.

Upvotes: 0

kockburn
kockburn

Reputation: 17626

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

Upvotes: 1

Related Questions