0

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. Then I asked a question here and again things quickly moved off topic. I decided to accept the answer that solved the original problem and move on. I now believe we have narrowed the problem down to a very specific question.

This problem now makes 0 sense to me. I have the following code

jQuery

$('#projects').click(function (e) {
$.trim(aid);
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]/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 extremely confused. If I simplify things and get to the root of the problem by changing 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'! Which means the file is receiving my $_POST['aid'] variable and correctly setting it inside PHP. Now if I change the code back, again I receive nothing.

However if I change the original PHP file to this

<?php

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

    $aid = '6';             
    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());
    }    
?> 

Then run the PHP file directly the query is successful and the page loads the table its dynamically creating. Which makes my head spin so much I want to puke.

So in review. The aid variable is set to 6, there is no question. If I simplify my PHP file it receives the $_POST['aid'] variable, takes the data, sets the PHP $aid variable and echo's it back. However if I try and insert it into my query to inflate my table I get nothing. Now if I change the PHP file to not rely on the $_POST['aid'] variable it works. So what the heck is going on here? The PHP file works without the post and the post works without the table inflation query.

I really hope someone can help me figure this out because I am just totally lost

EDIT

I changed my php file around for testing. It now looks EXACTLY like this. Sorry for the wall

<?php

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

    if(isset($_POST['aid'])) {  
        $aid = $_POST['aid'];
            echo $aid;      
        try {
            $query_projectInfo = $db->prepare("
                SELECT  projects.account_id,
                        projects.project_name,                  
                        projects.pm,    
                        projects.apm,
                        projects.est_start,
                        projects.est_end,
                        projects.contact,                   
                        projects.trips,
                        projects.tasks,
                        projects.perc_complete,
                        projects.bcwp,
                        projects.actuals,
                        projects.cpi,
                        projects.bcws,
                        projects.bac,
                        projects.comments,
                        projects.status,
                        projects.project_revenue,
                        projects.profit_margin,
                        projects.pm_perc,
                        projects.audited         
                FROM projects
                WHERE account_id = ?                        
            "); 

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

                echo "<table class='contentTable'>";
                echo "<th class='content_th'>" . "Job #" . "</th>";
                echo "<th class='content_th'>" . "Project Name" . "</th>";
                echo "<th class='content_th'>" . "PM" . "</th>";
                echo "<th class='content_th'>" . "APM" . "</th>"; 
                echo "<th class='content_th'>" . "Est. Start" . "</th>";
                echo "<th class='content_th'>" . "Est. End" . "</th>";
                echo "<th class='content_th'>" . "Contact" . "</th>";
                echo "<th class='content_th'>" . "Trips" . "</th>";
                echo "<th class='content_th'>" . "Tasks" . "</th>";
                echo "<th class='content_th'>" . "% Complete" . "</th>";
                echo "<th class='content_th'>" . "BCWP" . "</th>";
                echo "<th class='content_th'>" . "Actuals" . "</th>";
                echo "<th class='content_th'>" . "CPI" . "</th>";
                echo "<th class='content_th'>" . "BCWS" . "</th>";
                echo "<th class='content_th'>" . "BAC" . "</th>";
                echo "<th class='content_th'>" . "Comments" . "</th>";
                echo "<th class='content_th'>" . "Status" . "</th>";
                echo "<th class='content_th'>" . "Project Revenue" . "</th>";
                echo "<th class='content_th'>" . "Profit Margin" . "</th>";
                echo "<th class='content_th'>" . "PM%" . "</th>";
                echo "<th class='content_th'>" . "Audited" . "</th>";

                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>";
                    echo "<td class='content_td'>" . $row['pm'] . "</td>";
                    echo "<td class='content_td'>" . $row['apm'] . "</td>";
                    echo "<td class='content_td'>" . $row['est_start'] . "</td>";
                    echo "<td class='content_td'>" . $row['est_end'] . "</td>";
                    echo "<td class='content_td'>" . $row['contact'] . "</td>";
                    echo "<td class='content_td'>" . $row['trips'] . "</td>";
                    echo "<td class='content_td'>" . $row['tasks'] . "</td>";
                    echo "<td class='content_td'>" . $row['perc_complete'] . "</td>";
                    echo "<td class='content_td'>" . $row['bcwp'] . "</td>";
                    echo "<td class='content_td'>" . $row['actuals'] . "</td>";
                    echo "<td class='content_td'>" . $row['cpi'] . "</td>";
                    echo "<td class='content_td'>" . $row['bcws'] . "</td>";
                    echo "<td class='content_td'>" . $row['bac'] . "</td>";
                    echo "<td class='content_td'>" . $row['comments'] . "</td>";
                    echo "<td class='content_td'>" . $row['status'] . "</td>";
                    echo "<td class='content_td'>" . $row['project_revenue'] . "</td>";
                    echo "<td class='content_td'>" . $row['profit_margin'] . "</td>";
                    echo "<td class='content_td'>" . $row['pm_perc'] . "</td>";
                    echo "<td class='content_td'>" . $row['audited'] . "</td>";
                    echo "</tr>";

                }
                echo "</table>";                
        } catch(PDOException $e) {
            die($e->getMessage());
        }   
    } else {    
        echo 'could not load projects table';
    }

    ?>

