Reputation: 12190
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.
Upvotes: 0
Views: 177
Reputation: 64526
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
};
}
});
Upvotes: 1
Reputation: 30
indexOf will return the position in the string. So use this instead:
if(data.indexOf("not valid") == 0)
Upvotes: 0