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.
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 have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)
$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');
header('Content-type: application/json');
echo json_encode($array);
and it echos as:
[{"id":1,"price":"325"},{"id":2,"price":"486"}]
now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as
counterval1 = 325;
counterval2 = 486;
but I can't seem to get it to read that way. Here is the script at the current moment.
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval + data[i].id = data[i].price;
console.log (counterval2);
});
$('#results').html(counterval2);
});
var counterval1 = 0;
var counterval2 = 0;
any help on this would be greatly appreciated.
you can't do that... but you can do this...
var counterval = [];
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval[data[i].id] = data[i].price;
console.log (counterval[2]);
});
$('#results').html(counterval[2]);
});
counterval[1] = 0;
counterval[2] = 0;
See my comment on your post. If you really want the vars to look like you explained:
eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);
So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.
I have a foreach loop that creates a string in php , I'm unable to pass the string value to mootools in wordpress (I'm integrating a MooTool function ) :::
I need to substitute the "hard coded" image URL's in the new Array() (below) with a variable created from my php string eg. new Array( $myimageurl ) :::
I've created a var from the php string even tried json_encode , with no luck :::
window.addEvent("domready", function(){
var counter = 0;
var images = new Array('http://localhost/square/wp-content/uploads/2011/10/test-foo/foo.jpg','http://localhost/square/wp-content/uploads/2011/10/test-foo/foo1.jpg');
er, why not just:
var foo= <?=json_encode(Array("foo.jpg", "bar.jpg"))?>;
EDIT
Since you implied in a comment your files source is comma separated, then do this instead:
<? $files = "foo.jpg,bar.jpg"; ?>
var foo = <?=json_encode(explode(',', $files))?>;
where the array could be anything of any length, read from wherever. it will result in an array literal looking like so:
var foo = ["foo.jpg","bar.jpg"];
// eg use.
foo.each(function(img) {
new Element("img", {src: img}).inject(document.body);
));
nb: just noticed #Marc B has already mentioned json_encode. sorry, will delete
try:
var images = new Array('<?php echo $miImageUrl[0];?>', '<?php echo $miImageUrl[1];?>');
Other way:
<?php
//sample data
$descargables[0] = 'cero';
$descargables[1] = 'uno';
$descargables[2] = 'dos';
$descargables[3] = 'tres';
// end sample data
$arrayToJs="var descargables = new Array();";
for ($i=0; $i < count($descargables); $i++) {
$arrayToJs .= "descargables[" . $i . "]='" . $descargables[$i]. "';";
}
?>
<script>
<?php echo $arrayToJs;?>
idx = 3;
alert("descargable:" + descargables[idx]);
</script>
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