Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: If statement not working inside ajax success function

Tags:

jquery

ajax

I have a success function in my AJAX which returns the response text from a python script which can be either "SUCCESS" or "EMPTY". Now I want to place an if-loop inside the success function, but the if-loop is not working. I am getting the correct data from my python script because my alert statement is working fine and printing "SUCCESS". But it does not enter the ifloop

I have tried a bunch of things but the control is not entering the if-loop, could anyone please tell me what I am doing wrong:

submitHandler: function (form) {

                $.ajax({
                    type: 'post',
                    url: '/cgi-bin/getdataworld.py',
                    data: $(form).serialize(),

                    success: function(data) {
                            //document.write(result);
                            console.log("result is "+data);
                            alert(data);

                            if(data === "SUCCESS"){
                            window.location = 'index.html';
                               }
                           else{
                                 alert("NO DATA PRESENT");
                               }


                    },

                    error: function (responseData) {
                console.log('Ajax request not recieved!');
            }

                });

                return false;
            }
like image 576
wanab_geek Avatar asked Jul 17 '13 21:07

wanab_geek


1 Answers

This means that what you're responding with isn't "SUCCESS". It probably has a line break or other whitespace before or after it, maybe more than one.

Perhaps:

if (/^\s*SUCCESS\s*$/.test(data)) {
    // Success
}

Or use jQuery's $.trim:

if ($.trim(data) === "SUCCESS") {
    // Success
}

Also be sure that you're not replying with "Success" or "success", as string comparisons are case-sensitive.

If you're not sure:

if (/^\s*SUCCESS\s*$/i.test(data)) {
    // Success
}

or

if ($.trim(data).toUpperCase() === "SUCCESS") {
    // Success
}
like image 188
T.J. Crowder Avatar answered Sep 24 '22 01:09

T.J. Crowder