Chris Cates
Chris Cates

Reputation: 75

PHP - Sending a javascript variable over to a .PHP script

So, not entirely sure if this is correct, but, here is my php doc: connect.php

  <?php
mysql_connect("timereliefusers.db.8956371.hostedresource.com", "timereliefusers", "User1!db") or die(mysql_error());
mysql_select_db("timereliefusers") or die (mysql_error());


    $choice =(int) $_GET["choice"];

    switch ($choice) {
        case 1:
        mysql_query("UPDATE poll1 set choice1 = choice1 + 1");
        break;
        case 2:
        mysql_query("UPDATE poll1 set choice2 = choice2 + 1");
        break;
        case 3:
        mysql_query("UPDATE poll3 set choice3 = choice3 + 1");
        break;
    }
}

?>

Then, I send an AJAX request to the php doc here:

$(document).ready(function(){       
    var choice = 0;

    $("#s1main div").click(function(){
        $("#s1main div").removeClass("buttonclicked");
        $(this).addClass("buttonclicked");

        if ($(this).attr("id") == "choice1"){
            choice = 1;
        }

        if ($(this).attr("id") == "choice2"){
            choice = 2;
        }

        if ($(this).attr("id") == "choice3"){
            choice = 3;
        }

        xmlhttp.open("GET", "connect.php?choice=" + choice, true);
        xmlhttp.send();
        alert("Variables passed");          

    });

Please tell me of any errors concerning these two documents, thank you - Chris

NOTE: This doesn't get past the alert("variables passed"); for some odd reason, could someone explain as to why that happens? There must be something wrong with the AJAX call.

Upvotes: 0

Views: 182

Answers (1)

Mike L.
Mike L.

Reputation: 1966

Looks like you never send choice to your script...you should do something like this:

PHP:

<?php

mysql_connect("db.host", "username", "password") or die(mysql_error());
mysql_select_db("timereliefusers") or die (mysql_error());


$choice = (int) $_GET["choice"];

switch ($choice) {
    case 1:
    mysql_query("UPDATE poll1 set choice1 = choice1 + 1");
    break;
    case 2:
    mysql_query("UPDATE poll1 set choice2 = choice2 + 1");
    break;
    case 3:
    mysql_query("UPDATE poll3 set choice3 = choice3 + 1");
    break;
}
?>

JAVASCRIPT

$("#next").click(function(){
    if (choice != 0) {
            xmlhttp.open("GET", "connect.php?choice=" + choice, true);
            xmlhttp.send();
        }
    });

Upvotes: 1

Related Questions