jquery ajax form submit

2019-01-12 07:59发布

问题:

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...

回答1:

​$(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.



回答2:

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

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


回答3:

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.