Home >Backend Development >PHP Tutorial >How to Pass a JavaScript Variable to PHP Using AJAX?
Passing Javascript Variable to PHP via AJAX
Passing data from Javascript to server-side PHP code is essential for interactive web development. One common method for achieving this is through AJAX. To effectively pass a Javascript variable to PHP, follow these steps:
1. Configure the AJAX Call:
Update the Javascript code to correctly format the data being sent to PHP:
<code class="javascript">$.ajax({ type: "POST", url: 'logtime.php', data: { userID : userID }, success: function(data) { alert("success!"); } });</code>
2. Retrieve the Data in PHP:
In your PHP script (logtime.php), access the data using the proper syntax:
<code class="php">if(isset($_POST['userID'])) { $uid = $_POST['userID']; // Perform actions using $uid }</code>
3. Note on isset() Function:
The isset() function in PHP is used to check if a variable exists. In the updated PHP code, it ensures that the 'userID' variable is set in the POST request before assigning it to the $uid variable.
The above is the detailed content of How to Pass a JavaScript Variable to PHP Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!