0

I'm calling an API and getting results back as expected in JavaScript. If a 400 status is returned, I call another API, which I'm doing with an if statement. However, this "if" is never triggered, I think because the way my response is getting read. My code is:

 var getSearchPrimary = {
                    url: 'SEARCH_URL',
                    type: 'POST',
                    crossDomain: true,
                    dataType: 'jsonp',
                    context : this,
                    cache : true,
                    timeout: 60000,
                    success : function(e) {
                        status = JSON.stringify(e.status.code);
                        if(status === "400"){
                            console.log("failed");
                            this.getSearchSecondary(query);
                        }else{
                        console.log(JSON.stringify(e));
                        }

In this case, when I do console.log(status); I get "400" so I'm really not sure why my if statement is never firing!

The response is:

{"status":{"code":"400","message":"Error: No results match the query"},"response":{"results":""}}

I've been staring at this a while now, and would really appreciate any insight!!

6
  • your console log returns 400 as string or int? Because you're using strict comparison ===. Try using just == Commented Feb 16, 2017 at 16:51
  • Interesting-- I just tried replacing (status === "400") with if (!(e.response.length)) and that does fire. Commented Feb 16, 2017 at 16:52
  • I had tried just == , but that didn't solve anything. Commented Feb 16, 2017 at 16:52
  • just log what the status variable has, and check the datatype so that you can compare it correctly. Commented Feb 16, 2017 at 16:54
  • Print JSON.stringify(e) result in the question please. Commented Feb 16, 2017 at 16:54

1 Answer 1

1

The "success" method is called when the request is successful. When 400 is returned, that's not a success. Use the "error" property instead to provide a function that is executed when the request fails.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.