In this example you will learn, how to AJAX Submit a Form in jQuery. You can simply use the $.post() method in combination with the serialize() method to submit a form using AJAX in jQuery. The serialize() method creates a URL encoded text string by serializing form values for submission. Only “successful controls” are serialized to the string.
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 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery AJAX Submit Form</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script> $(document).ready(function(){ $("form").on("submit", function(event){ event.preventDefault(); var formValues= $(this).serialize(); $.post("process_form.php", formValues, function(data){ // Display the returned data in browser $("#result").html(data); }); }); }); </script> </head> <body> <form> <p> <label>Name:</label> <input type="text" name="name"> </p> <p> <label>Gender:</label> <label><input type="radio" value="male" name="gender"> Male</label> <label><input type="radio" value="female" name="gender"> Female</label> </p> <p> <label>Hobbies:</label> <label><input type="checkbox" value="music" name="hobbies[]"> Music</label> <label><input type="checkbox" value="sports" name="hobbies[]"> Sports</label> <label><input type="checkbox" value="dance" name="hobbies[]"> Dance</label> </p> <p> <label>Favorite Color:</label> <select name="color"> <option>Red</option> <option>Green</option> <option>Blue</option> </select> </p> <p> <label>Comment:</label> <textarea name="comment"></textarea> </p> <input type="submit" value="submit"> </form> <div id="result"></div> </body> </html> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.