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
Related
I'm working with JavaScript and PHP using arrays, the first step is create the array, here
var ListaA=[];
var i = 0, len = options.length;
while (i < len){
var tmp = {
'proyecto':'test',
'pendientes1':0,
'pendientes2':0,
'terminadas1':0,
'terminadas2':0,
'solucion':0
};
ListaA.push(tmp);
i++;
}
Then i send it to my PHP file like this
var laLista = JSON.stringify(ListaA);
$.get("php/operation.php?test="+ {'test' : laLista }, function( data ){
var tmp = {
'proyecto':""+value['proyecto']+"",
'pendientes1':""+value['pendientes1']+"",
'pendientes2':""+value['pendientes2']+"",
'terminadas1':""+value['terminadas1']+"",
'terminadas2':""+value['terminadas2']+"",
'solucion':""+value['solucion']+""
};
ListaA.push(tmp);
});
As you can see above i have ready the code to get the data which represents the array sent by the PHP file, so i got covered that part, my issue here is in my PHP file, here.
$arrayWork = json_decode($_POST['test']);
Then i want to loop, this time, just for testing i'm just taking one of the values and incresing it to watch the result, like this
foreach($arrayWork as $value){
$value['pendientes1']++; // this is not working for me
}
I got the following: "invalid argument supplied in foreach". So, what's wrong with my code? and which is the properly way to loop it and return it to my JavaScript?
I hope you can help me out with this issue. Thank you for your time and attention, good night.
Using this code
$arrayWork = json_decode($_POST['test']);
your json isn't really converted into an associated array, look at below
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc
When TRUE, returned objects will be converted into associative arrays.
To convert json object into an array just add true to the second parameter to it
$arrayWork = json_decode($_POST['test'], true);**strong text**
To increment an index value in an array
foreach($arrayWork $key => as $value){
$arrayWork['pendientes1']++;
}
Edited.
also since you are using $_POST method change your ajax from $.get to $.post
$.post("php/operation.php?test="+ {'test' : laLista }, function( data ){
var result = JSON.parse(data); // parse json string into json object
...
});
If you want to read $_POST, you have to make a POST request:
$.ajax({
url:'php/operation.php',
type:"POST",
data: { test: ListaA },
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
You can't use $.post, because you have to set the contentType to JSON.
Important: you don't need to run JSON.stringifyyourself, jQuery will take care of it for you - so pass the original ListaA array.
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.
After an ajax call, my php script echos out a json_encoded multidimensional array. When I loop over the array in my javascript, it iterates over each individual character instead of the top-level array elements. Why?
js
$('.test').on('click',function(){
$.ajax({
url: 'http://domain.com/my/script,
}).done(function(multidimensionalArray) {
console.log(multidimensionalArray); //outputs the seemingly correct array
console.log(multidimensionalArray.length); //outputs number of characters (instead of the expected 20...)
})
});
php
public function calledByAjax() {
$items = namespace\items\GetList::getAll(array(
'limit' => 20 // This appropriately limits the results to 20, which is why 20 is expected above in the js
));
$items_array = array();
foreach($items as $key=>$item){
$temp = array (
'attr1' => $item->getPrivateVar1(),
'attr2' => $item->getPrivateVar2(),
'attr3' => $item->getPrivateVar3(),
);
$items_array[$key] = $temp;
}
echo json_encode($items_array);
exit(0);
}
console.log(multidimensionalArray)
[{"attr1":"The variable","attr2":"the variable","attr3":"the variable"},...
...so on for 20 items...
]
console.log(multidimensionalArray.length)
1562
You are not working with an object but with a string.
You need to make sure that the returned output from your php script (a string) gets parsed as json. The easiest way to do that is to specify the dataType:
$('.test').on('click',function(){
$.ajax({
url: 'http://domain.com/my/script',
dataType: 'json' // the expected data type is json,
// jQuery will parse it automatically
}).done(function(multidimensionalArray) {
console.log(multidimensionalArray); //outputs the seemingly correct array
console.log(multidimensionalArray.length); //outputs number of characters (instead of the expected 20...)
})
});
I am echoing two array values from PHP. How do I differentiate these values in ajax.
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$i]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$i]['firstname'] = $row1['firstname'];
$traineravaildetails[$i]['lastname'] = $row1['lastname'];
$traineravaildetails[$i]['emailidvalue'] = $row1['email_id'];
$i++;
}
echo json_encode($trainerdetails);
echo json_encode($traineravaildetails);
}
?>
function loadavailabletrainers (m) {
$.ajax({
url: 'assignavailtrainers.php',
data: { action:'test' },
type: 'post',
success: function(output) {
console.log(output);
}
});
}
I've seen a examples of multiple return values from php and handling them in ajax, but I didn't understand them. Can someone please explain how to differentiate output values in my case?
OUTPUT:
[[{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"2","idi":"2"}],{"7":{"facilitatorid":"1","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*******#gmail.com"},"8":{"facilitatorid":"2","firstname":"Vignesh","lastname":"Anandakumar","emailidvalue":"vign*****#gmail.com"},"9":{"facilitatorid":"3","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*****#hotmail.com"},"10":{"facilitatorid":"4","firstname":"Vignesh","lastname":"Anand","emailidvalue":"****#live.com"}}]
It's a nice practice to send only one stream of values so you can process it all at once.
First, you could create a container array:
$data = array('trainerdetails' => $trainerdetails,
'traineravaildetails' => $traineravaildetails);
Then
echo json_enconde($data);
This will generate a merged output.
The encoded string returned by your PHP code needs to be decoded in the client side (more details: Parse JSON in JavaScript?). Because of that, you could use $.getJSON(), which is an alias for a specific call to $.ajax (doc: http://api.jquery.com/jquery.getjson/).
The 'success' function will pass a 'key'=>'value' array data. In this case you'd need to treat the value as they may contain extra levels of arrays. It helps if you can visualize your data structure as tree view, like this: http://jsonviewer.stack.hu/ (paste your output there).
I hope it helps!
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