June 12, 2016
How to Insert Data Using jQuery & Ajax serialize Method in PHP

Hi, friends in this tutorial I show you how to insert data using jQuery & Ajax serialize Method in PHP without page refresh. jQuery provides a very useful function jQuery.serialize() which encodes a collection of form elements as a string for submission and is very valuable while we are dealing with large form values. Essentially, it will combine your form values and then you can store values in the MySql Database.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<!DOCTYPE html> <html> <head> <title>How to Insert Data Using jQuery & Ajax serialize Method in PHP</title> </head> <body> <br/> <br /> <h3>How to Insert Data Using jQuery & Ajax serialize Method in PHP</h3> <br /> <form id="insert_data"> <label>Name</label> <input type="text" name="name" id="name" /> <br/> <br/> <label>Age</label> <input type="text" name="age" id="age" /> <br/> <br/> <label>Email</label> <input type="text" name="email" id="email" /> <br/> <br/> <input type="button" name="submit" id="submit" value="Submit" /> </form> <div id="return"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(document).ready(function() { $('#submit').click(function() { var name = $('#name').val(); var age = $('#age').val(); var email = $('#email').val(); if (name == '' || age == '' || email == '') { $('#return').html('<h4 style="color:red;">Required All Fields..</h4>'); } else { $.ajax({ url: "insert.php", method: "POST", data: $('#insert_data').serialize(), success: function(data) { $('form').trigger("reset"); $('#return').fadeIn().html(data); setTimeout(function() { $('#return').fadeOut("slow"); }, 6000); } }); } }); }); </script> </body> </html> |
insert.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $conn = mysqli_connect("localhost", "root", "", "test"); if(isset($_POST["name"])) { $name = mysqli_real_escape_string($conn, $_POST["name"]); $age = mysqli_real_escape_string($conn, $_POST["age"]); $email = mysqli_real_escape_string($conn, $_POST["email"]); $query = "INSERT INTO infomatic(name, age, email) VALUES ('".$name."', '".$age."', '".$email."')"; if(mysqli_query($conn, $query)) { echo '<p style="color:green;">Data Inserted Successfully..</p>'; } else { echo '<p>Data Insertion Failed..</p>'; } } ?> |
Download
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]