javascript jQuery $.ajax 发布到 PHP 文件不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17911472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:04:57  来源:igfitidea点击:

jQuery $.ajax post to PHP file not working

phpjavascriptjqueryajax

提问by i_me_mine

So this stems from a problem yesterday that quickly spiraled out of control as the errors were unusual. This problem still exists but the question was put on hold, here, and I was asked to reform a new question that now relates to the current problem. So here we go.

所以这源于昨天的一个问题,由于错误异常,该问题迅速失控。这个问题仍然存在,但问题被搁置,here,我被要求修改一个现在与当前问题相关的新问题。所以我们开始了。

The problem is basic in nature. If you were helping yesterday I have switched from a $.post to an $.ajax post to deliver a variable to my PHPfile. However my PHPfile seems to never receive this variable stating that the index is 'undefined'.

这个问题本质上是基本的。如果您昨天提供帮助,我已从 $.post 切换到 $.ajax 帖子以将变量传递到我的PHP文件中。但是,我的PHP文件似乎从未收到此变量,说明索引为“未定义”。

Now this would normally mean that the variable holds no value, is named incorrectly, or was sent incorrectly. Well after a full day of messing with this (kill me) I still see no reason my PHPfile should not be receiving this data. As I'm fairly new to this I'm really hoping someone can spot an obvious error or reccommend another possible solution.

现在这通常意味着该变量没有值、命名不正确或发送不正确。好吧,经过一整天的搞砸(杀了我),我仍然认为我的PHP文件没有理由不接收这些数据。由于我对此相当陌生,因此我真的希望有人能发现明显的错误或推荐另一种可能的解决方案。

Here's the code

这是代码

jQuery

jQuery

$('#projects').click(function (e) {
alert(aid); 
$.ajax({    
    url:'core/functions/projects.php',
    type: 'post',
    data: {'aid' : aid},
    done: function(data) {
    // this is for testing
    }
    }).fail (function() {
        alert('error');
    }).always(function(data) {
        alert(data);                                        
        $('#home_div').hide();          
        $('#pcd').fadeIn(1000);
        $('#project_table').html(data); 
    });         
});

PHP

PHP

<?php

include "$_SERVER[DOCUMENT_ROOT]/TrakFlex/core/init.php";

if(isset($_POST['aid'])) {  
    $aid = $_POST['aid'];               
    try {
        $query_projectInfo = $db->prepare("
            SELECT  projects.account_id,
                    projects.project_name,                  
                    projects.pm,    
                    //..irrelevant code      
            FROM projects
            WHERE account_id = ?                        
        "); 

        $query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);
        $query_projectInfo->execute();
        $count = $query_projectInfo->rowCount();

        if ($count > 0) {
            echo "<table class='contentTable'>";
            echo "<th class='content_th'>" . "Job #" . "</th>";
            echo "<th class='content_th'>" . "Project Name" . "</th>";
            //..irrelevant code          
            while ($row = $query_projectInfo->fetch(PDO::FETCH_ASSOC)) {                
                echo "<tr>";
                echo "<td class='content_td'>" . "<a href='#'>" . $row['account_id'] . "</a>" . "</td>";
                echo "<td class='content_td'>" . $row['project_name'] . "</td>"; 
                //..irrelevant code
                echo "</tr>";
            }
            echo "</table>";            
        }       
    } catch(PDOException $e) {
        die($e->getMessage());
    }   
} else {
    echo 'could not load projects table';
}

?>   

When I run this code by pressing '#projects' I get 2 alerts. This first alert says '6', which is the value of the variable 'aid' and is expected. The second alert is blank.

当我按“#projects”运行此代码时,我收到 2 个警报。第一个警报显示“6”,这是变量“aid”的值,是预期的。第二个警报是空白的。

Now here is where I get confused. If the post is being sent with a value of 6. Isn't the $_POST['aid'] set? Also if that's true shouldn't my code execute the ifportion of my conditional statement ratherthan my else?. Either way this strikes me as odd. Shouldn't I receive somethingback from my PHPfile?

现在这就是我感到困惑的地方。如果帖子的发送值为 6。$_POST['aid'] 不是设置了吗?此外,如果这是真的,我的代码不应该执行if我的条件语句的一部分不是我的else?。不管怎样,这让我觉得很奇怪。我不应该从我的文件中收到一些东西PHP吗?

So in Firebug we trust, right? If I open up Firebug and go through like this
Firebug -> POST projects.php -> XHR -> POST(tab) ->
I see 6 in the 'Parameter' window and '6' in the 'Source' window. Then if I click the 'Response' and 'HTML' tabs they both hold no value.

所以在我们信任的 Firebug 中,对吧?如果我打开 Firebug 并像这样进行操作,
Firebug -> POST projects.php -> XHR -> POST(tab) ->
我会在“参数”窗口中看到 6,在“源”窗口中看到“6”。然后,如果我单击“响应”和“HTML”选项卡,它们都没有价值。

So anyways, that wall of text is my problem. Again, I'm really hoping someone can help me out here. I would hate to waste anymore time on what should be a simple solution.

所以无论如何,那堵文字墙是我的问题。再次,我真的希望有人能在这里帮助我。我不想再浪费时间在什么应该是一个简单的解决方案上。

