Home > Article > Backend Development > Why is my jQuery serialized form data not reaching the PHP server?
Serializing and Submitting a Form with jQuery and PHP
Issue: Despite serializing form data using jQuery, data is not reaching the server.
HTML Form:
<code class="html"><form id="contactForm" name="contactForm" method="post"> <input type="text" name="nume" size="40" placeholder="Nume"> <input type="text" name="telefon" size="40" placeholder="Telefon"> <input type="text" name="email" size="40" placeholder="Email"> <textarea name="comentarii" cols="36" rows="5" placeholder="Message"></textarea> <input id="submitBtn" type="submit" name="submit" value="Trimite"> </form></code>
JavaScript:
<code class="javascript">$("#contactForm").submit(function(e) { e.preventDefault(); // Prevent browser submission $.post("getcontact.php", $("#contactForm").serialize()) .done(function(data) { // Process server response }); });</code>
Server-Side PHP (getcontact.php):
<code class="php">$nume = $_POST["nume"]; $email = $_POST["email"]; $telefon = $_POST["telefon"]; $comentarii = $_POST["comentarii"];</code>
Problem Resolution:
The issue arises from using the transport method option in $.post() (deprecated in jQuery 3.0). Instead, use $.ajax() with the following settings:
<code class="javascript">$.ajax({ type: "POST", url: "getcontact.php", data: $("#contactForm").serialize(), dataType: "json", success: function(data) { // Process server response }, error: function() { // Handle errors } });</code>
In this updated code:
The above is the detailed content of Why is my jQuery serialized form data not reaching the PHP server?. For more information, please follow other related articles on the PHP Chinese website!