To get Ajax data in PHP on the same page, you can do the following:
- Create an HTML form with an input field that will be used to send data to the server.
- Create a PHP script that will handle the data sent by the form and return a response to the client.
- Create a Javascript function that will use Ajax to send the form data to the server and handle the response.
Here's an example implementation:
<!-- HTML form --><form id="myForm"><input type="text" name="myData"><button type="submit" id="submitBtn">Submit</button></form>
<!-- Javascript code using jQuery --><script>$(function() {$('#myForm').submit(function(e) {e.preventDefault(); // prevent form from submitting normallyvar formData = $(this).serialize(); // get form data$.ajax({url: 'myPhpScript.php',type: 'POST',data: formData,success: function(response) {// handle response from serverconsole.log(response);}});});});</script>
<!-- PHP script (myPhpScript.php) --><?phpif ($_SERVER['REQUEST_METHOD'] === 'POST') {$myData = $_POST['myData'];// do something with $myData// return response to clientecho 'Data received: ' . $myData;}?>
In this example, when the form is submitted, the `submit()` function is called, which prevents the form from submitting normally and sends the form data to the PHP script using Ajax. The PHP script receives the data sent by the form using the `$_POST` superglobal array, processes the data, and returns a response to the client. The response is then handled by the `success` function in the Ajax call and logged to the console.