-2

I try to pass a JavaScript variable to php via Ajax so then I can make sql query. I call function votepick(id ) onchange event. However not working and get error Uncaught ReferenceError: $ is not defined.

html code:

</tr><select onchange="votepick('1')" name="vote1" id="1"> <option selected disabled>Vote here</option> <option value="0">00 vote</option> <option value="1">01 vote</option> <option value="2">02 vote</option> <option value="3">03 vote</option> <option value="4">04 vote </option> <option value="5">05 vote </option> <option value="6">06 vote</option> <option value="7">07 vote</option> <option value="8">08 vote </option> <option value="9">09 vote</option> <option value="10">10 vote</option> </select> </td> <td><?php include 'phpexample.php';?></td>

javaScript file:

function votepick(id){ var x = document.getElementById(id).value; //alert(x); $.ajax({ type: "POST", url: 'phpexample.php', data: {voteid: x }, success: function(data) { alert("success! X:" + data); }
}); }

php file:

<?php if (isset($_GET['voteid'])) { $x = $_GET['voteid']; echo $x; echo "ok"; }else{ echo 'no variable received'; } ?>

2
  • After var x = document.getElementById(id).value (before the AJAX call) does X have the expected value? May 3, 2014 at 14:29
  • Yes, i have checked with alert.
    – gek
    May 3, 2014 at 14:44

1 Answer 1

1

I assume you're getting this error in your JavaScript code.

This is because you're using a jQuery function but haven't included the jQuery library.

You can include it by putting the following line in the <head> section of your HTML file:

<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
15
  • Thanks,however no variable received... any idea?
    – gek
    May 3, 2014 at 14:07
  • In your JavaScript you send data using POST and in PHP you retrieve data using GET. What's the difference? So, you should change $_GET to $_POST in your PHP file. May 3, 2014 at 14:11
  • Yes,thanks again, but nothing,no variable received again....
    – gek
    May 3, 2014 at 14:24
  • Well, you're not showing the returned data anywhere, so how can you be sure? You can change alert("success!"); to alert("success! X: " + data); to display the data the PHP script is returning. May 3, 2014 at 14:44
  • 1
    I don't think you fully understand what AJAX does. Basically, you call the PHP script (optionally with some data, like the selected vote count in your case), the PHP script will process this request (you can do anything here, like use the vote count to insert x votes in your database) and return some data (for example "vote succesful" using echo) to your JavaScript. This return value is stored in the data var in JavaScript. You can use JavaScript to display it in your HTML page. The PHP script has executed, so the data is gone. By including it you won't get the same data. May 3, 2014 at 15:42

Not the answer you're looking for? Browse other questions tagged .