16
$.ajax({
    method: "post"
    , url: "save.php"
    , data: "id=453&action=test" 
    , beforeSend: function(){

    } 
    , complete: function(){ 
    }  
    , success: function(html){ 
        $("#mydiv").append(html);        
    }
});

I have set method type as post but in Save.php I just get values either in $_GET or $_REQUEST but not in $_POST.

My form looks like:

<form method="post" id="myform" action="save.php">

It was not working, looked around here and on Google, tried adding enctype

<form method="post" id="myform" action="save.php" enctype="application/x-www-form-urlencoded">

but still $_POST empty?

How do I make it work?

Jordi Nebot
  • 3,355
  • 3
  • 27
  • 56
TigerTiger
  • 10,590
  • 15
  • 57
  • 72
  • 1
    Just had a similar problem using jQuery's ajaxForm plugin. i resolved it by ensuring that each input element had a 'name' attribute. Mine matched the ID selector, but this may not be necessary. – jbrain Sep 28 '12 at 15:54

7 Answers7

10

Instead of method: "post" you need to use type: "POST"

So this should work without any alterations to your form HTML:

$.ajax({
    type: "POST"
    , url: "save.php"
    , data: "id=453&action=test" 
    , beforeSend: function(){

    } 
    , complete: function(){ 
    }  
    , success: function(html){ 
        $("#mydiv").append(html);        
    }
});

Not sure why it doesn't work but this works for me:

save.php

<?php
print_r($_POST);

file.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>Example</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $('input').click(function() {
                $.ajax({
                    type: "POST"
                    , url: "save.php"
                    , data: "id=453&action=test" 
                    , beforeSend: function(){

                    } 
                    , complete: function(){ 
                    }  
                    , success: function(html){ 
                        alert(html);        
                    }
                });
            });
        });
    </script>
</head>

<body>
    <div id="main"><input type="button" value="Click me"></div>
</body>
</html>

Your error must lie somewhere else.

Waleed Amjad
  • 6,716
  • 4
  • 35
  • 35
  • @Wbdvlpr: open firebug console and check requests being sent. You can see what method it uses (get/post) and what parameters being sent to which url. Then go from there. – serg Oct 30 '09 at 15:45
  • 1
    But I get values in $_GET and $_REQUEST .. but not in the $_POST .. any idea how to check if "somewhere else" is wrong?? – TigerTiger Oct 30 '09 at 15:45
  • You aren't doing cross domain requests, are you? – serg Oct 30 '09 at 15:47
  • btw there is a good plugin that automatically gets all fields values from the form and submits it via ajax: http://jquery.malsup.com/form/#ajaxForm – serg Oct 30 '09 at 15:54
  • no its on the same domain .. one thing I haven't mentioned is this form is in a dialog window – TigerTiger Oct 30 '09 at 15:55
  • @serg555: thanks for the link .. everything works fine except this POST so I dont think I need to use that plugin. – TigerTiger Oct 30 '09 at 15:57
  • I don't understand though how this problem is related to a form. Where your ajax is being called? Maybe it is not called at all and you are just submitting a form itself instead of doing ajax call? – serg Oct 30 '09 at 16:00
  • @serg555 .. checked in firebug console .. when I click the submit button it sends a GET request. Not sure why it does so. – TigerTiger Oct 30 '09 at 16:01
  • Are you sure that it is ajax call that sending this request, not form itself? Try it without a form, just use a link or a button like in this answer. Maybe your ajax is not being called at all. – serg Oct 30 '09 at 16:06
  • In the above example, the values are hardcoded but I am fetching values from FORM using serialize method. – TigerTiger Oct 30 '09 at 16:12
  • Yes I am sure its ajax as in save.php i dont send page_header and footer when its an ajax request. Also on request completion I update (appendTo) html of dialog window. – TigerTiger Oct 30 '09 at 16:14
  • Ok I give up then :p I've had some issues with ajax posts before but they were related to cross domain stuff. – serg Oct 30 '09 at 16:16
  • @serg555 - thanks a lot for your efforts .. its a bit strange as if I use .post it sends it as POST, ($.post uses .ajax itself!!) .. thnx – TigerTiger Oct 30 '09 at 16:20
