javascript object push how to set key value - javascript

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.

Related

Passing array data from php to javascript using a loop

Is there a similar way to implement this kind of "algorithm" in the right way?
for(i=0;i<howManyCourses;i++){
var stored = "<?php echo $buf[i] ?>";
var option = document.createElement("option");
option.text=stored;
e.add(option);
}
So I want to pass the data from the $buf array into a javascript variable. I've tried many ways but it seems like I cannot find the solution. I'm new into php and I apologise for any obvious mistake.
It should be in the same file or in another case AJAX will be the solution.
<script type="text/javascript">
const arr = <?php echo json_encode($buf); ?>;
for (var i = 0; i < arr.length ; i++) {
//do something
}
</script>
If you need that JS' variable buf contain the same elements as PHP's $buf, you can do the following:
var buf = <?php echo json_encode($buf); ?>;
Just keep in mind that if PHP's $buf is not an indexed array, JS' buf will be an object instead of an array.

How to pass an array parameter with javascript

I've to pass an ids array from a page to another page. I create $ids in PHP and I use use this with jQuery in this way:
var ids = <?php echo json_encode($ids); ?>;
jQuery(ids).each(function() {
filters.push('ids[]=' + jQuery(this));
});
The URL result is the following:
http://url.it/?sort=newest&ids[]=[object%20Object]&ids[]=[object%20Object]&ids[]=[object%20Object]&ids[]=[object%20Object]&ids[]=[object%20Object]
I would like to have in the URL an array with all elements but I obtain all arrays with one element.
Can you help me?
var params = ids.map(id => 'ids[]=' + encodeURIComponent(id))
filters.concat(params)
you do not need to do extra things. Just create your link like this:
var ids = <?= json_encode($ids); ?>;
var link = 'http://url.it/?sort=newest&ids=[' + ids.join(',') + ']';

Get Javascript variable as an index with PHP array in Javascript

Want javascript variable as index variable in php array in javascript.
Code is not working .....
<script>
var total = <?php echo count($resvalue); ?> ; //$resvalue is an array holding the values are 1,2,3,4. total will hold count of that array.
for(var j=0;j<total;j++)
{
<php echo $resvalue[j]; ?> // where j is javascript variable and $resvalue is PHP array
}
</script>
You cannot read values in a php array from javascript. Instead echo the array and turn it into a javascript array and let javascript do the count.
<script>
var resvalue = [<?php echo $resvalue; ?>]; // or something like this
for(var j=0; j < resvalue.length; j++)
{
// your value is available in the js-array
// resvalue[j]
}
</script>

Create an associative array in jquery using php array

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>

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.

Categories

Resources