Create an associative array in jquery using php array - javascript

I need to create an assosiative array in jQuery from PHP.
Here is my script so far. selectedStoresDict is json encoded array with values ["Lahore", "Islamabad"]
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = {};
for( i = 0 ; i <= selectedStores.length; i++) {
data['id'] = i;
data['text'] = selectedStores[i];
}
console.log(data, "Hello, world!");
However my console is showing that its not an array. I want something like this:
[{ id: 1, text: 'Lahore' }, { id: 2, text: 'Islamabad' }]

I think this should be a JS question instead of a PHP one, but here you have. You were almost there:
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = [];
for( i = 1 ; i <= selectedStores.length; i++) {
data.push({
id: i,
text: selectedStores[i]
});
}
console.log(data, "Hello, world!");
An array in JS is represented with [], so you need to initialize it like that, then just push the info (in this case, and object with keys and values). Also for ids starting with 1, you must initialize i = 1.

No need to loop thru.
Just json_encode the array
<?php
$selectedStoresDict[] = array("id"=>1,"text"=>"Lahore");
$selectedStoresDict[] = array("id"=>2,"text"=>"Islamabad");
?>
<script>
console.log('<?php echo json_encode($selectedStoresDict); ?>');
</script>

Related

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.

Loop through an array with objects

I get the following array from my back end:
[Object { 7="77.105.239.8", 10="77.105.239.11", 18="77.105.239.19", more...}]
How can I use ng-options to fill my select dropdown with the Ips from the array?
The array above Is the result of an array_diff from my back end In PHP:
foreach($ips as $ip)
{
$taken[] = $ip['ip'];
}
$start = (ip2long($serie->net) + 1);
$antal = pow(2,(32-$serie->mask));
for($i = $start; $i < ($start+$antal-3); $i++)
{
if(end(explode(".", long2ip($i))) != "0")
{
$possible_ips[] = long2ip($i);
}
}
$poss = array_diff($possible_ips, $taken);
return $poss;
If you don't want to or cannot fix the data to be formatted like m4lt3 answer, then you need to do some preprocessing of the data before trying to bind it.
var originalData = [{ 7: "77.105.239.8", 10: "77.105.239.11", 18: "77.105.239.19"}];
var originalObject = originalData[0];
var newData = [];
for (var i in originalObject) {
newData.push({'id': i, 'ip': originalObject[i]});
}
$scope.ipList = newData;
...then you could bind ipList using ngOptions.
I think you can leave your function as is, except change the return statement to: return json_encode($poss);
Actually you are getting an array with only one field which contains an object with the data you need.
My suggestion is, to fix that in the backend. So that you get what you need -> a real array. Like this:
[
{ "id":7, "ip":"77.105.239.8"},
{ "id":10, "ip":"77.105.239.150"},
{ "id":12, "ip":"77.105.239.12"}
]
Since array_diff returns an assoziative array, we need to transform it to a non-assoziative array and return it (either with json_encode or not, depending on you set up):
...
$poss = array_diff($possible_ips, $taken);
$res = [];
foreach ($poss as $key => $value) {
$res[] = $value;
}
return json_encode($res);

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.

javascript object push how to set key value

Is there any way to set own key value when using javascript push method? Here is my example:
<script>
var examples = [];
</script>
<?php foreach($examples as $example):?>
<script type="text/javascript">
var example<?php echo $example['id']?> = {
id : '<?php echo $example['id']?>',
another : '<?php echo $example['another']?>',
};
//here I would like to give key $example[id]
examples.push(example<?php echo $example['id']?>);
</script>
<?php endforeach;?>
<script>
for (index = 0; index < examples.length; ++index) {
somefunction(examples[index]);
}
</script>
For some reasons I need $example['id'] to have the same value as pushed key.
Making an array is making this a bit harder than you need it to be if you need the IDs to match.
If you want to reference it by the ID, you can simply use a vanilla JS object
<script>
var examples = {};
</script>
<?php foreach($examples as $example):?>
<script type="text/javascript">
var example<?php echo $example['id']?> = {
id : '<?php echo $example['id']?>',
another : '<?php echo $example['another']?>',
};
//here I would like to give key $example[id]
examples['' + <?php echo $example['id']?>] = example;
</script>
<?php endforeach;?>
<script>
for (var k in examples) {
somefunction(examples[k]);
}
</script>
This will let you set arbitrary string keys and loop through just like an array.
Use an object instead:
var examples = {};
...
examples[key] = value;
If your id is a string value, then you need a mapping object (var obj = {}; obj[key] = value), but you wan't be able to use it as an array since it's not an array, though, you still can do something like this: for (var k in elements) { if (elements.hasOwnProperty(k)) {do something} }
If you really want to use an Array than you can try using splice ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice ) method to insert your elements at certain index (just make sure that array length is always greater than index value you are trying to insert at), but for that your id has to be numeric, not a stirng.

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

Categories

Resources