0

I'm using Jquery's ajax method, and I need help parsing data coming back from backend server.

server response will be either "valid" or "not valid.

Currently my "if statement logic is not working, this is what I have tried so far).

$.ajax({
    url: 'php/phone-valid.php',
    type: 'POST',
    data: {userid: $.trim($('#userid').val())},
    success: function(data) {
        console.log(data);

        if (result.indexOf("not valid")) {
            ("#mustbevalid").val("You must validate your phone number");
            console.log("Phone hasn't been validated");
            e.preventDefault();
        };
    }
});

Your help is highly appreciated.

1
  • if(data=="valid") would seem more logical than if(result.indexOf("not valid")) ... result is undefined. Commented Mar 17, 2015 at 17:17

2 Answers 2

1

You're checking result.indexOf, but your response data is in data not result. Additionally, indexOf returns the position, which could be 0. So change to:

if(data.indexOf("not valid") > -1) {

Side note: this method of checking a result is error-prone and usually undesirable. It would be better for you to output a JSON object with a success property.

Example success response:

echo json_encode(array('success' => true));
// Outputs: {"success":true}

Example error response:

echo json_encode(array('success' => false));
// Outputs: {"success":false}

Now, you can parse the JSON:

$.ajax({
    ...
    dataType : 'json', // <-- tell jQuery we're expecting JSON
    success: function(data) {
        if (data.success) {
            // success
        } else {
            // error
        };
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

indexOf will return the position in the string. So use this instead:

if(data.indexOf("not valid") == 0) 

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.