Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a php switch case with ajax onclick and have it print the result in an H tag?

I have a page called beslutning.php with a random generator first followed by a switch case.

That page is included in the index file like so:

 <h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" ?></h1>

On a page load it runs the script, match a case and echoes out the result as it's intended.

Here's what I need

A button on the index page which when clicked requests the beslutning.php to be run again so I get a new result.

All my searches on phrases such as execute php script with ajax, run a php script with ajax onclick and a bunch of other alternatives has lead me to no result.

I have tried to fiddle with blocks of codes like the one below but to no luck.

<script>
$(document).ready(function(){
    $("#NyBeslutning").click(function() {
        $.ajax({
            type: "POST",
            url: "beslutning.php", //Your required php page
            data: "$beslutning", //pass your required data here
            success: function(response){
                $('$beslutning').html(response);
            }
        });
    return false;
    });
</script>

<a id="NyBeslutning" class="btn btn-lg btn-default" type="button" onClick="$beslutning()">Ny beslutning</a>

Here's how my beslutning.php looks like:

<?php
$beslutning = mt_rand(0, 1000);

switch($beslutning)
{
case 1:
    echo "something";
    break;

case 2:
    echo "something";
    break;
?>

Someone who can help? Explain it to me like I'm a baby :)

Thanks in advance.

like image 703
JJFDK Avatar asked Dec 12 '25 21:12

JJFDK


1 Answers

You're close, but you have some big problems with your jQuery code. Try to read up on documentation for these things before using them!

You aren't sending any data, so don't need to POST and can just do a simple GET request. In your success function you were referring to $('$beslutning') which isn't anything. Instead you want to refer to your H1 element. And, you'd forgotten closing braces around some code.

On the HTML side, you don't need an onclick attribute, since you're already declaring the click listener in the script. Give this a try, and if it doesn't work, check your browser's error console.

<script>
$(document).ready(function(){
    $("#NyBeslutning").click(function() {
        $.get("beslutning.php", function(response) {
            $('h1.cover-heading').html(response);
        });
    });
});
</script>

<h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" ?></h1>
<button id="NyBeslutning" class="btn btn-lg btn-default">Ny beslutning</button>
like image 51
miken32 Avatar answered Dec 14 '25 11:12

miken32