How to fill javascript array from ajax data result - javascript

I have scripts like this.
javascript
$.ajax({
url : "load_data_person.php",
dataType:"json",
success:data_person(arrData)
});
function data_person(info_person){
var attr = [];
var len = [];
for(j=0;j<info_person.length;j++){
attr.push(info_person[j][0]);
len.push(info_person[j][1]);
}
return [attr, len];
}
How can I insert data to variable info_person like this:
info_person = [['fname',20],['lname',15],['addr',50]];
so I can get each value of attr and len?
Here is the script for data_person.php
<?php
$qStrPerson = mysql_query("SELECT atribut, len FROM tb_person ORDER BY fname ASC");
$arrFullPerson = array();
while($rStrPerson = mysql_fetch_array($qStrPerson)){
$arrFullPerson[] = array($rStrPerson[atribut],$rStrPerson[len]);
}
echo json_encode($arrFullPerson);
// it will return like this : Array 0 : ['fname', 20], Array 1 : ['lname',15], Array 2 : ['addr',50]];
?>
Thank you for your help.

You can use simple jquery to convert the JSON to Javascript array
var array = JSON.parse(your json string);

You can just format the array as you wanted in the server side and then echo it. While receiving the ajax response, you can simply
var info_person = json.parse(arData);
to convert the json-encoded value into javascript array.

Related

How to properly use JSON.parse?

