shibbir ahmed shibbir ahmed - 5 months ago 9
jQuery Question

Why jQuery return data is not working as expected?

In my webpage I am using jQuery/Ajax to save form data. After save the data using php I am showing successful message like bellow :

if($sql){
$sql_result[] = "<div class='success'>updated</div>";
}

echo end($sql_result);


In Ajax return data I am checking a condition if message is contain
updated
then I will hide a html element but It's not working.

Here is my jQuery code:

function save_email (element, event) {

e = $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);

$.ajax({
data : formData,
cache : false,
contentType: false,
processData : false,

url : 'save_email.php',
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success : function (data) {
$("#email_success").html(data);
//$("#email_success").show('slow').delay(3000).hide('slow');
if(data == "<div class='success'>updated</div>" ) {
$("#save_email_button").hide('slow');
$(".delete_ex_email_label").hide('slow');
}
},
});
}


Console log data

enter image description here

Updated:

alert(data)
is showing this :

enter image description here

Answer

It's not uncommon to end up with extra whitespace in php text/html output

That is one reason it's easier to use json and check object properties , especially over comparing a complex string like you are doing.

However using trim() when comparing string results is generally a good idea

try

$.trim(data) === "<div class='success'>updated</div>")