Hi Im trying to send an array from php to my javascript. Is this possible? Ive tryied a few examples that Ive found but non of them have worked.
Here is what Im trying to do:
php file:
<?php
$n = array('test','test2', 'test3');
<script type='text/javascript'>
initArray($n);
</script>
?>
javascipt:
function initArray(array){
for(var i = 0; i < array.length; i++){
alert(array[i]);
}
}
Thx for all your answers
<?php
$n = array('test','test2', 'test3');
?>
<script type="text/javascript">
var arr = <?php echo json_encode($n); ?>; // create the JavaScript array
initArray(arr); // use it
function initArray(array){
for(var i = 0; i < array.length; i++){
alert(array[i]);
}
}
</script>
You need to use json_encode to convert a PHP array to a JavaScript one, and output its result while assigning it to a JavaScript variable.
You have to serialize it. Try it with JSON. http://php.net/manual/en/book.json.php
Related
i have an xml file in my server that i want to extract a list of IDs with php then convert the array to a JSON using json_encode() and put it in a $_SESSION variable, to make this clear my ideal JS function is:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = responseText;
});
}
//some other code
//return array; // this is an array i use later in js
}
in my getPL.php i have:
$videos_list = $theOne->parentNode->parentNode->getElementsByTagName('video');
for ($i = 0; $i < $videos_list->length; $i++) {
$a = $videos_list->item($i);
$id_out = $a->getElementsByTagName('id')->item(0)->nodeValue;
$array[$i] = $id_out;
}
$IDs = json_encode($array);
$_SESSION['IDs'] = $IDs;
echo $IDs;
break;
if i alert var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>; i get g8M8kxuaCWk,VWrBFt46J18
but when i alert the responseText i get ["g8M8kxuaCWk","VWrBFt46J18"]
all i want is to extract the IDs from the xml file and put them in a js array object
if there is anything need more tell me
i think you need the put quotes arround the php code in your JS like:
var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>';
ok i fixed it
so var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>'; would give me an array, which is what i actually want
but the alert(resposeText); was actually giving me a string so i did this JSON.parse(responseText);
thanks to who helped me get to this answer
after this in both cases if i alert(obj[0]); i get the first element so it is working
my ideal JS function becomes:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = JSON.parse(responseText); // this is the difference
});
}
return x;
}
I created a form with a text field that has Spry Validation (ie javascript). The user can select the number of rows in the form from 1 to 10. I need the code below to also expand but I'm not familiar enough with javascript to make it work.
$divkey is the variable that controls how many rows are in the form.
Original
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["change"], maxChars:20});
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
so I need the line 'var sprytextfield1...' to repeat based on $divkey with the next line being 'var sprytextfield2...' and so on. Can someone please rewrite this so it will work?
Trying to use php
<script type="text/javascript">
<?php for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Trying to use javascript
<script type="text/javascript">
var numwrestler = <?php echo $wrestlerkey; ?>;
var sprytextfield = [];
for (var i = 0; i < numwrestler; i++) {
var num = i+1;
var sprytextfield[num] = new Spry.Widget.ValidationTextField("sprytextfield"+num, "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
I'd recommend that you use a Javascript array for this type of task.
Your code is mostly correct, but the var in your for loop is incorrect, and the creation of the num variable instead of just using i is redundant.
<script type="text/javascript">
var sprytextfield = new Array();
var numwrestler = <?php echo $wrestlerkey; ?>;
for(var i = 0; i < numwrestler; i++){
sprytextfield[i] = new Spry.Widget.ValidationTextField("sprytextfield"+(i+1), "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Be sure that your PHP variable(s) are defined in the file before you include them in your script.
In your PHP code, you never define the variable divkey, by deafault the value will be 0.
Try:
<script type="text/javascript">
<?php $divkey = 10; for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Please, note that the variable that you are using as index $num in every iteration of the loop will be increasing 2, because of the i++ and the $num=$i+1
I have a array stored in a PHP file in which I am storing all the values.
I am trying to loop through the entire array in JavaScript. How should I do that?
The following does not work:
var index = 0;
var info = 1;
while(index<4) {
info = <?php echo $a[?>index<?php];?>
index++;
}
You can copy array from php to JavaScript and then process it.
var array = <?php echo json_encode($a); ?>
var index = 0;
var info = 1;
while(index<4) {
info = array[index];
index++;
}
I don't know what version of php you're using, but try something like this:
var info = null;
var a = <?php echo json_encode($a); ?>;
for(var index=0;index<a.length;index++) {
info = a[index];
}
You need to process the PHP into Javascript first. You can use json_encode to do this.
var index = 0;
var info = 1;
var a = <?php echo json_encode($a); ?>;
while(index < 4) {
info = a[index];
index++;
}
PHP runs on the server side, before the final page is served to the client.
Javascript runs on the client side (on the browser).
Therefore, what you are trying to achieve won't work. What you can do is use PHP to print the javascript code dynamically.
I am trying this code:
<script type="text/javascript">
for (i = 0; i < 5; i++) {
for (x = 0; x < 1; x++) {
$("#one" + i).html("<?php echo $arr["+i+"]["+x+"] ?>");
$("#two" + i).html("<?php echo $arr["+i+"]["+x+1+"] ?>");
};
};
</script>
No error is showed, but content also not.
How can I use the increment variable of JavaScript in PHP code?
Thanks
You may make your PHP-array accessible to JS(store it as a js-variable) :
<script type="text/javascript">
var arr=<?php echo json_encode($arr); ?>;
for (i = 0; i < arr.length; i++) {
for (x = 0; x < 1; x++) {
$("#one" + i).html(arr[i][x]);
$("#two" + i).html(arr[i][x+1]);
};
};
</script>
You cannot do this.
Javascript runs on the client, which is after all PHP code has executed.
Why don't you write the loop in PHP instead? For example,
<script type="text/javascript">
<?php
for ($i = 0; $i < 5; $i++) {
for ($x = 0; $x < 1; $x++) {
printf('$("#one%s").html("%s");', $i, $arr[$i][$x]);
printf('$("#two%s").html("%s");', $i, $arr[$i][$x + 1]);
};
};
?>
</script>
Ok, I try to give you a short question..althought it may be very long.
PHP it's a Server-side scripting language, while javascript it's a Client-side one.
That's mean that the php code is interpreted and executeted in the server (e.g. Apache), and the javascript code is executed inside the browser itself.
So, there is no way you can execute php code inside of your brower.
for the code you have written you can simpli transform the two for javascript iteration in php. If you actually need to print something in php given a javascript variable you should do an AJAX request to a php page that recive your javascript value and returns back the php-calculated values you need.
Please have a look at those references as a start:
http://en.wikipedia.org/wiki/Server-side_scripting
http://en.wikipedia.org/wiki/Client-side_scripting
http://en.wikipedia.org/wiki/Ajax_(programming)
<?php is interpreted by the php interpreter. If you don't have this block in an actual php file, then that means you are executing in the context of the browser. The browser doesn't know about php, only your web server. Thus, the browser will interpret <?php as an HTML element, which doesn't exist.
You need to move your entire block into a php file, like so:
myFile.php
==========
<?php
$arr = array(...);
$arrLen = count($arr);
$output = '<script type="text/javascript">';
for ($i=0; $i<$arrLen; $i++) { // notice this is in php, not js
$output .= '$("#one"'.$i.').html("'.$arr[$i][0].'");';
$output .= '$("#two"'.$i.').html("'.$arr[$i][1].'");';
}
$output .= '</script>';
echo $output;
?>
<?php
$abc=array();
$abc = (abc, cde,fre);
?>
<script language="javascript" type="text/javascript">
for (var i = 0; i < 3; i++) {
var gdf = "<?php echo $lat['i'];?>";
alert("value ="+gdf);
}
</script>
Following your comment, I think this is what you are trying to do:
<?php
$abc = array('abc', 'cde', 'fre');
?>
<script type="text/javascript">
var gdf = '<?php
for ($i = 0; $i < count($abc); $i++) {
echo "{$abc[$i]}";
if ($i != (count($abc)-1)) echo ", ";
}
?>';
</script>
Will output:
http://codepad.org/KjEH5CmN
<script type="text/javascript">
var gdf = 'abc, cde, fre';
</script>
NOTE
Using implode if you want a single variable would also work well:
http://codepad.org/UwukCY4m
<?php
$abc = array('abc', 'cde', 'fre');
?>
<script type="text/javascript">
var gdf = '<?php echo implode(', ',$abc); ?>';
</script>
You're not looking to assign a single value of the array; you're looking for the whole array. Your JavaScript loop is trying to iterate over the entire $abc array from PHP.
Something like this would work:
var abc = <?php echo json_encode($abc); ?>;
for(var i = 0; i < 3; i++)
var gdf = abc[i];
alert("value = " + gdf);
}
Firstly, to build a PHP array you should be using this notation:
<?php
$abc = array('abc', 'cde', 'fre');
?>
Next, it's not possible use JavaScript to directly loop through your variable that is stored in PHP. You can do something like this instead, performing the loop in PHP:
<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
<?php foreach ( $abc as $el ): ?>
alert('value=<?php echo $el ?>');
<?php endforeach ?>
</script>
Or, if you'd really like the loop to happen in JavaScript and not PHP, you can "export" the PHP array to JavaScript by converting the array to a JSON string and outputting it.
<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
var abc = <?php echo json_encode($abc) ?>;
for ( var i = 0; i < abc.length; i++ ) {
alert('value=' + abc[i]);
}
</script>