The response I get in my browser is now this

6<table class='contentTable'><th class='content_th'>Job #</th><th class='content_th'>Project Name</th><th class='content_th'>PM</th><th class='content_th'>APM</th><th class='content_th'>Est. Start</th><th class='content_th'>Est. End</th><th class='content_th'>Contact</th><th class='content_th'>Trips</th><th class='content_th'>Tasks</th><th class='content_th'>% Complete</th><th class='content_th'>BCWP</th><th class='content_th'>Actuals</th><th class='content_th'>CPI</th><th class='content_th'>BCWS</th><th class='content_th'>BAC</th><th class='content_th'>Comments</th><th class='content_th'>Status</th><th class='content_th'>Project Revenue</th><th class='content_th'>Profit Margin</th><th class='content_th'>PM%</th><th class='content_th'>Audited</th></table>

Which means two things. The aid variable is being passed and set. However when I run it in my query it fails. But if I put $aid = '6'; then bind aid as a value it works.

WHY?

2nd EDIT

So through the help of others we found out this was a js error not a php one. The variable is being set to 6 in the js but it has some hidden characters and I think I found them. When I look in firebug I see this as the source

aid=%0D%0A6

which is supposed to be a line break right? I think that's what's causing the errors.

This is how I'm getting aid

var title;
var aid;
$(".sa").click(function (e) {
    title = $(this).text();
    $.post('core/functions/getAccountId.php', { 
        title: title              
    })
    .done(function(data) {
        aid = data;     
        $("#acc_title").html(title);    
        $('#accountsSelectDiv').hide();
        $('#acc_home').fadeIn(1000);
        $('#home_div').show();      
    })
    .fail(function(jqXHR, status, error) {
        alert(error);
    });     
});

This might be because of how I'm getting it, I have no idea. How do I remove the extra characters in the source though? That is what I think the problem is

Community
  • 1
  • 1
