Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jquery $.post() method to submit form values [duplicate]

I have 1 main page with a form and another page to process the form value here are source codes of the 2 pages

Form Page:

<meta charset="UTF-8"> <title>Form Page</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="process.php" method="post" id="reg-form">         Username: <input type="text" id="username" name="username">         <br>         Password: <input type="password" id="password" name="password">         <br>         <button type="submit" id="submit-btn">Traditional Submit</button>         <button type="button" id="post-btn">$.Post Submit</button> </form> <script>     $("#post-btn").click(function(){                 $.post("process.php",function(data){             alert(data);         });     }); </script> 

Process Page:

<?php $username=$_POST["username"]; $password=$_POST["password"]; echo "Username: ".$username; echo "<br>"; echo "Password: ".$password;?> 

if I click the "Traditional Submit" buttton, it works perfectly well.

but when I click the "$.Post Submit" button, I just keep getting error msg "Notice: Undefined Index ..."

I can not figure out where the problem is, please kindly help check and fix, thanks in advance!

like image 672
Yolo Avatar asked Sep 17 '14 02:09

Yolo


1 Answers

You have to select and send the form data as well:

$("#post-btn").click(function(){             $.post("process.php", $("#reg-form").serialize(), function(data) {         alert(data);     }); }); 

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

like image 181
nbrooks Avatar answered Sep 18 '22 18:09

nbrooks