I am trying to assign a json array to a javascript array so that my JS functions can access the array.
So I have an ajax call to MySQL db to get a JSON array of data:
var data = [];
$.ajax({
type:"post",
url:"position.php",
dataType:'json',
success:function(jsonarray){
data=$.parseJSON(jsonarray);
}
});
position.php:
<?php
include 'dbconnect.php';
$sql = "SELECT pid, posX, posY FROM posTable;";
$result = $conn->query($sql);
$myrows = $result->num_rows;
$return=array();
if ($result->num_rows>0){
while($row=$result->fetch_assoc()){
$return[]=array((int)$row['pid'],(int)$row['posX'],(int)$row['posY']);
}
}else{
echo "[]";
}
echo json_encode($return);
$conn->close();
?>
This gives an output like this:
[[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
And from this I want the following two dimensional array so that I can access its memebers in this form:
data[i][j]
data => [[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
However when I execute the code I keep getting the following error:
Uncaught SyntaxError: Unexpected token , in JSON at position 1
What am I doing wrong?
jQuery will automatically parse a JSON response before populating the success function's first argument.
$.parseJSON(jsonarray); calls toString() on your array and then tries to parse it as JSON, which it isn't (because Array.prototype.toString() doesn't convert to JSON).
Just don't try to parse it again.
Related
Following are my code i want to retrieve values from JSON which is returned by php file.
following are my php code.
$i=1;
foreach($chck as $value){
$qry_a = "SELECT ans_tags FROM wp_pp_actionphp_answers where id=".$value['answer_id'];
$result_a = $wpdb->get_results( $qry_a );
$final[]=array(
"question_id_$i"=>$value['question_id'],
"answer_id_$i"=>$value['answer_id'],
"ans_tags_$i"=>$result_a[0]->ans_tags,
"test_attempt_$i"=>$test_count_by_email,
);
$i++;
}
$jsonstring = json_encode($final);
print_r($jsonstring);//Return JSON to javascript file
exit();
Following are my javascript code.
function get_result(result_id,email){
var data='result_id=' + result_id+"&email="+email;
$.post(
ajaxurl + '?action=actionphp_get_result',
data,
function(result){
document.write(result);
}
);
}
following are my result.
[{"question_id_1":"2","answer_id_1":"3","ans_tags_1":"","test_attempt_1":"181"},{"question_id_2":"1","answer_id_2":"1","ans_tags_2":"This is a tag test","test_attempt_2":"181"}]
How can i retrive values.
You can simply parse the JSON in Javascript:
var data = "{\"a\": 1, \"b\": 2, \"c\": [1,2,3]}"; // your result
var obj = JSON.parse(data);
Then you can simply access the data stored in obj:
obj.a -> 1
obj.b -> 2
obj.c[0] -> 1
EDIT (thanks to Webomatik):
Of course you have to have to pay attention to your result. In your case your result is an array, so you could access the single objects in the array via
obj[0].question_id_1 // "2"
obj[0].answer_id_1 // "3"
in mybb forum with ajax call i get json array as result.
php code:
<?php
define("IN_MYBB", 1);
define('THIS_SCRIPT', 'getComuni.php');
header('Content-Type: application/json');
....read data form DB
$comuni = array();
while($row = $db->fetch_array($query))
{
$comuni[$row['ID']] = $row['Descrizione'];
}
echo json_encode($comuni);
?>
Javascript:
function showComuniCompleted(response)
{
var json = response.responseJSON;
for(var k in json)
{
$("cboComuni").insert(new Element("option", {value: k}).update(json[k]));
}
}
json variable is Object not Array when empty get error in for istruction.
Is there a way to convert json variable from Object to Array or some way to check if empty?
In page load I am calling this function
function myFunction(selectedCinemaID) {
$.ajax({
type: "POST",
url: "show_details.php",
data: {cinema_id: selectedCinemaID }
}).done(function( show_list ) {
console.log(show_list.length);
});
And my code in show_details.php
$query = "SELECT * FROM `show` WHERE cinema_id=2;";
$result = mysql_query($query);
if($result){
$show_list = array();
while($row = mysql_fetch_array($result)){
array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));
}
echo json_encode($show_list);
} else {
echo mysql_error();
}
In my database I have only two row and three column but the length showed in the console is 64. But according to the database length should be 2. console.log(show_list) output [["2","2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] but it seems everything here is treated as an array element or string. What is wrong in this code?
You haven't told jquery that you're sending JSON. As such, it'll treat the json text that the server is sending as text. That means
console.log(show_list.length);
is outputting the length of the json string, not the count/size of the array you're building in PHP.
You need either
$.getJSON(....);
or
$.ajax(
dataType: 'json'
...
)
However, note that if your mysql query fails for any reason, then outputting the mysql error message as your are will cause an error in jquery - it'll be expecting JSON, and you could potentially be sending it a mysql error message, which is definitely NOT json.
Once you switch to JSON mode, you should never send anything OTHER than json:
if (query ...)
output json results
} else {
echo json_encode(array('error' => mysql_error()));
}
The JavaScript function .length is counting the length of the entire serialized array string. You need to parse it first:
.done(function( show_list ) {
var data = JSON && JSON.parse( show_list ) || $.parseJSON( show_list );
console.log( data.length );
});
Thanks,
Andrew
I am having a difficulty retrieving a series of json data from php to my JavaScript, file..
Firstly, I have a series of json data stored in an array in php, and echoing each by wrapping it in the for loop to my JavaScript file,
<?php
$result = array('{"one": "test","two": "test"}','{"three": "test","four": "test"}');
for ($i = 0; $i < count($result); ++$i) {
echo $result[$i];
}
?>
in my JavaScript,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
My console does not display anything at all, not recognizing each array element as a json..
but if I send just one array element specifically, for example,
echo $result[0];
then it successfully displays,
Object {one: "test", two: "test"}
why can't I pass a series of json data in an array from php in my ajax call?
It doesn't work because you are generated malformed JSON. The output of your script is
{"one": "test","two": "test"}{"three": "test","four": "test"}
When you access the first element of the array only you get
{"one": "test","two": "test"}
Which is valid.
PHP has json_encode which will do this work for you, so your code would become
$result = array(
array('one' => 'test', 'two' => 'test'),
array('three' => 'test', 'four' =>'test')
);
echo json_encode($result);
giving the output
[{"one":"test","two":"test"},{"three":"test","four":"test"}]
Your code will output this:
{"one": "test","two": "test"}{"three": "test","four": "test"}
This is invalid JSON, so obviously will not work. (Try parsing it with JSON.parse and you'll see.)
You actually need to send the data as an array, so replace your for loop with a simple json_encode call:
echo json_encode($result);
This will output
[{"one": "test","two": "test"},{"three": "test","four": "test"}]
This is valid JSON, and can be parsed into a Javascript array.
Also can you this script
function doj($json){
$result = json_encode($json);
return json_decode($result, true);
}
$json = array(
'{"one": "test","two": "test"}',
'{"three": "test","four": "test"}'
);
$j = doj($json);
foreach($j as $k=>$v){
$extractagain = json_decode($v);
print_r($extractagain);
}
and the output is:
stdClass Object ( [one] => test [two] => test ) stdClass Object ( [three] => test [four] => test )
I'm getting a JSON array from server :
mysql_select_db('******') or die("Error connecting to db.");
$res = mysql_query("SELECT DISTINCT(valeur) as val FROM *****") or die(mysql_error());
while($r = mysql_fetch_assoc($res)){
$tab[] = $r['val'];
} echo json_encode($tab);
unset($tab);
And :
$.getJSON("autocomp.php?id=valeur", function(data){
$("#other-valeur").autocomplete({delay: 100, source: data, dataType: 'json'});
});
The server returns me a correct json array :
["UMTS","RAN","Swap","Regions","Brasseur",...]
But when i start typing something in the input, i get this message in firebug:
c is null
In the jquery code...
What i dont understand is that i'm doing the exact same thing for another input on the same page, and it work perfectly, the json array look the same, the code is the same...
It will not work because autocomplete need the property "id" and "value" in your json. this is not the case here.
Try to return the json like that :
[{"id":"1","value":"UMTS","comment":"umts comment"},
{"id":"2","value":"RAN","comment":"ran comment"},
{"id":"3","value":"Swap","comment":"swap comment"}]
in your php, also return a content type of : application/json