I feel like I’m making a really obvious mistake. Please bear with me, I just started learning jquery and ajax.
Basically, I think something’s wrong with my if statement. Everything else is working properly: ajax was called successfully and the value of the data returned was “no”. However, as soon as I put in the if statement, all the commands in the if statement fail to run. What am I doing wrong?
Html:
<button class='clicky'>Click Me</button>
<section class='modal'>
<p>Some text</p>
</section>
<script>
$(document).ready(function(){
$(".clicky").on('click', function(){
$.ajax({
url: "indexFunct.php",
type: "POST",
success: function(data){
//alert with data if successfully called ajax; showed data = "no"
//alert(data);
//does not alert with data if code for alert is inside if statement
if(data==='no')
{
alert(data);
}
},
error: function(er){
alert('error');
}
})
});
});
</script>
test.php:
<?php echo "no"; ?>
2
Answers
The obvious reason why your
if(data==='no')
does not work is thatdata
is not"no"
. It can be for example"no "
(with ending space) or"non"
, wheren
is newline.Why you get space or newline in the output? Because you have them in your php-file.
What to do? Manually remove them.
If your php file is consist only of php-code, you can omit closing
?>
so as not to output anything after lastecho
, your test.php becomes:Solution:
Your data has a space “
<?php echo "no"; ?>
“<— here before quotes