skip to Main Content

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


  1. The obvious reason why your if(data==='no') does not work is that data is not "no". It can be for example "no " (with ending space) or "non", where n 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 last echo, your test.php becomes:

    <?php echo "no";
    
    Login or Signup to reply.
  2. Solution:

    Put a console.log(data) and validate the response.

    Your data has a space “<?php echo "no"; ?> “<— here before quotes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search