Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if ajax response contains specific value

Tags:

jquery

ajax

How can you check to see whether the returned results contain a specific value?

$(function () {
    $('form').submit(function (e) {
        e.preventDefault();
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {

               //here i wanna check if the result return contains value "test"
               //i tried the following..
                 if($(result).contains("test")){
                 //do something but this doesn't seem to work ...
                 }

                }
            },
        });
    });
});
like image 495
Raju Kumar Avatar asked Nov 28 '22 14:11

Raju Kumar


2 Answers

Array.prototype.indexOf()

if(result.indexOf("test") > -1)

Since this still gets up votes I'll edit in a more modern answer.

With es6 we can now use some more advanced array methods.

Array.prototype.includes()

result.includes("test") which will return a true or false.

Array.prototype.some()

If your array contains objects instead of string you can use

result.some(r => r.name === 'test') which will return true if an object in the array has the name test.

like image 168
Kolby Avatar answered Dec 09 '22 19:12

Kolby


The jQuery object does not have a contains method. If you are expecting the returned result to be a string, you can check if your substring is contained within it:

if ( result.indexOf("test") > -1 ) {
    //do something
}

If your result is JSON, and you're checking for a top-level property, you can do:

if ( result.hasOwnProperty("test") ) {
    //do something
}
like image 20
nbrooks Avatar answered Dec 09 '22 19:12

nbrooks