Halnex
Halnex

Reputation: 4536

How can I show an error message if ajax post failed?

I have an ajax post request that works well if the user is logged in but gives an error if the user is logged out.

The error that gets thrown in the console

POST http://localhost/r2/public/votes 500 (Internal Server Error)

I have an authentication gate forbidding users to vote if they're not logged in. All is good so far.

But I would like to show a customized an error message, perhaps in a simple modal window.

at the moment, I am trying to console.log() but it's not printing anything, I keep getting the same error as above.

$('.topic').upvote();

$('.vote').on('click', function (e) {
    e.preventDefault();
    var $button = $(this);
    var postId = $button.data('post-id');
    var value = $button.data('value');
    $.post('http://localhost/r2/public/votes', {postId:postId, value:value}, function(data) {
    if (data.status == 'failure')
    {
       console.log('You are not logged in.');
    }
   }, 'json');
});

Upvotes: 0

Views: 757

Answers (1)

Oleg Sklyar
Oleg Sklyar

Reputation: 10092

See http://api.jquery.com/jquery.post/

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
}).fail(function() {
  alert( "error" );
});

And it is not ideal to use 500 for authentication errors as there is 401 for that.

Upvotes: 2

Related Questions