You need to understand how pages are constructed. PHP is a server side language, that means that all the PHP is executed prior to being sent to the client (i.e. the persons browser). Your PHP is parsed and what is sent to the client is:
<script>
$(document).ready(function(){
var my_name = 'Jack Goodman';
alert(my_name);
});
</script>
That is then executed on the client's PC. The PHP has completely finished, there is no way for the client to change the value of the PHP variable, it doesn't exist any more. The only way to pass information from the client to the server is to open a new connection (e.g. a new page) and set the information you want to send to the server as a GET or POST variable.
Imagine going to a page on your website, you enter a URL in the browser such as http://www.mywebsite.com
. We can include variable information by using GET variables, so if we wanted to pass the name in it would be something like http://www.mywebsite.com?name=My%20Name
(%20
is a space). In your PHP you can then access this using the $_GET
superglobal, e.g. $name = $_GET['name']
and use it as you need.
So if you have some information you need sending to the server, traditionally you would use a form:
<form action="mypage.php" method="get" id="myform">
<input type="text" name="name" id="myname" value="Jack Goodman">
<button type="submit">Submit</button>
</form>
However you can also send data asynchronously using AJAX. That means we don't have to open a new page, or submit a form to send data to the server. AJAX allows us to send some data to the server and read its response. So to send the name variable we can use jQuery's AJAX plugin.
// We intercept the submission of the form
$('#myform').submit(function () {
$.ajax({
url: 'mypage.php',
type: 'GET',
dataType: 'JSON',
data: { name: $('#myname').val() }
}).success(function (response) {
alert(response);
});
return false; // This stops the form submitting so the page doesn't reload.
});
response
will contain whatever the PHP page outputs. So if your PHP page looked like this:
<?php
$name = $_GET['name'];
// ... do something with $name
$response = ['result' => 'success', 'name' => $name];
echo json_encode($response);
We're passing back a JSON string, so response
will contain that JSON string. However because we know that it's a JSON string and we tell jQuery to expect a JSON string response (by using dataType: 'JSON'
) jQuery will automatically convert that to an object for us, so response
contains an object with the properties result and name.