简体   繁体   中英

jQuery $.ajax post to PHP file not working

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.

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 PHP file. However my PHP file seems to never receive this variable stating that the index is 'undefined'.

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 PHP file 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.

Here's the code

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

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.

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 if portion of my conditional statement rather than my else ?. Either way this strikes me as odd. Shouldn't I receive something back from my PHP file?

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.

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

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?

side note This 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 = '6';

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

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 this those methods are or will be deprecated. Either way it made 0 difference in the outcome.

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.

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.

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.

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

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.

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?

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

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

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.

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

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

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