Home > Article > Web Front-end > How to Correctly Post Form Data Within $.load Using AJAX?
Using AJAX to Correct Form Posting Within $.load
When attempting to post data from a form within an $.load call, you may encounter an issue where the post is not properly sent to the target PHP script. This can lead to the page reloading instead of processing the submitted data.
To resolve this, consider implementing AJAX. AJAX allows you to send data to a server-side PHP file without reloading the page. Here's how it works:
FILE #1:
This file contains the HTML and JavaScript code for the form.
<html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#Sel').change(function() { var opt = $(this).val(); var someelse = 'Hello'; var more_stuff = 'Goodbye'; $.ajax({ type: "POST", url: "receiving_file.php", data: 'selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff, success:function(data){ alert('This was sent back: ' + data); } }); }); }); </script> </head> <body> <select id = "Sel"> <option value ="Song1">default value</option> <option value ="Song2">Break on through</option> <option value ="Song3">Time</option> <option value ="Song4">Money</option> <option value="Song5">Saucerful of Secrets</option> </select> </body> </html>
FILE #2: receiving_file.php
This file is the PHP script that will process the submitted data.
$recd = $_POST['selected_opt']; echo 'You chose: ' . $recd;
This method ensures that the form data is posted without reloading the page, allowing you to process the data and respond appropriately.
The above is the detailed content of How to Correctly Post Form Data Within $.load Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!