0

I have a php file where I am pulling data from a database and I want to access its contents in javascript. When I try to access the array with data[0].card_id I get "undefined".

Here is my javascript

$(document).ready(function() {
  var userId = 1;
  var updateUrl;

  $.ajax({
    type: "POST",
    url: "url",
    data: {userId: userId},
    success: function(data) {
      alert(data[0].card_id);
      var suffix = ".html";
      fb.start('../Animations/' + updateUrl[0].card_id + suffix); 
    }
  });
}

Here is my php file

<?php

include('connect.php');

$user_id = $_POST['userId'];

$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL";
}

$select = "SELECT card_id FROM decks WHERE id=$user_id ORDER BY order_num";
$result = mysqli_query($db, $select);

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
    $animation[] = array(
        'card_id' => $row['card_id'],
    );
}

json_encode($animation);
echo $animation;
mysqli_close($db);
?>

The array contains the following data

Array ( [0] => eating [1] => mummy

etc.. )

David Folksman
  • 225
  • 3
  • 8
  • 24
  • 2
    You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) against. – Quentin Jun 15 '13 at 18:35
  • Thanks i've read about sql injection and i'm going to sort this out as soon as my application is built. – David Folksman Jun 15 '13 at 18:45

2 Answers2

1

You have two problems.

First: You aren't doing anything with the return value of json_encode.

Second: The PHP is claiming it is sending back HTML, so it wouldn't parsed as JSON anyway.

header("Content-Type: application/json");
echo json_encode($animation);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Sorry, im quite new and I dont understand your answer, could you elaborate a bit more on header("Content-Type: application/json"); ? I understand the second part, i've made that mistake before silly me :( – David Folksman Jun 15 '13 at 18:39
  • When an HTTP server responds with a resource, it says what kind of resource it is. `application/json` means "a JSON text". `text/html` means "An HTML document". `image/png` means "A PNG formatted image". PHP will tell the server to send `text/html` unless you say otherwise. jQuery will look at the content-type and use that to decide what sort of parsing to do on the response before putting it into `data`. – Quentin Jun 15 '13 at 18:41
  • Thanks, do I just put the header after the php tag like ` – David Folksman Jun 15 '13 at 18:43
  • In practical terms, it doesn't matter where you set the header so long as it is before you give any output. For the sake of sanity, I'd put it between your business logic and your view logic (i.e. where I put in in the example in the answer). – Quentin Jun 15 '13 at 18:45
  • Unless you have added the header, the data will be treated as HTML, so that result is to be expected. If you still have that problem after adding the header, `console.log(data)` to find out exactly what it is. – Quentin Jun 15 '13 at 18:46
  • isnt console.log(data) the same as doing the alert but the output goes to the console instead? – David Folksman Jun 15 '13 at 18:47
  • @DavidFolksman — No. Since (a) I said to do it on `data` not `data[0].card_id` and (b) It won't stringify it first so you can examine the complete data structure. – Quentin Jun 15 '13 at 18:48
  • Right, sorry. So I did it on data and got eating,mummy,selectMummy,plate,selectPlate – David Folksman Jun 15 '13 at 18:48
1

You need to add dataType: "json" to your ajax call.

$.ajax({
    type: "POST",
    dataType: "json",
    url: "url",
    data: {userId: userId},
    success: function(data) {
        alert(data[0].card_id);
        var suffix = ".html";
        fb.start('../Animations/' + updateUrl[0].card_id + suffix); 
    }
});

http://api.jquery.com/jQuery.getJSON/

There is no need to change MIME type, jQuery will handle this.

ghost
  • 769
  • 5
  • 11
  • It makes much more sense to tell the server to say "This is JSON" instead of letting it lie and say "This is HTML" then it does to tell jQuery to ignore what the server claims. – Quentin Jun 15 '13 at 18:41
  • I added the dataType but still get "undefined" in my alertbox :( – David Folksman Jun 15 '13 at 18:44
  • I wouldn't call hacking around a bad HTTP response "just fine". It's a substitute for doing it right. – Quentin Jun 15 '13 at 18:47