Skip to content
Advertisement

Jquery .ajax method=”post” but $_POST empty

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement