Pass variables and data from PHP to JavaScript? - javascript

This is not a duplicate of How to pass variables and data from PHP to JavaScript?
After consulting the previous question, I have another :
My problem is that when I get the php array in Js, and I print it, I have just [object][object]
<?php
$tl = array(
0=>array('a', 'b', 1),
1=>array('c', 'd', 2)
);
?>
and javascript :
<script type="text/javascript">
var arr= <?php echo json_encode($tl ); ?>;
for(var i=0;i<3;i++){
alert(arr[i]);
}
</script>

You should display it using console.log instead of alert :
console.log(arr[i]); //Check the result in you browser console
console.log : Formats your objects nicely and allows to traverse them.
Hope this helps.

Remember:
You don't have more than 2 object in your array so you should not run loop more than 2 times.
first loop give you permission to access the object of array then you can run a loop to show/get the property of object.
<?php
$tl = array(
0=>array('a', 'b', 1),
1=>array('c', 'd', 2)
);
?>
var arr = ;
for(var i=0;i<2;i++){
for(var j=0;j<3;j++){
alert(arr[i][j]);
console.log(arr[i][j]);// you can also show the value from the console of your browser
}
}
output of console

Try this ;)
alert() shows type if not basic data type. In your case it's Object that's why it's showing [object][object]
To debug JavaScript one should use console.log() and other console methods like:
console.log();
console.debug();
console.warn();
console.error();
etc.
One more thing here you are trying to access values of nested array so you can go with alert like this:
var arr= <?php echo json_encode($tl ); ?>;
for(var i=0;i<3;i++){
alert(arr[i][0] + " " + arr[i][1] + " " + arr[i][2]);
}
OR
Use nested loop to iterate inner array values;

try this:
<input type="hidden" id="array" value="<?php echo json_encode($tl); ?>" />
then use
<script type="text/javascript">
var arr = getElementById('array').value
for(var i=0;i<3;i++){
alert(arr[i]);
}
</script>

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.

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>

How do you convert a JS array into a PHP array? [duplicate]

Let's say I have a javascript array with a bunch of elements (anywhere from 50-200).
I want to send that to PHP (prepared statement) using ajax. Currently, I .load a php file many times inside of a loop, but I want to convert that into an array and send the array once, loading the PHP file once instead of 50-200 times.
array[i] = variable;
You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.
AJAX requests are no different from GET and POST requests initiated through a <form> element. Which means you can use $_GET and $_POST to retrieve the data.
When you're making an AJAX request (jQuery example):
// JavaScript file
elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})
It's (almost) equivalent to posting this form:
<form action="/test.php" method="post">
<input type="text" name="elements" value="1,2,9,15">
</form>
In both cases, on the server side you can read the data from the $_POST variable:
// test.php file
$elements = $_POST['elements'];
$elements = explode(',', $elements);
For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.
Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:
function obj2url(prefix, obj) {
var args=new Array();
if(typeof(obj) == 'object'){
for(var i in obj)
args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
}
else
args[args.length]=prefix+'='+encodeURIComponent(obj);
return args.join('&');
}
prefix is a parameter name.
EDIT:
var a = {
one: two,
three: four
};
alert('/script.php?'+obj2url('a', a));
Will produce
/script.php?a[one]=two&a[three]=four
which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.
So use the client-side loop to build a two-dimensional array of your arrays, and send the entire thing to PHP in one request.
Server-side, you'll need to have another loop which does its regular insert/update for each sub-array.
You can transfer array from javascript to PHP...
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>

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 integrate PHP with javascript variables?

I want to do something like this:
for (var i = 0; i < massages.length; i++)
{
commentBoxDiv.appendChild(createCommentBox("<?php echo $massages[i]['likes']; ?> people like this.", i));
}
but I don't know how to break the syntax in order to access the i variable.
With a little json_encode and some creativity, you can work out a solution like the following:
<script>
var messages = <?php echo json_encode($messages); ?>;
for(var i = 0; i < messages.length; i++) {
commentBoxDiv.appendChild(createCommentBox(messages[i].likes + " %d people like this.", i));
}
</script>
You can't use JS variables inside php code block. You must iterate $massages array and make from them JS objects.

Categories

Resources