简体   繁体   中英

POST variables not being passed by jQuery ajax request

I have been trying for hours to get call a php function when a button is clicked. The ajax.php file is being opened and it is returning fine, however the post variables are not being passed. Here is my jQuery code:

$(function() {
    $("#button-id").click(function() {
        $.post('functions/ajax.php',
          { param1: "value1", param2: "value2" },
          function(data) {
              alert(data);
          }
        );
    });
});

And the following php code results in an empty array being displayed.

<?php
    print_r($_POST);
?>

I can't for the life of me figure out why the data variables aren't being passed to the ajax.php file. What could be causing this?

You should be doing this:

$.post("functions/ajax.php", {
    param1: "value1",
    param2: "value2"
}).done(function (data) {
    alert("Data Loaded: " + data);
});

http://api.jquery.com/jquery.post/ (under examples)

This will helpful for you.

$.ajax({
    type : "POST",
    url:"<?=Yii::app()->createUrl('site/Enquiryvalidation');?>",
    data:{"param1: "value1", param2: "value2"},
    success:function(data){
alert(data);
}
});

Turns out the problem was being caused by my .htaccess file. Because I was redirecting all .php file requests to their respective page without the .php extension, an extra get request was being executed each time the file was opened, resulting in all the previous post variables being lost.

I had the same issue being caused by my .htaccess removing the php file extensions. To fix this, simply remove the php extension in the request:

$.post('functions/ajax',
    { param1: "value1", param2: "value2" },
    function(data) {
        alert(data);
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM