Serializing and Submitting a Form Using jQuery and PHP
Problem: Attempting to send a form's data using jQuery results in no data reaching the server.
HTML Form:
<code class="html"><form id="contactForm" name="contactForm" method="post"> <!-- Input fields and textarea --> <input id="submitBtn" type="submit" name="submit" value="Trimite"> </form></code>
JavaScript (jQuery):
<code class="javascript">$(document).ready(function(e) { $("#contactForm").submit(function() { $.post("getcontact.php", $("#contactForm").serialize()) .done(function(data) { if (data.trim().length > 0) { $("#sent").text("Error"); } else { $("#sent").text("Success"); } }); return false; }) });</code>
PHP (getcontact.php):
<code class="php">$nume = $_REQUEST["nume"]; // Empty $email = $_REQUEST["email"]; // Empty $telefon = $_REQUEST["telefon"]; // Empty $comentarii = $_REQUEST["comentarii"]; // Empty</code>
Cause:
The issue lies in the use of the $.post() method. By default, jQuery sends data in the application/x-www-form-urlencoded format. However, PHP's $_REQUEST superglobal expects the data to be in the multipart/form-data format for form submissions.
Solution:
One way to fix this is to use the $.ajax() method with the contentType and processData options set to false:
<code class="javascript">var datastring = $("#contactForm").serialize(); $.ajax({ type: "POST", url: "your url.php", data: datastring, contentType: false, processData: false, dataType: "json", // If desired success: function(data) { // Handle success }, error: function() { // Handle error } });</code>
Another option is to use the var_dump($_POST) statement in your PHP script to debug the form submission and determine whether the data is being received properly.
The above is the detailed content of Why is my jQuery form submission not reaching my PHP server?. For more information, please follow other related articles on the PHP Chinese website!