How to get multidimensional array data using java script and php - javascript

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); ?>;

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);
}

Passing array to JS as values

I want to pass an array from PHP to Javascirpt so I just get a list of values - currently I get JSON format - which I know because I'm using JSON_ENCODE I'm just hoping/wondering is there a way to pass it as a simple set of values or to parse it afterwards?
Apologies I'm quite new to this :)
I've tried a few different things from previous answers to similar questions, but none seem to do the trick.
<?php
$user = 'xxx';
$pass = 'xxx';
$connection_string = 'connectionstringtomysqldatabase';
$connection = odbc_connect( $connection_string, $user, $pass );
$sqlstring = "SELECT FIELD1 FROM TABLE.ITEM where IASOHQ<>0 FETCH FIRST 10 ROWS ONLY";
$result = odbc_exec($connection, $sqlstring);
while ($info = odbc_fetch_array($result)) {
$content[] = $info;
}
?>
<script type="text/javascript">
var content = <?php echo json_encode($content); ?>;
</script>
I want...
var content = [68,116,49,57,13,11,46,47,14,79]
I get...
var content = [{"FIELD1":"68"},{"FIELD1":"116"},{"FIELD1":"49"},{"FIELD1":"57"},{"FIELD1":"13"},{"FIELD1":"11"},{"FIELD1":"46"},{"FIELD1":"47"},{"FIELD1":"14"},{"FIELD1":"79"}];
You are getting this result because your array is multi-dimensional with associative second level keys i.e. it looks like
$content = [['FIELD1' => 68], ['FIELD1' => 116], ..., ['FIELD1' => 79]];
This is because odbc_fetch_array returns an associative array for each row. To fix your data format, just change this line:
$content[] = $info;
to
$content[] = $info['FIELD1'];
That will give you an array that looks like your desired result of
[68,116,49,57,13,11,46,47,14,79]
Just add ' to make it a value. Change
var content = <?php echo json_encode($content); ?>;
to
var content = '<?php echo json_encode($content); ?>';
var myObject = JSON.parse(content);
Iterate over the array then.
Just change this peace of php code. I think that all of the index of array is FIELD1
...
while ($info = odbc_fetch_array($result)) {
$content[] = $info['FIELD1'];
}
...
Just
echo json_encode(array_values($content));
it will work;

How to set php array to html element data attribute as javascript array? [duplicate]

