0

I have some simple HTML :

First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">

What I wish to do is submit this form using JQuery and store what is entered in a database. The page, without refreshing would then update to show:

<p>Thanks for submitting $fname + $lname</p>

I would also like for a cookie to be created so that if the same user is to visit the site, it will always show this message rather than force them to see the input form multiple times.

What is the best way for me to do this? How can I do this using JQuery? Is there a better alternative? It is simple to do using PHP, but I would like it to be as interactive as possible and my example is just a very simple representation of what I will have :).

4

1 回答 1

1

您可以使用 jQuery Ajax。

这很简单:首先,您需要在 head 标签中添加 jQuery 文件,如下所示:

<!-- Add jquery library -->
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
     $(document).ready(function(){ 
         $("#btnSubmit").click(function(){
             var fname = $("#fname").val();
             var lname = $("#lname").val();
             $.ajax({
                 url : "updateDb.php", // php file where you write your mysql query to store value
                 type : "POST", // POSTmethod
                 data : {"fistname":fname,"lastname":lname},
                 success : function(n){
                      // after success you can alert popup here
                      // also set you cookies here
                      // I have also function for set  cookie through javascript  
                      setCookie("username",fname,30);
                 } 
             });
         });
     });

     function setCookie(c_name,value,exdays)
     {
      var exdate=new Date();
      exdate.setDate(exdate.getDate() + exdays);
      var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
      document.cookie=c_name + "=" + c_value;
     }
</script>
</head>

<!-- Now your HTML code -->
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
<input type="button" value="Submit" id="btnSubmit">

<!-- Note : if you use input type=submit then page must load.so you need to remove that and use only button -->
于 2013-05-17T05:58:12.073 回答