PHP and jQuery Ajax not doing anything

I made a test page (my first test of PHP) using AJAX and jQuery to call a PHP function in my main document. Unlike all the other answers on how this is done, my PHP and HTML are in the same file (phptest.php). When I click my button to submit a form (this is a really simple test- I click a button and something happens- I KNOW I should have used javascript) I can see in Firebug's panel that the post was sent, yet nothing happens on my page, so I believe it is a problem on the PHP side. Could someone help me out or give me some pointers on why my code is not working? Here it is.

phptest.php

<!DOCTYPE html>
<html>
<head>
    <script src="../jquery/jquery-2.1.4.min.js"></script> <!--jQuery 2 script (used for Ajax, titlebar)--> <!--Note: doesn't work with IE 6/7/8-->
    <script src="../soundmanager/soundmanager2.js"></script>
    <script src="phptest.js"></script>

    <link rel="stylesheet" type="text/css" href="phptest.css">
    <title>PHP Test | Flippy Coin | thisisatest.com</title>
</head>
<body>
    <button type="button" id="clickMe1">Do Thoust Want to Flip the Coin of Flipping?</button>
    <div>
    <?php 
        function wipeCanvas(){}
        function coinFlip(){
            $recentFlip = 0;
            $totalFlips = 0;
            $headsInRow = 0;
            while($headsInRow < 3){
                $recentFlip = rand(0,1);
                if ($recentflip==1){
                    $headsInRow = $headsInRow +1;
                    $totalFlips = $totalFlips +1;
                    echo "<div class="coin">Heads</div>";
                }
                else {
                    $totalFlips = $totalFlips +1;
                    echo "<div class="coin">Tails</div>";
                }
            }
            if ($headsInRow == 3 && $totalFlips <11){
                echo "<p>Hey, we got 3 heads in a row! Wonderful!";

                if ($totalFlips ==3){echo "And on our first try, too! ...wait... 3...       </p><p></p><p>HALF LIFE 3 CONFIRMED!</p>";}
                else {"And it only took us ".$totalFlips." flips!</p>";}
            }
            else if ($headsInRow == 3 && $totalFlips == 21){echo "<p class="bold"> TWENTY-ONE!</p>";}
            else if ($headsInRow == 3 && $totalFlips == 42){
                echo "<p> It is important to note that suddenly, and against all probability, a sperm whale had been called into existence, several miles above the surface of an alien planet. And since this is not a naturally tenable position for a whale, this innocent creature had very little time to come to terms with its identity. This is what it thought, as it fell: " Ahhh! Woooh! What's happening? Who am I? Why am I here? What's my purpose in life? What do I mean by who am I? Okay okay, calm down calm down get a grip now. Ooh, this is an interesting sensation. What is it? Its a sort of tingling in my... well I suppose I better start finding names for things. Lets call it a... tail! Yeah! Tail! And hey, what's this roaring sound, whooshing past what I'm suddenly gonna call my head? Wind! Is that a good name? It'll do. Yeah, this is really exciting. I'm dizzy with anticipation! Or is it the wind? There's an awful lot of that now isn't it? And what's this thing coming toward me very fast? So big and flat and round, it needs a big wide sounding name like 'Ow', 'Ownge', 'Round', 'Ground'! That's it! Ground! Ha! I wonder if it'll be friends with me? Hello, Ground!" Curiously, the only thing that went through the mind of the bowl of petunias, as it fell, was, "Oh no, not again!" Many people have speculated that if we knew exactly *why* the bowl of petunias had thought that we would know a lot more about the nature of the universe than we do now. </p>";
            }
            else if ($headsInRow == 3 && $totalFlips == 420){
                echo "<p>SMOKE WEED EVERYDAY</p>";
            }
            else if ($headsInRow == 3 && $totalFlips < 101){
                echo "<p>Hey, we got 3 heads in a row! It took us ".$totalFlips." flips.</p>";
            }

            else if ($headsInRow == 3 && $totalFlips < 10000){
                echo "<p>Okay, so we got 3 heads in a row, but after ".$totalFlips." times?!? That's just not fair!</p>";
            }
            else if ($headsInRow ==3){
                echo "<p>Nope. Nope, nope, nope. ".$totalFlips." flips. Just... no. Honestly, take a screenshot of this and post it on some message board somewhere. How does this happen? I mean, how does a computer take ".$totalFlips." flips before it gets 3 heads? Seriously? This is just... just... I'm done. Don't bother me again. I'M DONE!</p>";
            } 
        }
        if (isset($_POST['action'])){
            $action = $_POST['action'];
            switch($action) {
                case 'callCoinFlip': coinFlip(); 
                break;
            }
        }
    ?>
    </div>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p>Verdict: <b>PHP is not worth it.</b></p>
</body>
</html>

phptest.js

//   onclick="xmlhttp.open(&quot;GET&quot;,&quot;phptest.php?t=&quot;+ Math.random(), true" <-- Just in case ;)

//jQuery 2 Ajax
$(document).ready(function () {
    var data = {'action': 'callCoinFlip'};
    $("#clickMe1").on('click', function(){

        $.ajax({
            type: "POST",
            url: 'phptest.php',
            dataType: "json",
            data: {'action': 'callCoinFlip'},
            success: function(){
                console.log("pootis");
            }
            //error: function(){
                //console.log("Oh no! There has been a problem.");
            //}
        })
    })
})

You have done two mistakes in your code.

  • In coinFlip() function you added a undefined variable $recentflip . In the above line you declared a variable $recentFlip = rand(0,1); . That means $recentflip and $recentFlip are not equal. In PHP, variables are case sensitive. Check the reference.
  • After the execution of the post request the error function inside the post function will be called not the success function because in the jquery post function added dataType as json means it excepting the php file will return a json string. But the php file will return plain text. So the success function won't called. To know more detail about dataType in post function check this link.
  • After fixing those two issues i added the code below.

    phptest.php

    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <!--jQuery 2 script (used for Ajax, titlebar)--> <!--Note: doesn't work with IE 6/7/8-->
        <!--script src="../soundmanager/soundmanager2.js"></script-->
        <script src="phptest.js"></script>
    
        <!--link rel="stylesheet" type="text/css" href="phptest.css"-->
        <title>PHP Test | Flippy Coin | thisisatest.com</title>
    </head>
    <body>
        <button type="button" id="clickMe1">Do Thoust Want to Flip the Coin of Flipping?</button>
        <div>
        <?php 
            function wipeCanvas(){}
            function coinFlip(){
                $recentFlip = 0;
                $totalFlips = 0;
                $headsInRow = 0;
                while($headsInRow < 3){
                    $recentFlip = rand(0,1);
                    if ($recentFlip==1){
                        $headsInRow = $headsInRow +1;
                        $totalFlips = $totalFlips +1;
                        echo "<div class="coin">Heads</div>";
                    }
                    else {
                        $totalFlips = $totalFlips +1;
                        echo "<div class="coin">Tails</div>";
                    }
                }
                if ($headsInRow == 3 && $totalFlips <11){
                    echo "<p>Hey, we got 3 heads in a row! Wonderful!";
    
                    if ($totalFlips ==3){echo "And on our first try, too! ...wait... 3...       </p><p></p><p>HALF LIFE 3 CONFIRMED!</p>";}
                    else {"And it only took us ".$totalFlips." flips!</p>";}
                }
                else if ($headsInRow == 3 && $totalFlips == 21){echo "<p class="bold"> TWENTY-ONE!</p>";}
                else if ($headsInRow == 3 && $totalFlips == 42){
                    echo "<p> It is important to note that suddenly, and against all probability, a sperm whale had been called into existence, several miles above the surface of an alien planet. And since this is not a naturally tenable position for a whale, this innocent creature had very little time to come to terms with its identity. This is what it thought, as it fell: " Ahhh! Woooh! What's happening? Who am I? Why am I here? What's my purpose in life? What do I mean by who am I? Okay okay, calm down calm down get a grip now. Ooh, this is an interesting sensation. What is it? Its a sort of tingling in my... well I suppose I better start finding names for things. Lets call it a... tail! Yeah! Tail! And hey, what's this roaring sound, whooshing past what I'm suddenly gonna call my head? Wind! Is that a good name? It'll do. Yeah, this is really exciting. I'm dizzy with anticipation! Or is it the wind? There's an awful lot of that now isn't it? And what's this thing coming toward me very fast? So big and flat and round, it needs a big wide sounding name like 'Ow', 'Ownge', 'Round', 'Ground'! That's it! Ground! Ha! I wonder if it'll be friends with me? Hello, Ground!" Curiously, the only thing that went through the mind of the bowl of petunias, as it fell, was, "Oh no, not again!" Many people have speculated that if we knew exactly *why* the bowl of petunias had thought that we would know a lot more about the nature of the universe than we do now. </p>";
                }
                else if ($headsInRow == 3 && $totalFlips == 420){
                    echo "<p>SMOKE WEED EVERYDAY</p>";
                }
                else if ($headsInRow == 3 && $totalFlips < 101){
                    echo "<p>Hey, we got 3 heads in a row! It took us ".$totalFlips." flips.</p>";
                }
    
                else if ($headsInRow == 3 && $totalFlips < 10000){
                    echo "<p>Okay, so we got 3 heads in a row, but after ".$totalFlips." times?!? That's just not fair!</p>";
                }
                else if ($headsInRow ==3){
                    echo "<p>Nope. Nope, nope, nope. ".$totalFlips." flips. Just... no. Honestly, take a screenshot of this and post it on some message board somewhere. How does this happen? I mean, how does a computer take ".$totalFlips." flips before it gets 3 heads? Seriously? This is just... just... I'm done. Don't bother me again. I'M DONE!</p>";
                } 
            }
            if (isset($_POST['action'])){
                $action = $_POST['action'];
    
                switch($action) {
                    case 'callCoinFlip': coinFlip(); 
                    break;
                }
            }
        ?>
        </div>
        <p></p>
        <p></p>
        <p></p>
        <p></p>
        <p>Verdict: <b>PHP is not worth it.</b></p>
    </body>
    </html>
    

    phptest.js

    //   onclick="xmlhttp.open(&quot;GET&quot;,&quot;phptest.php?t=&quot;+ Math.random(), true" <-- Just in case ;)
    
    //jQuery 2 Ajax
    $(document).ready(function () {
        var data = {'action': 'callCoinFlip'};
        $("#clickMe1").on('click', function(){
    
            $.ajax({
                type: "POST",
                url: 'phptest.php',
                data: {'action': 'callCoinFlip'},
                success: function(){
                    console.log("pootis");
                }
                //error: function(){
                    //console.log("Oh no! There has been a problem.");
                //}
            })
        })
    })
    

    To show the response in the html page

    I thought after successful execution of the code you need to append the result in the html. So I added a code below which will append the result in the html. You must try the below code .

    phptest.php

    <?php 
        function wipeCanvas(){}
        function coinFlip(){
            $recentFlip = 0;
            $totalFlips = 0;
            $headsInRow = 0;
            while($headsInRow < 3){
                $recentFlip = rand(0,1);
                if ($recentFlip==1){
                    $headsInRow = $headsInRow +1;
                    $totalFlips = $totalFlips +1;
                    echo "<div class="coin">Heads</div>";
                }
                else {
                    $totalFlips = $totalFlips +1;
                    echo "<div class="coin">Tails</div>";
                }
            }
            if ($headsInRow == 3 && $totalFlips <11){
                echo "<p>Hey, we got 3 heads in a row! Wonderful!";
    
                if ($totalFlips ==3){echo "And on our first try, too! ...wait... 3...       </p><p></p><p>HALF LIFE 3 CONFIRMED!</p>";}
                else {"And it only took us ".$totalFlips." flips!</p>";}
            }
            else if ($headsInRow == 3 && $totalFlips == 21){echo "<p class="bold"> TWENTY-ONE!</p>";}
            else if ($headsInRow == 3 && $totalFlips == 42){
                echo "<p> It is important to note that suddenly, and against all probability, a sperm whale had been called into existence, several miles above the surface of an alien planet. And since this is not a naturally tenable position for a whale, this innocent creature had very little time to come to terms with its identity. This is what it thought, as it fell: " Ahhh! Woooh! What's happening? Who am I? Why am I here? What's my purpose in life? What do I mean by who am I? Okay okay, calm down calm down get a grip now. Ooh, this is an interesting sensation. What is it? Its a sort of tingling in my... well I suppose I better start finding names for things. Lets call it a... tail! Yeah! Tail! And hey, what's this roaring sound, whooshing past what I'm suddenly gonna call my head? Wind! Is that a good name? It'll do. Yeah, this is really exciting. I'm dizzy with anticipation! Or is it the wind? There's an awful lot of that now isn't it? And what's this thing coming toward me very fast? So big and flat and round, it needs a big wide sounding name like 'Ow', 'Ownge', 'Round', 'Ground'! That's it! Ground! Ha! I wonder if it'll be friends with me? Hello, Ground!" Curiously, the only thing that went through the mind of the bowl of petunias, as it fell, was, "Oh no, not again!" Many people have speculated that if we knew exactly *why* the bowl of petunias had thought that we would know a lot more about the nature of the universe than we do now. </p>";
            }
            else if ($headsInRow == 3 && $totalFlips == 420){
                echo "<p>SMOKE WEED EVERYDAY</p>";
            }
            else if ($headsInRow == 3 && $totalFlips < 101){
                echo "<p>Hey, we got 3 heads in a row! It took us ".$totalFlips." flips.</p>";
            }
    
            else if ($headsInRow == 3 && $totalFlips < 10000){
                echo "<p>Okay, so we got 3 heads in a row, but after ".$totalFlips." times?!? That's just not fair!</p>";
            }
            else if ($headsInRow ==3){
                echo "<p>Nope. Nope, nope, nope. ".$totalFlips." flips. Just... no. Honestly, take a screenshot of this and post it on some message board somewhere. How does this happen? I mean, how does a computer take ".$totalFlips." flips before it gets 3 heads? Seriously? This is just... just... I'm done. Don't bother me again. I'M DONE!</p>";
            } 
        }
        if (isset($_POST['action'])){
            $action = $_POST['action'];
    
            switch($action) {
                case 'callCoinFlip': coinFlip(); 
                break;
            }
        }else{
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <!--jQuery 2 script (used for Ajax, titlebar)--> <!--Note: doesn't work with IE 6/7/8-->
        <!--script src="../soundmanager/soundmanager2.js"></script-->
        <script src="phptest.js"></script>
    
        <!--link rel="stylesheet" type="text/css" href="phptest.css"-->
        <title>PHP Test | Flippy Coin | thisisatest.com</title>
    </head>
    <body>
        <button type="button" id="clickMe1">Do Thoust Want to Flip the Coin of Flipping?</button>
        <div id="response">
        </div>
        <p class="verdict">Verdict: <b>PHP is not worth it.</b></p>
    </body>
    </html>
    <?php } ?>
    

    phptest.js

    //   onclick="xmlhttp.open(&quot;GET&quot;,&quot;phptest.php?t=&quot;+ Math.random(), true" <-- Just in case ;)
    
    //jQuery 2 Ajax
    $(document).ready(function () {
        var data = {'action': 'callCoinFlip'};
        $("#clickMe1").on('click', function(){
    
            $.ajax({
                type: "POST",
                url: 'phptest.php',
                data: {'action': 'callCoinFlip'},
                success: function(response, status){
                    console.log("pootis");
                    $("#response").html(response);
                    $(".verdict").append("<br/>Accusation:<b id="accusation" style="color:red"><blink>PHP is worth more that what you think. Please improve your skills first.</blink></b>");
    
                    window.setInterval(function() {
                    $('#accusation').toggle();
                    }, 500);
                }
                //error: function(){
                    //console.log("Oh no! There has been a problem.");
                //}
            })
        })
    })
    

    Instead of

     success: function(){
                console.log("pootis");
            }
    

    Try:

     success: function(response){
                console.log(response);
            }
    

    You should see the server response. But you never do anything with it, you should append to the page with something like:

     success: function(response){
                $('body').append(response);
            //    console.log(response);
            }
    

    Edit, that said you'll end up appending things that you dont need such as the scripts etc, its probably advisable to put your coinflip function in a separate php file


    或尝试这一个

        
    
        $(document).ready(function () {
        $('#clickMe1').click(function(e) {
                $.ajax({
                type:'POST', 
                url: 'phptest.php', 
                data: {'action':'callCoinFlip'}, 
    
                    success: function(response) {
                        $('#result').html(response); 
                    }
                });
                return false;        
        });
    });
    
    
    链接地址: http://www.djcxy.com/p/46164.html

    上一篇: jQuery的Ajax不发送JSON数据

    下一篇: PHP和jQuery Ajax没有做任何事情