Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP + Jquery - pass value through ajax to php and check against variable

Tags:

jquery

ajax

php

I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.

This is the code I've written:

<?php
$score = "1";

$userAnswer = $_POST['name'];

if ($_POST['name'] == "145"){
    $score++;
}else{
    //Do nothing
}

echo $score;

?>


<script type="text/javascript">

$(document).ready(function() {

    $("#raaagh").click(function(){

    var value = "145";

    alert(value);

    $.ajax({
        url: 'processing.php', //This is the current doc
        type: "POST",
        data: ({name: value}),
        success: function(){
            location.reload();
       }
    });


    });
});

</script>

<p id="raaagh">Ajax Away</p>

Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.

like image 406
Richard Avatar asked Dec 02 '22 04:12

Richard


2 Answers

First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.

I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.

// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)

<?php
$score = "1";    
$userAnswer = $_POST['name'];    
if ($_POST['name'] == "145"){
    $score++;
}       
echo $score;    
?>

// test.html

<script type="text/javascript">  
$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: 145}),
            success: function(data){
                // Why were you reloading the page? This is probably your bug
                // location.reload();

                // Replace the content of the clicked paragraph
                // with the result from the ajax call
                $("#raaagh").html(data);
            }
        });        
    });
});

</script>

<p id="raaagh">Ajax Away</p>
like image 142
Juan Mendes Avatar answered Jan 25 '23 11:01

Juan Mendes


You use POST in your jQuery, but you try and get a GET in you php.

BTW it is good practice to check if a GET/POST variable is set before reading it. using the isset() function.

like image 45
yossi Avatar answered Jan 25 '23 09:01

yossi