2

I am getting a very self explanatory error. However the index, as far as I can tell is not only 100% defined, it also contains a value. This is the latest of a series of silly problems that's driving me insane today.

Here is the code you've probably seen a million times that should work.

jQuery

$('#projects').click(function (e) {
    alert(aid); 
    $.post('core/functions/projects.php', { aid: aid })
    .done(function(data) {
        alert(aid);             
        $('#home_div').hide();      
        $('#pcd').fadeIn(1000);     
    })
    .fail(function(jqXHR, status, error) {
        alert(error);
    }); 
});

Which alerts me twice with the value of 6

PHP

<?php
require_once "$_SERVER[DOCUMENT_ROOT]/core/init.php";
if(isset($_POST)) {             
    $aid = $_POST['aid'];
    echo $aid;
} else {
    echo 'fail';
}
?>

I receive this error:

Notice: Undefined index: aid in C:\xampp\htdocs\core\functions\projects.php on line 5

So I added a little deeper check to my if else and it now looks like this

<?php
require_once "$_SERVER[DOCUMENT_ROOT]/core/init.php";
$account_id;
if(isset($_POST['aid'])) {          
    $aid = $_POST['aid'];
    echo $aid;
} else {
    echo 'fail';
}

and now it spits back fail. I already went here, to check out the error and it's exactly as I thought it was. That doesn't mean it makes any more sense to me why I'm getting it.

So lets review. My jQuery, is hitting the right PHP file because I am getting responses from that specific PHP file. My variable holds a value because jQuery alerts me twice with the value it holds of 6. However my PHP file is not receiving this value? Can someone please explain to me why?

EDIT

If I add a line to my jQuery I get another message verifying the data is being sent. Yet I STILL receive the error that the $_POST index is not set. This is crazy

$('#projects').click(function (e) { 
    alert(aid); 
    $.post('core/functions/projects.php', { aid: aid })
    .done(function(data) {  
        alert(aid);
        alert(data);            
        $('#home_div').hide();      
        $('#pcd').fadeIn(1000);     
    })
    .fail(function(jqXHR, status, error) {
        alert(error);
    }); 
}); 

Now I get 3 Alert boxes holding the value 6.

1 alert box fires before the post is sent with the $aid variable information of '6'
1 alert box fires after the data is received again with the $aid variable '6'
1 alert box fires after the data is received now with the php response which is again '6'!

I mean WTF? Will this nightmare ever end? That means even the variable in php is being set from the post! How is this possible? I mean look at the php code all it echos is either 'fail' or $aid and $aid cant have a value unless its set by the post and furthermore it would NOT be giving me the error of Undefined index. I need to go take a break, I am gonna lose it.

FIREBUG

In firebug I see

I see POST ->
projects.php ->
POST ->
PARAMETERS ->
aid 6 ->
SOURCE -> aid=%0D%0A6
RESPONSE ->

There is nothing in the response, the brief time I posted a response here was because I left my 'require_once' off and I had my code commented out.

There is something odd in the source though. It says SOURCE aid=%0D%0A6 instead of the normal SOURCE aid = 6

2ND EDIT

I had a large section of code commented out to simplify this example. The code uses the variable and query's for data. Then returns a table created in php. If un-comment the code I can see the table in my RESPONSE in html form. If I go to HTML I can actually see the visual table. So Whats going on? Why is that response inflating my div and not the table? I will now post some more code to explain

<?php
require_once "$_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,    
                    //...more columns    
            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>";              
            //...more table headers      
            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>";                
                         //.. more data 
                echo "</tr>";
            }
            echo "</table>";            
        }       
    } catch(PDOException $e) {
        die($e->getMessage());
    }   
} else {
    echo 'could not load projects table';
}

?>    

So as you can see my full php file actually sends back a table of data. I can see this table in FireBug -> NET -> XHR -> HTML. I can also see all the php code in FireBug -> NET -> XHR -> RESPONSE. However the div that should hold the table only holds the else statement 'could not load projects table'. So I think I'm getting closer, but I'm still stuck. Any ideas?

Community
  • 1
  • 1
