I refer to this question:
Javascript value to PHP with Jquery
I tried with below code in file named a.php:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
var ms = 9000;
function test()
{
$.ajax({ url: "a.php",
data: {"test":ms},
type: 'get',
success: function(output) {
$('#testing').html(output);
}
});
}
test();
</script>
<?php
$ms = $_GET["test"];
echo "I am getting below value:";
echo $ms;
?>
Then I point browser to http://localhost/learn/a.php but got error message & value of $ms is not shown as expected:
( ! ) Notice: Undefined index: test in
C:\wamp\www\learn\a.php on line 17$ms = $_GET[“test”]; <– The line 17
in a.php
I tried another simpler code (b.php) below:
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
var ms = 3000;
$.get("http://localhost/learn/b.php", { "test": ms } );
</script>
<?php
$ms = $_GET["test"];
echo $ms;
?>
Then I point browser to http://localhost/learn/b.php but got similar error message & no value of $ms displayed:
( ! ) Notice: Undefined index: test in
C:\wamp\www\learn\b.php on line 7
Below is code of line 7
$ms = $_GET[“test”];
Please advice. Thanks.
OK, looking at this code:
I’m presuming that this is all in one file. You have two bits of code in two different languages that are interpreted in different places. First, you have the Javascript at the top. This is not interpreted by your server. It is returned to the browser just as HTML is.
Later, you have a piece of PHP. We’re still on the server, and haven’t sent anything to the browser yet. You look for a
$_GET['test']value. Your URL washttp://localhost/learn/b.php: plainly there are no GET values in that URL, hence the error.When your code is sent to the browser, the browser sees the line
$.getand does an AJAX request. This is another HTTP request. It does not modify the original request, so it doesn’t mitigate the error you received above. With this request, your browser will sendhttp://localhost/learn/b.php?test=3000to the server, and there won’t be an error. However, because you’re not doing anything with the response, you aren’t seeing the effects of this second request.