skip to Main Content

I’m using jquery and ajax to get the data from the API but when the user insert invalid data, I want to get the message that coming from xhr in an alert.

this is the code I’m using



const settings = {
                      "url": "A url",
                      "method": "POST",
                      "contentType": "application/json; charset=utf-8",
                      "timeout": 0,
                      "data":  JSON.stringify({
                      username: ''+theUserVal+'',
                      password: ''+thePassVal+''
                    }),

                    };

                    $.post(settings).done(function (response) {
                      console.log('backend response', response);
                      localStorage.setItem('user', JSON.stringify(response));
                    }).done(function() {
                        
                     $('.loader-img').fadeIn(100);

                    setTimeout(goToSecPage,500);
                        
                  }).fail(function() {
                        
                    alert( "please insert valid data" );
                        
                  });

this code works fine but I need to replace "please insert valid data" with the response that coming from xhr

update

I used this code

.fail(function(xhr, status, error) {
                        
              var err = JSON.parse(xhr.responseText)
           alert( JSON.stringify(err));

 });

and it worked but the response has an error as a key and its value and a message as a key and its value, how can I get only the message

2

Answers


  1. update .fail section of your code to pass xhr as a parameter of your function.

    .fail(function(xhr, status, error{
      var err = eval("(" + xhr.responseText + ")");
     alert(err.Message);
    });
    

    or

    .fail(function(xhr, status, error) {
       alert(xhr.responseText);
    });
    
    Login or Signup to reply.
  2. First of all, I would recommend removing the double quotes around the variables you are sending to the server, is it necessary?

    You can access the XHR object from your fail() method and narrow down to the data you need.

    This links might be useful too.

    https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_post
    https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_post2

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search