1

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.

Community
  • 1
  • 1
i_me_mine
  • 1,435
  • 3
  • 20
  • 42

6 Answers6

2

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.

JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29
  • I have updated my question to show the changes you suggested. The outcome is till exactly the same – i_me_mine Jul 28 '13 at 18:44
  • I agree. Just to expand, the post needs labels and values for the data. wrapping aid in quotes makes it a label and without it will pass the value of aid. – joatis Jul 28 '13 at 18:45
  • I agree completely. I will make an edit showing simple code. Just for the record if I remove the if(isset($_POST) and hard code the variable $aid. Then run the `PHP` file directly, the table is inflated and the query is successful, I will mention all of this in the edit when I post the simplified version – i_me_mine Jul 28 '13 at 18:50
  • I've decided to accept this answer and post a new question as this WAS the solution to the ORIGINAL problem and I fear this question has gone out of scope and off topic. Please see the new question if you're still interested in helping. Thanks again – i_me_mine Jul 28 '13 at 19:35
  • No worries will have a look now – JohnnyFaldo Jul 28 '13 at 19:36
1

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.

Ryan Williams
  • 959
  • 7
  • 15
1

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?

joatis
  • 3,375
  • 1
  • 17
  • 13
  • It's highly unlikely. It includes my connect_db.php and a users.php which holds *only* functions. I can however post the contents if you'd like – i_me_mine Jul 28 '13 at 18:54
  • OK re-reading your post you're now saying that you are getting No response after fixing the AJAX call. According to your PHP code the only branch that doesn't echo is if $count <= 0. What happens if you add an else there? – joatis Jul 28 '13 at 19:03
  • I just posted a new edit. Read it and let me know if this still applies, and thank you for the help – i_me_mine Jul 28 '13 at 19:12
  • see the **new** edit, in my haste I was a fool and forgot to include the `echo $aid;` line. It's not working yet, but we have made a breakthrough!. Maybe now we can solve this! – i_me_mine Jul 28 '13 at 19:19
1

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.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • Thank you for your answer. I was using done, fail, and complete however because I am using jQuery v1.10.2 and according to [this](http://api.jquery.com/jQuery.ajax/) they are deprecated. For the record though I have tried `success` , `error`, and `complete` instead of done, failm and complete. The results are the same. – i_me_mine Jul 28 '13 at 18:56
1

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.

L105
  • 5,379
  • 3
  • 18
  • 23
  • this may be true in some cases, I just tried it in mine and it throws an error saying `Notice: Use of undefined constant DOCUMENT_ROOT - assumed 'DOCUMENT_ROOT' in C:\xampp\htdocs\TrakFlex\core\functions\projects.php on line 3` – i_me_mine Jul 28 '13 at 18:58
  • I forgot to add the ' ' of document root, I edited my code. Try it, it should work. – L105 Jul 28 '13 at 19:01
  • you were correct in your edit, but still no change in the outcome. Thank you for the heads up on the `{}` braces though. I'll make sure to include them in the future – i_me_mine Jul 28 '13 at 19:14
0

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){
});
Sudheesh.M.S
  • 498
  • 1
  • 7
  • 13