i_me_mine
  • 1,435
  • 3
  • 20
  • 42
  • possible duplicate of [php loading before $.post](http://stackoverflow.com/questions/17901762/php-loading-before-post) – Sven Jul 27 '13 at 22:27
  • 1
    It is not helpful to duplicate your question here. Work on ONE question, update it, and give feedback to the answers you already got! – Sven Jul 27 '13 at 22:28
  • @Sven what are you talking about? That was a question that I accepted an answer for and this is a SEPERATE issue. – i_me_mine Jul 27 '13 at 22:29
  • What is the output of `print_r($_POST)`? – bfavaretto Jul 27 '13 at 22:31
  • Well, your jQuery code looks suspiciously the same. Basic rule of debugging: If you don't know the value of a variable, and it is not the value you expect, use `var_dump($_POST)`. – Sven Jul 27 '13 at 22:35
  • @bfavaretto Array( ). As I expected. I understand that $_POST is not holding a value. What I don't understand is how the value is being lost from my `jQuery` to the `PHP` file. The variable without a doubt holds a value of 6. However when it gets to the `PHP` file there is nothing – i_me_mine Jul 27 '13 at 22:37
  • Your code works for me (without the require_once). Perhaps something in your core/init.php is causing the problem. – James Holderness Jul 27 '13 at 22:38
  • @JamesHolderness Ya, this is such basic code it drives me INSANE that it doesn't work. The `init.php` holds my db connect and its used everywhere. It doesn't seem to give me problems anywhere else. Just this one place. – i_me_mine Jul 27 '13 at 22:42
  • @i_me_mine If you are trying to narrow down the problem, why not just comment out that line (it's obviously not needed in this simplified example). That way you'll know for sure if it has anything to do with the issue. – James Holderness Jul 27 '13 at 22:45
  • @JamesHolderness yea, I just did, I get the same result =(. – i_me_mine Jul 27 '13 at 22:45
  • @i_me_mine How is the *aid* variable set in the javascript code? Have you tried hardcodeing it with something like `var aid=6;` before making the post call. And have you looked at what's being sent in the post body via your browser console? – James Holderness Jul 27 '13 at 22:51
  • @JamesHolderness yes my friend, all the way around it says '6'. See the edit, I'll be back in 5 minutes, I need to walk away for a second – i_me_mine Jul 27 '13 at 22:54
  • First check your browsers dev tools (network tab) to make sure the value is being posted. If it is, it must be some php config messing up with the post data – bfavaretto Jul 27 '13 at 22:55
  • It's possible `post_max_size` was somehow corrupted in your php.ini file. Don't know if it'll help, but check out [PHP $_POST array empty although php://input and raw post data is available?](http://getluky.net/2009/02/24/php-_post-array-empty-although-phpinput-and-raw-post-data-is-available/) – Herbert Jul 27 '13 at 23:01
  • @Herbet that definitely sounds like my problem. Do you know where I find that setting in my ini file? – i_me_mine Jul 27 '13 at 23:04
  • In mine it's about half way down. Use a text editor and search for `post_max_size`. It should say `post_max_size = 8M` – Herbert Jul 27 '13 at 23:07
  • 1
    Have you added that `var_dump($_POST)` and posted the result here? – Sven Jul 27 '13 at 23:09
  • @Sven: see [this comment](http://stackoverflow.com/questions/17903067/index-undefined-when-receiving-post-from-jquery#comment26151124_17903067). It's subtle, but apparently it was `Array()`. – Herbert Jul 27 '13 at 23:12
  • @Herbert I found it, it says 8M. I think I'm just going to back up my site, and reinstall XAMPP. This has to be a bug, this code is just too simple to fail like this – i_me_mine Jul 27 '13 at 23:14
  • 1
    Don't reinstall! Fire up your Firebug or other network console and have a look at what is really contained in that Ajax request. – Sven Jul 27 '13 at 23:16
  • 1
    After reading your update and all these comments, I'm led to only one possible conclusion. If you run your PHP code directly, without the ajax call, `$_POST` will be empty because nothing has been posted to it. – Herbert Jul 27 '13 at 23:35
  • @herbert I think I understand what you mean and for the record I was **not** running this php file directly. I was clicking a link with the id of #project and it was sending the $.post to the php file. – i_me_mine Jul 27 '13 at 23:40
  • Apparently, using `isset($_POST['aid'])` solved your problem. – Herbert Jul 27 '13 at 23:56
  • @Herbert No it just avoided the error from coming out. That if else statement prevents $aid from ever being set by the $_POST and then returns my else statement of 'fail'. I am ultimately trying to get this file to echo back what I'm sending to it. This is part of a much bigger problem I narrowed down to this. After this file receives my post it has to query with the variable I passed over to it. Right now it never receives this variable. Hence the problem – i_me_mine Jul 28 '13 at 00:02
  • 1
    But you received 3 alerts from jQuery indicating that `data` was correctly returned. The only way that can happen is if PHP echoed `$aid`, which means `$_POST['aid']` was set. As @Sven said, use [Firebug](http://getfirebug.com/) to help sort this out. – Herbert Jul 28 '13 at 00:07
  • @Herbert the communication was just off there. I changed my code to that for just a moment. To test. It's back to the original post. Also that's why I was so upset. I receive three alert boxes. 2 of which are with the variable I send and one is from the one I get back. Yet I still receive the error with that variable saying the index is not set for $_POST. It makes 0 sense. Now you understand why I'm upset and this seems stupid to me – i_me_mine Jul 28 '13 at 00:10
  • @Herbert if you read the last paragraph of the **edit** you see I already stated this. I am using firebug. I see 0 errors with how the `jQuery` is performing. – i_me_mine Jul 28 '13 at 00:13
  • `isset($_POST)` is ALWAYS **true** regardless of whether any data is sent. Hence the error message. That's why everyone checks the specific variable, `isset($_POST['aid'])`. Are you having trouble with normal form posts? – Herbert Jul 28 '13 at 00:24
  • @Herbert nope, I can use my sign in, create forms, create accounts, get accounts, heck even create projects, all with $.post functions. This file for some reason is the only one not receiving and sending data back and forth – i_me_mine Jul 28 '13 at 00:27
  • What do you see in Firebug under Net > Params in Firebug? – Herbert Jul 28 '13 at 00:28
  • @Herbert see edit, I posted the Firebug – i_me_mine Jul 28 '13 at 00:35
  • 2
    `%0D%0A` is a line break – bfavaretto Jul 28 '13 at 01:00
  • @bfavaretto thank you. See my 2nd edit and response to Herberts answer. – i_me_mine Jul 28 '13 at 01:17
  • 1
    Your latest edit made think about ajax caching. Try `$.ajax` instead of `$.post`, and explicitly set `cache: false`. – bfavaretto Jul 28 '13 at 01:20
  • @bfavaretto if you post the code for it as an answer and it works I'll accept it. – i_me_mine Jul 28 '13 at 01:26
  • @bfavaretto: caches get me everytime. I should've thought of that. Go ahead and post your answer because that's the only thing it _can_ be at this point. Feel free to go into detail, I could use the education. Not to mention that this problem pops up a lot on Google. – Herbert Jul 28 '13 at 01:34
  • Except, it's getting the string "could not load projects table" instead of "fail". Wouldn't that require a round trip to the server? Am I missing something? – Herbert Jul 28 '13 at 01:44
  • @Herbert I'm not even sure it's cache, but it must be something obvious we're all missing... Let's wait until the OP tests it with caching disabled, and we'll see. – bfavaretto Jul 28 '13 at 02:00
  • 2
    Since the comments on this thread have become excessively long and the question is now an incredible wall of information that might or might not have any relevance to a still unclear problem, I suggest you ask a new question with the relevant information from your findings here. – Gordon Jul 28 '13 at 10:14

1 Answers1

1

POST -> aid 6 shows that the server is indeed receiving the data. Something else is clearing $_POST at some point before it reaches the if statement.

While you had require_once "$_SERVER[DOCUMENT_ROOT]/core/init.php"; commented out, your jQuery data contained the expected value. It was still commented out when you posted the Firebug info, hence the database connection error messages. Those messages, which you've since removed, indicates errors on line 7 of projects.php which tells me that your testing a file with more code than you posted here. It's not uncommon for people to show us a portion of their code, in fact, it's encouraged; however, in this case it's problematic because the error doesn't lie in the code you gave us.

Inorder to validate this finding and save your sanity, rename projects.php temporarily to projects.backup.php. Create a new file called, "projects.php" and run the following code (and ONLY the following code) through AJAX:

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

Incidentally, %0D%0A is the Windows® newline combo, CRLF (carriage return + line feed)

Herbert
  • 5,698
  • 2
  • 26
  • 34
  • Done, the div contains the 'fail' message. However in `FireBug -> NET -> XHR -> RESPONSE` I see 6. I see the same in `FireBug -> NET -> XHR -> HTML`. – i_me_mine Jul 28 '13 at 01:16
  • It's not possible for the response to be 6 and for AJAX to receive "fail". `$_POST['aid']` is either set or it isn't. It can't be both. – Herbert Jul 28 '13 at 01:25
  • thats what I thought, but I can post pictures if you want. The div contains 'false' and the firebug console contains 6 in both fields – i_me_mine Jul 28 '13 at 01:27
  • What bfavaretto [said](http://stackoverflow.com/questions/17903067/index-undefined-when-receiving-post-from-jquery?noredirect=1#comment26152751_17903067). :P – Herbert Jul 28 '13 at 01:36
  • I wasn't calling you a liar. I was just point out the fact that it's logically inconsistent. I think bfavaretto may be right about the cache. If ajax is retaining the old "false" value, then it'll keep giving you the same results no matter what you do. I ran into similar problems before and it's a nightmare to debug. – Herbert Jul 28 '13 at 01:41
  • Oh I know, I was just letting you know so that you could share my pain and disbelief, =) – i_me_mine Jul 28 '13 at 01:43