Home >Backend Development >PHP Tutorial >Why Doesn't My $.load() Submit Form Data, and How Can I Use AJAX Instead?
Form Data Not Submitting via $.load
Question:
A button click triggers the following code, but its post request fails to reach the intended PHP file (MonsterRequest.php) when executed through a $.load call. The page reloads instead, limiting the ability to submit data without reloading.
Answer:
To facilitate data posting without page reloading, it's essential to understand AJAX. AJAX processes data by sending it to an external PHP file, which responds with a result.
Implementation:
In the first file, attach a change event handler to the relevant element to capture the selected option. The data is then sent via an AJAX POST request to the second file. If successful, the returned data is displayed in an alert.
File 1:
<script> $(document).ready(function() { $('#Sel').change(function() { var opt = $(this).val(); $.ajax({ type: "POST", url: "receiving_file.php", data: 'selected_opt=' + opt, success:function(data){ alert('This was sent back: ' + data); } }); }); }); </script>
File 2: receiving_file.php
$recd = $_POST['selected_opt']; echo 'You chose: ' . $recd;
The above is the detailed content of Why Doesn't My $.load() Submit Form Data, and How Can I Use AJAX Instead?. For more information, please follow other related articles on the PHP Chinese website!