Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript jQuery AJAX POST data error

I am trying to send a post param. to request.php but it returns that the post param. are empty.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
$.ajax({
    url: "request.php",
    type: "POST",
    data: "{key:'123', action:'getorders'}",
    contentType: "multipart/form-data",
    complete: alert("complete"),
    success: function(data) {
        alert(data);
    },
    error: alert("error")
});
like image 387
PaulE Avatar asked Aug 11 '16 04:08

PaulE


3 Answers

remove " " from this data as data:{key:'123', action:'getorders'}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
   <script>
     $.ajax({
        url:"request.php",
        type:"POST",
        data:{key:'123', action:'getorders'},
        contentType:"multipart/form-data",
        complete:alert("complete"),
        success:function(data) {
          alert(data);
            },
        error:alert("error")
             }); 

          </script>
like image 119
Sameera Prasad Jayasinghe Avatar answered Sep 25 '22 17:09

Sameera Prasad Jayasinghe


You must use FormData for multipart/form-data ,and also need additional option in ajax ..

var request = new FormData();   
request.append('key',123);
request.append('action','getorders');
$.ajax({
    url: "request.php",
    type: "POST",
    data: request,    
    processData : false,
    contentType: false,
    success: function(data) {
        alert(data);
    }    
});
like image 30
David Jaw Hpan Avatar answered Sep 22 '22 17:09

David Jaw Hpan


This will help you. You don't want a string, you really want a JS map of key value pairs.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $.ajax({
       url:"request.php",
       type:"POST",
       data:{key:'123', action:'getorders'},
       contentType:"multipart/form-data",
       complete:alert("complete"),
       success:function(data) {
          alert(data);
       },
       error:function(){
          alert("error");
       }); 

</script>
like image 38
Sinscary Avatar answered Sep 23 '22 17:09

Sinscary