i_me_mine
  • 1,435
  • 3
  • 20
  • 42
  • I wonder if the (jQuery-submitted) AID value contains spaces or similar that the hardcoded AID does not. That'd definitely affect a WHERE clause. – Winfield Trail Jul 28 '13 at 19:59
  • http://www.php.net/manual/en/pdostatement.rowcount.php – Musa Jul 28 '13 at 19:59
  • @sudowned this mixed with the recent answer by FrancescoMM makes total sense. I edited my question to add $.trim() around aid. This should solve that problem right? Because it's still happening – i_me_mine Jul 28 '13 at 20:10
  • Does updating ```$query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);``` to ```$query_projectInfo->bindValue(1, $aid, PDO:: PARAM_INT);``` have any effect? – foiseworth Jul 28 '13 at 20:12
  • @foiseworth oh man, I thought you had it. I was like *punch myself in the face*. However no, it has no effect. – i_me_mine Jul 28 '13 at 20:14
  • @Musa you were partly correct. My $count in my if statement was holding up the table execution. However it still has no value in my query. which is just crazy – i_me_mine Jul 28 '13 at 20:18
  • Have you tried `data: {'aid' : '6'}` in your ajax call? Does that make any difference. This would at least tell you if the `aid` in js that's the problem. – vee Jul 28 '13 at 20:21
  • Just before ```$query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);``` could you ```print_r($aid);die();`` and post the output? – foiseworth Jul 28 '13 at 20:21
  • `$query_projectInfo->rowCount();` will not give you the number of rows selected. – Musa Jul 28 '13 at 20:22
  • @Musa I understand that after reading the documentation. Thank you for pointing it out though. This was helpful in getting closer to a solution – i_me_mine Jul 28 '13 at 20:23
  • @vinodadhikary i think it somehow has to be the value of the js variable. see the edit. It just doesn't make sense to me that the js variable which equals 6 and the hard coded $aid = '6', would be any different from each other – i_me_mine Jul 28 '13 at 20:25
  • @foiseworth I did something similar, check the edit and let me know if that's what you were looking for – i_me_mine Jul 28 '13 at 20:25
  • I guess trimming and cleaning $aid doesn't help? `$aid=preg_replace('/[^0-9]+/','',$aid);`. Have you tried to do like @vinodadhikary said in his comment? – FrancescoMM Jul 28 '13 at 20:26
  • @vinodadhikary you and FrancescoMM were right, if I use `{'aid' : '6'}` it works. So what the heck? How do i fix this? – i_me_mine Jul 28 '13 at 20:27
  • Post the content of the other file how you are setting the value of `aid`, at least now we all know that the problem is in javascript and not in php. Also make sure not to leave out any closing parenthesis or braces like you've done in the click handler. – vee Jul 28 '13 at 20:30
  • @vinodadhikary indeed, and I'm grateful to know the source, thanks. I will post it asap – i_me_mine Jul 28 '13 at 20:31
  • @vinodadhikary posted the 2nd edit. I think FrancescoMM may already have my answer though – i_me_mine Jul 28 '13 at 20:38
  • @i_me_mine, trim the data in the file where you're setting the `aid` (i.e. `aid = $.trim(data);`), also keep in mind that this being an ajax response, you might get confused in the future if your other script doesn't return any record unless you click this `.sa` first. – vee Jul 28 '13 at 20:40
  • 1
    if the "6" is loaded by js from a file (including a PHP script), be sure it is not saved as UTF-8 with BOM or that will add an invisible char before it http://en.wikipedia.org/wiki/Byte_order_mark – FrancescoMM Jul 28 '13 at 20:42
  • @FrancescoMM the source its coming from is through a `PHP` file and that `PHP` file is indeed grabbing the data from a utf8_unicode_ci table. – i_me_mine Jul 28 '13 at 20:47
  • BOMs are text file things, not db things, so I'd check the PHP file that reads the table if it has a BOM (the PHP file itself) if you are sure the table contents are ok. If you are not sure, take the whole PHP file down and change it with something like `` if it is ok try putting all the old file contents inside again except the first chars.. if it breaks again, it' the table contents – FrancescoMM Jul 28 '13 at 20:59
  • Or just trim($response) at the end of getAccountId.php and live happily ever after? :) – FrancescoMM Jul 28 '13 at 21:07
  • `.done(function(data) { aid = data.trim(); ...` or http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript – FrancescoMM Jul 28 '13 at 21:14

2 Answers2

1

* EDIT *

Although this is the accepted answer, it is quite wrong, in the sense it has nothing to do with the real solution. That came out of the comments, both here and those to the question, and in the end it was a CR/NL ("\r\n") combination in the string that came from a JS file that read it from another PHP file... you get the idea. "If strange things happen, check for hidden chars!"


I have no time now, working at 10PM on sunday! But..

This is your problem, if I understand:

when you define data: {'aid' : aid} aid is not defined yet!

Don't get confused by the fact that $('#projects').click(function (e) { alert(aid); is before, on top of it. It is called when you click, so it is executed much later, when probably aid is defined. While {'aid' : aid} takes the value of aid at the time the code is parsed, so if aid is not defined on top of it it will be undefined.

If you fut a aid="hello"; before, out of the click scripts you will see it work or at least it will show "hello".

You have to be careful with JQuery and Ajax and callbacks. Think exactly at what time everything is executed, do not rely on "written on top= executed first".

Hope this is your problem and you may solve it, g'nite.. :)

One more thing.. one solution is to prepare the Ajax stuff inside the click handler.

$("..").click() { // prepare stuff here // {'aid' : aid} here aid is defined }

FrancescoMM
  • 2,845
  • 1
  • 18
  • 29
  • Sorry for the late work night! I have them too, I understand. I would say you were correct but in FireFox's Firebug when I look at the POST method it still holds the value 6, which should be after it was sent correct? Also The simplified version of my `php`, would not be able to take this variable, which it does, and then returns it. – i_me_mine Jul 28 '13 at 20:12
  • aid is defined in another .js file that's included *before* this one. The aid variable has value. If I add echo $aid; to my php file, I get it back – i_me_mine Jul 28 '13 at 20:17
  • @i_me_mine ok, so probably it's something else, you may write a hardcoded {'aid' : 6} so you are sure you exclude any errors or strangenes on the js/setting aid side – FrancescoMM Jul 28 '13 at 20:20
  • Some bloody char like a zero or a BOM in the value? Try cleaning it from PHP see my comment. If then it works you may start finding the cause. You will probably search for the error in the js that generates the 6 value – FrancescoMM Jul 28 '13 at 20:29
  • arg, so much time wasted on this stupid problem, and for it to be such a silly reason. Ok just saw the comment, I'll try it, thanks – i_me_mine Jul 28 '13 at 20:30
  • Go up in reverse in the chain where the 6 is generated, trying to find where that char comes from. use something like escape() to find what is inside aid that looks like a 6 but is not! – FrancescoMM Jul 28 '13 at 20:32
  • Use escape() in js or htmlentities() twice in PHP htmlentities(htmlentities($aid)) – FrancescoMM Jul 28 '13 at 20:33
  • Thanks for staying up late with me. I now know the proper source of the problem. I can make a new question to find the information I need to solve it. I tried unescape() and htmlentities() and they didnt work. I think I'm doing it wrong though. Answer accepted – i_me_mine Jul 28 '13 at 20:56
  • Wow, thanks, first time I get an answer accepted that has nothing to do with the real solution! :) I will edit it a bit. In Js you should escape, not unescape, you want to see the codes of hidden chars. – FrancescoMM Jul 28 '13 at 21:04
  • Francesco thank you so much my friend. You got the accepted answer because you were correct. You just had the correct answer in the comments above ;). What finally worked for me was this line `aid = data.trim();`. Just so you and everyone else knows – i_me_mine Jul 28 '13 at 21:17
  • Be careful that String.trim() will not work on ie7, check the link in my comment to the main question for a solution that implements trim in older browsers. From that link: "Worth noting that in jQuery, $.trim(str) is always available." So maybe `aid = $.trim(data);` is better. Bye! – FrancescoMM Jul 28 '13 at 21:20
0

This may not work but try changing:

type: 'post',

to

type:'POST',

If it's case sensitive then it would not recognise it and default to $_GET, which would explain why looking for $_POST['aid'] isn't working.

JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29