EDIT

编辑

If I change my php file to look like this

如果我将我的 php 文件更改为如下所示

<?php

if(isset($_POST['aid'])) {  
    $aid = $_POST['aid'];
    echo $aid;
} else {
    echo 'fail';    
}

The response is now '6'! Hooray! We made a breakthrough! Now why won't it load my table that results from my query?

响应现在是'6'!万岁!我们取得了突破!现在为什么不加载我的查询结果表?

side noteThis should of been noted originally if I take away the

旁注如果我拿走,这本来应该被注意到

if(isset($_POST['aid'])){
//all my code
} else {
    //response
}

and just hard code the variable $aid like this

并像这样对变量 $aid 进行硬编码

$aid = '6';

Then run the PHPfile directly the query is successful and the page loads the table its dynamically creating.

然后PHP直接运行文件查询成功,页面加载其动态创建的表。

Also in response to one of the answers asking me to use

也是为了回应要求我使用的答案之一

$('#projects').click(function (e) {
    alert(aid); 
    $.ajax({    
        url:'core/functions/projects.php',
        type: 'post',
        data: aid,
        success: function(data) {
        // this is for testing
        }
        }).error (function() {
            alert('error');
        }).complete (function(data) {
            alert(data);                                        
            $('#home_div').hide();              
            $('#pcd').fadeIn(1000);
            $('#project_table').html(data); 
        });     
});

I was using that, but I'm using jQuery v1.10.2 and according to thisthose methods are or will be deprecated. Either way it made 0 difference in the outcome.

我用这一点,但我使用jQuery v1.10.2的,并根据这些方法或将被弃用。无论哪种方式,它都会使结果产生 0 差异。

Anyways the question is now. Why is it if I used the simple version I get echo'd back my $aid variable of '6'. However when I try and run my query with it I get nothing. Also please try to remember if I hard code the 6, the table creates.

无论如何,问题是现在。为什么如果我使用简单版本,我会得到回显我的 $aid 变量“6”。但是,当我尝试用它运行我的查询时,我什么也没得到。另外请记住,如果我对表创建的 6 进行硬编码。

回答by JohnnyFaldo

I think this may be the error:

我认为这可能是错误:

data: aid,

it should be

它应该是

data: {'aid':aid},

That will provide the $_POST['aid'] label and value you're looking for in your php page.

这将提供您在 php 页面中寻找的 $_POST['aid'] 标签和值。

EDIT:

编辑:

If you're having trouble with this, I'd simplify it for testing, the main reasons for things like this not working in my experience are:

如果您对此有疑问,我会简化它以进行测试,根据我的经验,此类事情不起作用的主要原因是:

it's not reaching the file

它没有到达文件

it's reaching the file but the file's expecting something different than it's receiving and due to control structures it's not returning anything

它正在到达文件,但文件期望的东西与它接收的东西不同,并且由于控制结构,它没有返回任何东西

it's reaching the file with the correct data, but there are other errors in the php file that are preventing it from ever returning it.

它使用正确的数据到达文件,但 php 文件中还有其他错误阻止它返回它。

You can easily rule out each of these in your case.

在您的情况下,您可以轻松排除其中的每一个。

回答by Ryan Williams

The jQuery data parameter to the ajax method should be an object, such as {'aid': aid}. I think that's your problem. I also noticed your always method is missing a parameter for data.

ajax 方法的 jQuery 数据参数应该是一个对象,例如{'aid': aid}. 我想那是你的问题。我还注意到您的 always 方法缺少数据参数。

回答by joatis

If you're now posting the data correctly could the problem be in your PHP page? The init.php include couldn't be changing the value of $_POST['aid'] could it?

如果您现在正确发布数据,问题可能出在您的 PHP 页面上吗?init.php 包含不能改变 $_POST['aid'] 的值吗?

回答by Jonast92

I'm not sure done is suppose to behave like that, normally you use done like this:

我不确定 done 是否应该表现得像那样,通常你像这样使用 done :

$.ajax({
    //...
})
.done(function(data){
    //...
});

Just do it like this:

只是这样做:

var fetch = true;
var url = 'someurl.php';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'aid' : aid
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;
            // Do something with the returned data
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

You can add the failure part in if you want. This is, anyway, guaranteed to work. I'm just not familiar enough with done to make more comments about it.

如果需要,您可以添加失败部分。无论如何,这保证有效。我只是对 done 不够熟悉,无法对此发表更多评论。

回答by L105

Try

尝试

include "{$_SERVER['DOCUMENT_ROOT']}/TrakFlex/core/init.php";

instead cause $_SERVER[DOCUMENT_ROOT] witout bracket won't work. When you are using an array in a string, you need those brackets.

而是导致 $_SERVER[DOCUMENT_ROOT] 没有括号将不起作用。当您在字符串中使用数组时,您需要这些括号。

回答by Sudheesh.M.S

Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cachefor the particular ajax request helped to make it work. Refer below:

由于某些浏览器会缓存 ajax 请求,因此它不会按预期响应。因此,明确禁用特定 ajax 请求的缓存有助于使其工作。参考以下:

$.ajax({
    type: 'POST',        
    data: {'data': postValue},
    cache: false,
    url: 'postAjaxHandling.php'
}).done(function(response){
});