使用JQuery滑块运行服务器端PHP

I've been looking into a new project to further learn PHP after finishing the codecademy course... However, I've run into a dead end and I think it has to do with the AJAX-part of it, but can't figure out what/where and how it's going wrong.

The Code:

<html>
    <head>
        <meta charset="utf-8">
        <script src="https://cdn.jsdelivr.net/jquery/1.11.3/jquery.min.js"></script>
        <link href="https://cdn.jsdelivr.net/jquery.roundslider/1.3/roundslider.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/jquery.roundslider/1.3/roundslider.min.js"></script>
    </head>
    <body>
        <div id="slider"></div>
        <!-- I use the roundsliderui documentation for this: http://roundsliderui.com/ -->
        <script type="text/javascript">
            $("#slider").roundSlider({
                radius: 80,
                min: 0,
                max: 360,
                width: 9,
                startAngle: -90,
                handleSize: "+8",
                sliderType: "min-range",
                value: 180
          });

            $("#slider").on("drag", function (e) {
                var heading = e.value;
                $.post( "quicktest.php", {send: heading});
                console.log(heading);})
        </script>

        <?php
            function show(){
                $course= $_POST["send"];
                echo "Heading is: ".$course;
            } if (isset($_POST["send"])){
                show();}
        ?>
    </body>
</html>

What I'm trying to do is display a round slider on a php-page called quicktest.php. On draggin the slider, the page should update using the php function called show(). For this I use the echo statement.

What happens is the following:

  • Post works: In the developper console of chrome I see that the correct value gets send to the localhost and see a status of 200.
  • When I look in the Developer console > Network > Preview: I see that the page gets updated correctly.
  • However, the page in my browser remains unchanged.

All of this leads me to think I did something wrong with AJAX; but like I said, I can't pinpoint the error.

This is because you can't use PHP this way. PHP is evaluated on the server before gets to the browser.

The way you would do something like this is to use javascript for it. One way would be to use jQuery's after():

$("#slider").on("drag", function (e) {
    var heading = e.value;

    $('#slider').after("<p>Heading course is: " + heading + "</p>")

    $.post("quicktest.php", {send: heading});
    console.log(heading);
})

Alternatively, if you don't want the message to be displayed until after you ajax request has finished you could do:

$("#slider").on("drag", function (e) {
    var heading = e.value;

    $.post("quicktest.php", {send: heading}, function () {
        $('slider').after("<p>Heading course is: " + heading + "</p>")
    });
})

Hope this helps!