-4

I want to submit some data via Ajax:

index.php:

<form>
  <input name="name" value="Frank"><br>
  <input name="submit" type="submit" value="Submit">
</form>

<div id="result"></div>

<script>
$(document).on('submit','form',function(e){
    e.preventDefault();
    $form = $(this);
    submit($form);  
});

function submit($form){
    var formdata = new FormData($form[0]); 
    var request = new XMLHttpRequest(); 
    request.open("post", "action.php");
    request.send(formdata);
    $.ajax({url: "action.php", success: function(result){
        $("#result").html(result);
    }});
}
</script>   

action.php:

echo "hello ";
echo $_POST["name"];

My result:

hello

My expected result:

hello Frank
peace_love
  • 6,229
  • 11
  • 69
  • 157
  • Is the contents of `$form[0]` what you expect it to be? – Henders Jun 01 '16 at 14:09
  • @Henders The content of the form – peace_love Jun 01 '16 at 14:12
  • 2
    why are you doing xmlhttprequest and .ajax? Choose one or the other, not both. you're doing **TWO** ajax calls there. and on the .ajax version, you're sending a blank body to the server. and for the xmltttprequest you don't bother processing the response at all. you do a call and then forget it exists. – Marc B Jun 01 '16 at 14:13
  • @MarcB Oh ok, I will check this, thanks a lot! – peace_love Jun 01 '16 at 14:14
  • Possible duplicate of [Sending data via AJAX](http://stackoverflow.com/questions/22179620/sending-data-via-ajax) – Tirth Patel Jun 01 '16 at 14:16

3 Answers3

1

Using jQuery:

function submit($form){
    $.ajax('action.php', {
        method: 'POST',
        data: $form.serialize(),
        success: function(result) {
            $('#result').html(result);
        }
    });
}
James A
  • 775
  • 5
  • 11
1

Since you are mixing jquery ajax with normal ajax, you go wrong. Just stick with jquery ajax.

HTML Form and give your input an id:

<form>
  <input name="name" id="name" value="Frank"><br>
  <input name="submit" type="submit" value="Submit">
</form>



 $(function() {
         $(".submit").click(function(e) {
         e.preventDefault();
         var name = $("#name").val();
         var dataString = 'name='+ name;    
        if(name==''){
           alert('Name is blank');
           $("#name").focus();
        } else {
           $.ajax({
              type: "POST",
               url: "action.php",
              data: dataString,
           success: function(data){
               $("#result").html(data);
          }
         });
       }
       return false;
      });
    });
joz ralte
  • 21
  • 2
1

If you want to use FormData API then this is what you need to do:

<script>
 var formdata= document.querySelector("form");
 var data = new FormData(formdata);
 $.ajax({url: "action.php",data:data, success: function(result){
    $("#result").html(result);
}});

</script>