0

I have a strange problem..

When i try to access my json code with the corresponding number [0], [1] etc.. I just get the first character of the object.

First of my code:

test2.php

if(isset($_POST['getCustomersArray'])){
$runQuery = mysql_query($Query) or
 die("SQL: $Query)<br />".mysql_error()); 
$numrows = mysql_num_rows($runQuery); 
$array = array(array());
for($i = 0;$i <= 2; $i++){
 $row = mysql_fetch_array($runQuery);
 $array[$i]['namn'] = $row['fornamn'];
}
 print json_encode($array);
}

scriptfile.js

$.ajax({
 type:"POST",
 url: "test2.php",
 data: "getCustomersArray=true",
 datatype: "JSON",
 cache: false,
 success: function(json) {
 console.log(json[0]);
 }
});

The result (from console.log(json[0])):

[

The result from just console.log(json):

[{"namn":"the first name"},{"namn":"The secound name"},{"namn":"the third name"}]

Im not sure why the squarebrackets are there but maybe they should be?

Ive been fuzzing with this problem for a while now and im sure its something stupid. Please help.

asked Nov 8, 2012 at 16:26

3 Answers 3

6

You have an incorrect option in the AJAX settings,

datatype: "json",

It should be:

dataType: "json",
answered Nov 8, 2012 at 16:28
Sign up to request clarification or add additional context in comments.

3 Comments

try json in lowercase. dataType: "json"
@Martin Aha, I thought jQuery lowercases it by default.
I also thought that to be honest, but it seems not, haha!
1
datatype: "JSON",

supposed to be

dataType: "json", // json in lowercase and T has to be captalized
answered Nov 8, 2012 at 16:30

Comments

1

Make sure you have the following code:

if(isset($_POST['getCustomersArray'])){
$runQuery = mysql_query($Query) or
 die("SQL: $Query)<br />".mysql_error()); 
$numrows = mysql_num_rows($runQuery); 
$array = array(array());
for($i = 0;$i <= 2; $i++){
 $row = mysql_fetch_array($runQuery);
 $array[$i]['namn'] = $row['fornamn'];
}
header("Content-Type: application/json; charset=UTF-8");
print json_encode($array);
}

Here you need to set the content-type to application/json and set the correct charset to avoid any cross-browser issues. Take a look at the following tutorial from my website which should cover all of this and perhaps some improvements to your code: PHP jQuery Search Tutorial - using JSON object the proper way

Hope this helps :)

Andrew Barber
40.3k20 gold badges98 silver badges124 bronze badges
answered Nov 8, 2012 at 16:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.