6

**Add below piece of code in your code before success **

beforeSend: function(xhr){xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")}
Rajnish
  • 71
  • 1
  • 2
4

I was having trouble with the variables getting lost in the mix as well and discovered that while using Rewrite Conditions to externally redirect dir/foo.php to dir/foo Apache was dropping the POST request altogether and redirecting.

So when writing the JavasSript you must reference the file in a way that it can bypass any external redirecting.

eg. Drop the extension name inline with the JavaScript.

Write

url: "dir/foo"

instead of

url: "dir/foo.php"

I hope that this helps others who found this page like me.

jkofron.e
  • 5,043
  • 1
  • 17
  • 16
4

Why not call jQuery.post() directly?

$.post("save.php",
  $("#myform").serialize(),
  function(html) { 
    $("#mydiv").append(html);        
  },
  "html"
);

In regards to jQuery.ajax(), changing to type: "POST" instead of method: "POST" will cause a proper POST request:

$.ajax({
        type: "POST",
        url: "test.mhtml",
        data: $("#myform").serialize(),
        success: function(html){ 
                $('#mydiv').html(html);
        }
});

This shows up in the Apache logs as:

::1 - - - [30/Oct/2009:09:44:42 -0700] "POST /test.php HTTP/1.1" 200 9 "http://localhost:10501/test.mhtml" "(sic)"

Possible alternate issue:
I found this question on StackOverflow while looking around at your problem. Maybe it isn't the jQuery which is giving you trouble, it is PHP? The top voted answer has some suggestions for ensuring that PHP isn't interfering, and the second highest answer offers some code to see if the request is actually a POST or not:

<?php
  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo 'POSTed';
  }
?>
Community
  • 1
  • 1
Jack M.
  • 30,350
  • 7
  • 55
  • 67
  • how about beforesend, complete, success ?? with .post ?? – TigerTiger Oct 30 '09 at 15:38
  • just use: $.post("save.php", $("#myform").serialize(),function(data){$('.msg').html(data);); (3rd arugment is a function callback.) – CodeJoust Oct 30 '09 at 15:43
  • I edited to include the third and fourth arguments. The third argument is the callback function for when information comes back, and the fourth argument is the type of data coming back. jQuery will do some parsing for you, if you change to JSON return type. – Jack M. Oct 30 '09 at 15:58
  • @Jack thanks for your example. I can see the .post works. But if you help me debug .ajax as well that would be great!! – TigerTiger Oct 30 '09 at 16:15
  • Mostly just giving you what Sbm007 said above. They are correct, as this generates a POST request. – Jack M. Oct 30 '09 at 16:51
0

I was experiencing similar problems with $(form).ajaxSubmit().

Browser tools were indicating that I was successfully issuing a POST. On the server $_SERVER['REQUEST_METHOD'] was also indicating a POST, and yet the $_POST variable in PHP was being returned as array(0) { }. The problem for me was that I was actually submitting an empty form. As soon as there was data in the form, $_POST had something in it (as you might expect!) but more importantly, if ($_POST) { ... } started returning true.

charlesdeb
  • 571
  • 5
  • 14
0

In my case the solution was adding the missing .serialize() in the data line of the Ajax statement:

data: $("#form").serialize()
askepott
  • 250
  • 3
  • 13
0

You might try changing the contentType, i.e: application/x-www-form-urlencoded. If you have application/json for example, you can get the behaviour you witnessed.

$.ajax({
    url: 'index.php',
    dataType: 'json',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: { 'test': jsonStr },
    success: function( data, textStatus, jQxhr ){
        console.log('success');
    },
    error: function( jqXhr, textStatus, errorThrown ){
        console.log( errorThrown );
    }
});    
CSharp
  • 1,396
  • 1
  • 18
  • 41