0

I have an ajax call that posts data to a php script and returns data. If I echo the data in the php script, I can alert it fine in javascript. But if I return it as json, the alert just shows nothing.

my javascript

  $.ajax({
                type: "POST",
                url: url,
                async: false,
                data: {1:'Home', 2:'About', 3:'Contact'},
                success: function(data){
                            alert(data);
                         //manipulate returned data here
                ));

                }
            });

my php

function get_latest() {
    $stack = array(); 
    foreach($_POST as $key => $value) {
        $tmpRec = db_fetch_object(db_query('SELECT * FROM node_revisions WHERE nid = "%s"', $key));
        $arr = array($key => array('timestamp' => $tmpRec->timestamp, 'body' => $tmpRec->body));
        array_push($stack, $arr);   
    }

   echo '<pre>' . print_r($stack,1) . '</pre>'; //works and comes up in alert
    echo json_encode($stack); //Shows nothing


}

Is there another way to do this? I need the server to send the data back in a format that I can manipulate in javascript.

Billie
  • 231
  • 6
  • 15
  • show us `var_dump($stack);` please – Marek Sebera Aug 30 '11 at 16:20
  • 1
    That should work. Are you sure the JSON encode is working? Try this as your last line: `if (!function_exists('json_encode')) echo 'No JSON functions are available!'; else echo ($json = json_encode($stack)) ? $json : json_last_error();` – DaveRandom Aug 30 '11 at 16:22
  • 2 things; what is the value of url? Secondly your code is vulnerable to SQL injections. I would really look into using parameterized queries to save yourself future headaches – CountMurphy Aug 30 '11 at 16:23
  • No JSON functions are available! – Billie Aug 30 '11 at 16:28
  • Also, using `array_push()` to add one value to an array is pointless and inefficient, you are also adding overhead by assigning a value to the unnecessary variable `$arr`. Use `$stack[] = array(...);` instead. – DaveRandom Aug 30 '11 at 16:28
  • So json is not on there. Is this something I install? some php-json? – Billie Aug 30 '11 at 16:28
  • If you look down the comments on the [json_encode() manual page](http://uk3.php.net/manual/en/function.json-encode.php) you will find a couple of functions to make this functionality available when the JSON extension is not installed or you are using an old PHP build. – DaveRandom Aug 30 '11 at 16:30
  • Just tried it and http://uk3.php.net/manual/en/function.json-encode.php#100835 seems to work well. – DaveRandom Aug 30 '11 at 16:32
  • Rather than doing that, I have just installed json on the server. Since doing that, it now returns json properly! Thank you so much DaveRandom :) I have also modifed the way it gets the array the the code is more efficient. Do I still need to worry about sql injections? To safeguard myself and the server, any ajax requests sends over a secrety key. If the secret key matches, only then it will go and execute the sql commands. Is this sufficient? – Billie Aug 30 '11 at 16:40
  • ajax is all client side, meaning the client can modify what ever is sent. If the client sends the key, the user can get it. I like using PDO to prevent injections. Here is some sample code: $sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password"); $query="Select * from Northwind where Id=:ID; $stmt=$sql->prepare($query); $stmt->bindParam(':ID',$random_Id); $stmt->execute(); $dr=$stmt->fetch(); You can get your data out of $dr like you would a hash table. $dr['Column_name'] If the code is too messy I can put it in an answer (that way its formatted nicely) – CountMurphy Aug 30 '11 at 16:47
  • Any reason why this question was down voted? – CountMurphy Aug 30 '11 at 23:07
  • Down voted, what does that mean? Yes, could you please post the code as an answer. It looks like something I need to implement. Thank you – Billie Aug 31 '11 at 08:51
  • the -1 up top is part of a scoring system. The better the question, the higher the number. I'm not sure why someone gave it a negative value. – CountMurphy Aug 31 '11 at 15:13
  • more info on downvoting here: http://stackoverflow.com/faq#reputation – CountMurphy Aug 31 '11 at 18:31

1 Answers1

1

As requested in the comments here is an example of a parameterized query using PDO.

$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password"); 
$query="Select * from Northwind where Id=:ID"; 
$stmt=$sql->prepare($query);
$stmt->bindParam(':ID',$random_Id); 
$stmt->execute(); 
$dr=$stmt->fetch();
$sql=null;

Let's go over it line by line.

$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password");

$sql becomes a new PDO object (pdo can support many types of databases ( in this example we are using MYSQL).

$query="Select * from Northwind where Id=:ID;

note instead of providing an actual Id from the Northwind table, we are supplying ':ID.'

$stmt=$sql->prepare($query);

Here comes the fun part. The prepare statement sends our query string to the sql server. At this point the server knows the sql command we will run, but doesn't yet know the value of our variable.

$stmt->bindParam(':ID',$random_Id);

bindParam then sends the value of $random_Id to replace the ':ID.'

$stmt->execute(); 
$dr=$stmt->fetch();

our query is then executed, and the results are put into $dr. You can get your data out of $dr like you would a hash table. So lets say the northwind table looks like this:

+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id     | int         | NO   | PRI | NULL    |       |    
| Name   | varchar(10) | NO   | UNI | NULL    |       |
| Passwd | varchar(50) | NO   |     | NULL    |       |
| Salt   | varchar(50) | NO   | UNI | NULL    |       |
+--------+-------------+------+-----+---------+-------+

and we want the value of 'Name.' We would type something like this:

$userName=$dr['Name'];


$sql=null;

this line destroys the PDO object, freeing it from memory and closes the Database connection.

There are two advantages of doing SQL this way. The first is speed. If you needed to run that query above, I dunno 6 times with 6 different Ids you could do something like this after the prepare statement:

for($i=0;$i<=6;$i++)
{
 $stmt->bindParam(':ID',$i);
 $stmt->execute;
}

The server already has the main query, so we just send it whats changed. If we were doing something like this to insert many records, it would be much faster than putting the whole query in the loop.

The second benefit is it makes SQL injections impossible (the main reason I use it).

CountMurphy
  • 1,086
  • 2
  • 18
  • 39