Jquery: If statement does not work inside ajax success function

I have a success function in my AJAX that returns the response text from a python script, which can be either “SUCCESS” or “EMPTY”. Now I want to place the if-loop inside the success function, but the if-loop does not work. I get the correct data from my python script because my warning statement works fine and prints "SUCCESS". But he is not included in ifloop

I tried a bunch of things, but the control is not included in the if-loop, can someone tell me what I'm 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; } 
+4
source share
3 answers

This means that what you answer is not "SUCCESS" . It probably has a line break or other spaces before or after it, possibly more than one.

May be:

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

Or use jQuery $.trim :

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

Also make sure that you do not respond to "SUCCESS" or "SUCCESS" , as string comparisons are "SUCCESS" .

If you are not sure:

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

or

 if ($.trim(data).toUpperCase() === "SUCCESS") { // Success } 
+8
source

check if there are any additional spaces before / after "SUCCESS"

Also try changing

 if(data === "SUCCESS"){ 

to

 if(data == "SUCCESS"){ 
0
source
 submitHandler: function (form) { $.ajax({ type: 'post', url: '/cgi-bin/getdataworld.py', data: $(form).serialize(), success: function(data1) { //document.write(result); console.log("result is "+data1); alert(data1); if(data1 == "SUCCESS"){ window.location = 'index.html'; } else{ alert("NO DATA PRESENT"); } }, error: function (responseData) { console.log('Ajax rariequest not recieved!'); } }); return false; } 

try here two things that I noticed: === in if statement and the other you use the data as a variable for some time your conflicts in some browser

-one
source

Source: https://habr.com/ru/post/1491975/


All Articles