This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 3 years ago.
I'm trying to convert a PHP array to a javascript array for jQuery's datetimepicker to disable some dates. But I can't seem to find the right answer on the internet. I'm using Zend Framework for my project.
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
}
?>
<script>
var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
for(var i = 0; i < disabledDaysRange.length; i++) {
if($.isArray(disabledDaysRange[i])) {
for(var j = 0; j < disabledDaysRange[i].length; j++) {
var r = disabledDaysRange[i][j].split(" to ");
r[0] = r[0].split("-");
r[1] = r[1].split("-");
if(new Date(r[0][2], (r[0][0]-1), r[0][1]) <= d && d <= new Date(r[1][2], (r[1][0]-1), r[1][1])) {
return [false];
}
}
}else{
if(((d.getMonth()+1) + '-' + d.getDate() + '-' + d.getFullYear()) == disabledDaysRange[i]) {
return [false];
}
}
}
return [true];
}
$('#date').datepicker({
dateFormat: 'dd/mm/yy',
beforeShowDay: disableRangeOfDays
});
});
</script>
To convert you PHP array to JS , you can do it like this :
var js_array = [<?php echo '"'.implode('","', $disabledDaysRange ).'"' ?>];
or using JSON_ENCODE :
var js_array =<?php echo json_encode($disabledDaysRange );?>;
Example without JSON_ENCODE:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
alert(js_array[0]);
</script>
Example with JSON_ENCODE :
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array =<?php echo json_encode($disabledDaysRange );?>;
alert(js_array[0]);
</script>
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it.
<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>
You can pass the JSON string output by json_encode to a JavaScript variable as follows:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:
<?php
echo json_encode($ar, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
Associative Array Example:
<?php
$book = array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan",
"edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan",
"edition": 6
}; */
alert(book.title);
</script>
Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format.
You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title'].
here you can find more information and details.
When we convert PHP array into JS array then we get all values in string.
For example:
var ars= '<?php echo json_encode($abc); ?>';
The issue in above method is when we try to get the first element of ars[0] then it gives us bracket where as in we need first element as compare to bracket so the better way to this is
var packing_slip_orders = JSON.parse('<?php echo json_encode($packing_slip_orders); ?>');
You should use json_parse after json_encode to get the accurate array result.
Have you tried using json_encode http://php.net/manual/en/function.json-encode.php
It converts an array to a json string
This may be a easy solution.
var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
}
$disDays = size($disabledDaysRange);
?>
<script>
var disabledDaysRange = {};
var disDays = '<?=$disDays;?>';
for(i=0;i<disDays;i++) {
array.push(disabledDaysRange,'<?=$disabledDaysRange[' + i + '];?>');
}
............................
<script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
in the above assign array to javascript variable "disableDaysRange"
$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
$disallowDates .= "'".$disableDates."',";
}
echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";
so your javascript var diableDateRange shoudl be
var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
array_push($disabledDaysRange, $date);
}
$finalArr = json_encode($disabledDaysRange);
?>
<script>
var disabledDaysRange = <?=$finalArr?>;
</script>
You should need to convert your PHP array to javascript array using PHP syntax json_encode.
json_encode convert PHP array to JSON string
Single Dimension PHP array to javascript array
<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>
Multi Dimension PHP array to javascript array
<?php
var $itemsarray= array(
array('name'='Apple', 'price'=>'12345'),
array('name'='Bear', 'price'=>'13344'),
array('name'='Potato', 'price'=>'00440')
);
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>
For more detail, you can also check php array to javascript array

How to fill javascript array from ajax data result

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.

PHP variable as Javascript variable name

I know this kind of post is frequently found on internet. But my problem is a little bit more dificult and I did not find an answer.
I want to make an associative array in Javascript in a loop with a variable name.
($JJ = table of object)
($JJ->getResto($DB,$acad) allows me to recover my database datas)
$JJ = new RestaU();
$JJ = $JJ->getResto($DB,$acad);
for ($i = 0; $i <= sizeof($JJ)-1; $i++) {
//Datas recovering
$lat = $JJ[$i]->loc_lat;
$long = $JJ[$i]->loc_long;
$name = $JJ[$i]->nom;
$ville = $JJ[$i]->ville;
//String treatment to avoid spaces
$ville = str_replace(" ","",$ville);
$name = str_replace(" ","",$name);
echo <<< SC
<script>
//here $ville will contain an google map object associated to the ville name.
//It means that I need to change it for each "for" loop.
var $ville = new Object();
//that is why here I need to have $ville["name"] to generate a table for each city
//and have an access to it later.
$ville+["name"] = new google.maps.LatLng($lat,$long);
console.log(string2);
</script>
SC;
My problem is, I can not find the solution to right for example ville1["name"]. Each time the code is not "interpreted" it means I can have the string but it does not create my array.
Thank you a lot for all your ideas!
SOLUTION IN COMMENT.
I used that :
var string = "$ville";
window[string]["name"] = "blabla";
It works really well.
php is server language and javascript is clint browser language!
in fact you can't share variables!
But you can print variables to javascript code like:
<script>
var myvar = '<?php echo $myvar; ?>';
</script>
if you want to send variables from javascript to php you must use Ajax
for array
<script>
<?php
$array = array('index1'=>'hellow World!','index2'=>'Iran haven`t nuclear bomb');
echo 'var arryname = new Array();';
foreach($array as $key=>$val){
echo "\n arryname['{$key}'] = '{$val}';";
}
?>
</script>

Categories

Resources