I'm receiving a string with php and then parsing it:
String saved in db:
{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477}, {"totale_casi"235,"terapia_intensiva":123,"ricoverati_con_sintomi":154,"totale_ospedalizzati":344,"isolamento_domiciliare":654,"totale_positivi":786,"dimessi_guariti":988,"deceduti":675,"tamponi":2324}
Then I do
var myJson = '<?php echo $dataCustom; ?>';
This is how It prints on js
var myJson = '{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477}, {"totale_casi"235,"terapia_intensiva":123,"ricoverati_con_sintomi":154,"totale_ospedalizzati":344,"isolamento_domiciliare":654,"totale_positivi":786,"dimessi_guariti":988,"deceduti":675,"tamponi":2324}';
How to read a property?
Tried
var myJson = '<?php echo $dataCustom; ?>';
var customJsonData = JSON.parse(myJson);
I am trying to:
for(var d = 0; d < customJsonData.length; ++d) {
console.log(customJsonData[d]totale_positivi);
}
UPDATE
This is how I am constructing the json
var saveJsondata = {
"totale_casi": totCasiRegione,
"terapia_intensiva": totTerapiaRegione,
"ricoverati_con_sintomi": totSintomiRegione,
"totale_ospedalizzati": totOspedalizzatiRegione,
"isolamento_domiciliare": totDomiciliariRegione,
"totale_positivi": totPositiviRegione,
"dimessi_guariti": totGuaritiRegione,
"deceduti": totDecedutiRegione,
"tamponi": totTamponiRegione
};
Then sending that to db via ajax and Adding | in order to have something that I can use to separate the objects later. I am saving saveJsondata to a field called jsonBlock
Then in php I do:
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
$dataCustom = $dataSavedBlocks[0];
$dataCustom = str_replace('|', '', $dataCustom);
Finally in js:
var myJson = '<?php echo $dataCustom; ?>';
Output of that is:
var myJson = {"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477} ,{"totale_casi":47348,"terapia_intensiva":1362,"ricoverati_con_sintomi":11726,"totale_ospedalizzati":13088,"isolamento_domiciliare":12935,"totale_positivi":26023,"dimessi_guariti":13020,"deceduti":8305,"tamponi":133588} ;
Now I need to loop and get each individual value
You don't need to use the loop... just try console.log(customJsonData.totale_positivi). JSON properties become object attributes when parsed. Hence JavaScript Object Notation 8^D
Actually it is not an Array. If you want to iterate, use object keys.
var myJson = '{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477} ';
var customJsonData = JSON.parse(myJson);
Object.keys(customJsonData).forEach(key=>{
console.log(customJsonData[key]);
})
If you want a single value:
var myJson = '{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477} ';
var customJsonData = JSON.parse(myJson);
console.log(customJsonData.terapia_intensiva)
If you have an array of objects :
var myJson = '[{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477},{"totale_casi":826,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477},{"totale_casi":827,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477}]';
var customJsonData = JSON.parse(myJson);
customJsonData.forEach(data=>{
console.log(data.totale_casi);
})
This is how I resolved it:
var myJson = '<?php echo $dataCustom; ?>';
var customJsonData = JSON.parse("["+myJson+"]");
Now that we have a valid json, we can loop and iterate with each obj:
for(var d = 0; d < customJsonData.length; ++d) {
console.log(customJsonData[d].totale_casi);
}

make an array with the values of similar keys from JSON array

I have an array in JSON array format. I want to extract the values of common keys and make a new array with this.
I've tried this
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
where sale_date and total are the keys.
but this code returned an array of undefined objects.
my array named data looks like
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
I'm expecting two arrays date[2017-12-26 11:05:05, 2017-12-26 11:05:18 ] and amt[500, 500]
I'm getting data as a ajax response From the code below.
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data = $row;
print json_encode($db_data);
}
}
And this how my ajax request looks like
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});
var data = [
{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}
];
var date = [];
var amt = [];
for(var i in data){
console.log(i);
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
PHP Code :-
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$data = array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data[] = $row;
}
}
echo json_encode($db_data);
Ajax Request :-
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
data = JSON.parse(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});
You need to encapsulate your object between array
var data = [{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
var date = [];
var amt = [];
for(var i=0;i<data.length;i++){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
This is not a JavaScript but PHP issue.... you are sending invalid JSON. The following:
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
Should actually look like:
[{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
You need to change your PHP code to this:
// Add content type so that jQuery knows you're sending JSON
header("Content-Type: application/json");
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$db_data = array();
while ($row = $result->fetch_assoc()) {
$db_data[] = $row;
}
echo json_encode($db_data);
Sending Content-Type header should be enough but you should also change your jQuery code just to be sure:
$(document).ready(function() {
$.post("ajax-req-handler.php", {
key: "draw-line-chart"
}, function(data) {
console.log(data);
var date = [];
var amt = [];
for (var i in data) {
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
}, "json");
// the 4th parameter is dataType set to json
});
//Hope this will be of help.
var data = [ {"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"} ];
var date = amt = [];
X = 0;
while (x < data.length) {
date.push(data[x].sale_date);
amt.push(data[x].total);
x++;
};
console.log(date);
console.log(amt);
Explanation:
line 1 is the array of objects which represent the data u are pulling from ur json data.
Line 2 is the declaration of the two variable arrays which is assigned to and empty array. So, I used the short form of declaring multi-variable on the same line of statement.
Line 3 is the initialization of the counter "x" that will help break the While Loop once the it counts to the last Object in the array "data".
Line 4. Then the While Loop which keep iterating through the array " data". The conditional statement there always check if the counter "x" is < (less than) the length of the array In each iteration it.
Line 5. In the While Loop block code using the counter "x" as index of the array to access the property "sale_date" of the object in that array index and push it to the array "date" (I.e adding it at the end of the array "date").
Line 6. The same as line 5, accessing the property total in that index of the array " data" and push it to array "amt".
Line 7 increment the counter " x" by 1 and assign it to back to x which is used to reevaluate the While Loop.
Line 8 & 9 is just a console log that displays what's in date and amt respectively.
Thanks
Hope this makes sense to u... Please, Let me know your feedback.

Convert Json Object to Array in JS

I convert Array in php by json_encode and send to JS.
I want convert this json:
[{"category_id":4},{"category_id":2},{"category_id":3}]
to:
['3','2','4']
You should use map method.
let array=[{"category_id":4},{"category_id":2},{"category_id":3}]
array=array.map(function(item){
return item.category_id.toString();
});
console.log(array);
try this code :
var myObj = [{"category_id":4},{"category_id":2},{"category_id":3}]
var yourArray = myObj.map(function(value, index) {return value.category_id;})
I think this should resolve your issue.
var data = [{"category_id":4},{"category_id":2},{"category_id":3}];
var id = [];
for(var i in data)
{
id.push(data[i].category_id);
}
console.log(id);
try this
var a = [{"category_id":4},{"category_id":2},{"category_id":3}];
var b=[];
for(let i of a){
b.push(i.category_id);
}
console.log(b);
let array=[{"category_id":4},{"category_id":2},{"category_id":3}]
array=array.map(function(item){
return item.category_id.toString();
});
console.log(array);
I json Pass In php to JS with variable $category
bu in JS var array= <?php echo $category; ?>
error : Uncaught SyntaxError: Unexpected identifier

How to get multidimensional array data using java script and php

I have a multidimensional array in php, and i want to get its data from javascript but i didn't work
here my code in php
$managername = $_SESSION['managername'];
$sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";
$sql = mysql_query($sqls);
$newservices = array();
while($row = mysql_fetch_array($sql))
{
$nsrvid = $row['srvid'];
$nsrvname = $row['srvname'];
$nunitprice = $row['unitprice'];
$nunitpricetax = $row['unitpricetax'];
$ntotal = $nunitprice + $nunitpricetax;
$newservice = array($nsrvid, $nsrvname , $ntotal);
array_push ($newservices, $newservice);
}
and here my java script code
<script>
function changeserviceprice(id)
{
var newservice = $("#newservice").val();
var data = '<?= $newservices ?>';
var asd = data;
var asd2 = data[0][0];
$("#qq4").val(asd);
$("#qq5").val(asd2);
}
</script>
PHP code i think it is work fine, and i think the error is in javascript function.
when i try to print the data using javascript it print the "Array" word when i print the whole row "array", but
it print "a" character when i try to print the first element in the first array!!
try encoding the $newservices array:
var data = <?php echo json_encode($newservices); ?>;

Convert js Array() to JSon object for use with JQuery .ajax

in my app i need to send an javascript Array object to php script via ajax post. Something like this:
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
alert(saveData);
$.ajax({
type: "POST",
url: "salvaPreventivo.php",
data:saveData,
async:true
});
Array's indexes are strings and not int, so for this reason something like saveData.join('&') doesn't work.
Ideas?
Thanks in advance
Don't make it an Array if it is not an Array, make it an object:
var saveData = {};
saveData.a = 2;
saveData.c = 1;
// equivalent to...
var saveData = {a: 2, c: 1}
// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;
Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
//creating a json object
var jObject={};
for(i in saveData)
{
jObject[i] = saveData[i];
}
//Stringify this object and send it to the server
jObject= YAHOO.lang.JSON.stringify(jObject);
$.ajax({
type:'post',
cache:false,
url:"salvaPreventivo.php",
data:{jObject: jObject}
});
// reading the data at the server
<?php
$data = json_decode($_POST['jObject'], true);
print_r($data);
?>
//for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
//include the follwing files
//<!-- Dependencies -->
//<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
//<!-- Source file -->
//<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
Hope this helps
You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:
var a = [];
for (key in saveData) {
a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
There is no need of converting it into JSON because its already a json object.
To view the same use json.toSource();
When using the data on the server, your characters can reach with the addition of slashes eg
if string = {"hello"}
comes as string = {\ "hello \"}
to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>

Categories

Resources