How to pass an array parameter with javascript - 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(',') + ']';

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.

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;

Replace different Values in String?

I have a string which looks like this: (id:561644cdb40fbe0100247dd7:q) (id:56165d8a79c8c40100adbdb6:q) and I need to replace the different id's with different values. I already have the id's in a variable and trying to loop through with something like this var mailId = "(id:" + rplcId + ":q)"; But If I use the replace() function it doesnt work...Any other suggestions?
You can select the id with:
"(id:56165d8a79c8c40100adbdb6:q)".split(":")[1]
var id = "(id:561644cdb40fbe0100247dd7:q)";
var idArr = id.split(":");
idArr[1] = newId; //56165d8a79c8c40100adbdb6
var mailId = idArr[0]+idArr[1]+idArr[2];
and please provide your full code

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.

Categories

Resources