Reputation: 601
I apologise if you think this might be a duplicate but I've tried everything I've come across and the problem persists - it's driving me mad!
I basically want to pass a JS variable to a PHP variable whenever a key is hit.
This is a simplified version of how my PHP file is set up (located at http://localhost/quiz/index.php
)
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<head>
<body>
<p>
<?php
$uid = $_POST['userID'];
echo $uid;
?>
</p>
<script src="js/site.js"></script>
</body>
</html>
Then in the site.js file I have the following:
jQuery(document).ready(function($) {
$(document.body)
.keyup(function() {
var userID = "Jim";
$.ajax({
type: "POST",
url: 'http://localhost/quiz/index.php',
data: { userID : userID },
success: function(data)
{
alert("success!");
}
});
});
});
Of course, I am wanting the JS variable userID value ('Jim') to output in the paragraph when a key is pressed, but it only ever shows:
Notice: Undefined index: userID in C:\xampp\htdocs\quiz\index.php on line 66
However, when a key is pressed the "success" alert pops up.
Does anyone know where I'm going wrong here? I'm using Xampp if that's relevant!
Thanks!
Upvotes: 0
Views: 823
Reputation: 943547
You need two PHP files (or one with some branching logic).
You are getting the error because the userID
is not submitted in a POST request to load the initial page.
Then you need to modify your JavaScript so that it does something with data
instead of just alerting.
Upvotes: 2