简体   繁体   中英

jquery ajax form submit

Is this code correct? I'm trying to submit it and also I would like on submit if text area would be empty again.

<script type="text/javascript">
$(document).ready(function(){

    $("form#submit").submit(function() {
        // we want to store the values from the form input box, then send via ajax below
        var fid = $(".messag").attr("id");
        var val = $("#mess_ar").val();
        $.ajax({
            type: "POST",
            url: "send_message.php",
            data: "fid="+ fid +"&val="+ val,
            success: function(){
                    $("#mess_ar").
            }
        });
        return false;
    });
}):
</script>

I'm trying to upload this:

<form id="submit" method="POST">
<textarea name="mess_cont" id="mess_ar" autofocus="autofocus" cols="70" rows="5">      </textarea>
<button id="mess_but" type="submit">Send</button>
</form>

Thankx...

Looks good. To empty the textarea use the following in the ajax success callback:

$("#mess_ar").val('');

What are you actually looking for? Does it return the data in response too? Add the functions to track your the error case too. Make something like

<script type="text/javascript">
$(document).ready(function(){

    $("form#submit").submit(function() {
       // we want to store the values from the form input box, then send via ajax below
       var fid = $(".messag").attr("id");
       var val = $("#mess_ar").val();
       $.ajax({
          type: "POST",
          url: "send_message.php",
          data: "fid="+ fid +"&val="+ val,
          success: function(incoming_data){
             // ALERT incoming data if coming
             $("#mess_ar").text(""); // DO YOUR JOB CONTINUOU
          },
          error: function() { 
             alert("BROKEN REQUEST.");
          }
       });
       return false;
   });

});
</script>

Else, seems all fine.

​$(function(){
    $("form#submit").submit(function(e){
        e.preventDefault();
        var fid = $(".messag").attr("id");
        var val = $("#mess_ar").val();
        $.ajax({
            type: "POST",
            url: "send_message.php",
            data: "fid="+ fid +"&val="+ val,
            success: function(){
                $("#mess_ar").val("");
            }
        });
    });
});​

Use

$("#submit").on('submit', function(e){...});

instead of

$("#submit").submit(function(e){...});

if you are using latest version of jquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM