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;
?>
Related
My Questions is Find a 7 letter string of characters that contains only letters from
acegikoprs
such that the gen_hash(the_string) is
675217408078
if hash is defined by the following pseudo-code:
Int64 gen_hash (String s) {
Int64 h = 7
String letters = "acegikoprs"
for(Int32 i = 0; i < s.length; i++) {
h = (h * 37 + letters.indexOf(s[i]))
}
return h
}
For example, if we were trying to find the 7 letter string where gen_hash(the_string) was 677850704066, the answer would be "kppracg".
Solution
test1.php
I did that question solve in php, I am unable to run this code I am in php i don't have that much knowledge regarding php class and their function, Can any one solve this code and describe me. thanks in advance i will be very great full if anyone help me.
<?php
$set = "acdegilmnoprstuw";
$CONST_HASH = 7.0;
$CONST_MULT = 37.0;
$hash = new Func(function($string = null) use (&$CONST_HASH, &$CONST_MULT, &$set) {
$_hash = $CONST_HASH;
for ($i = 0.0; $i < get($string, "length"); $i++) {
$_hash = _plus(to_number($_hash) * to_number($CONST_MULT), call_method($set, "indexOf", get($string, $i)));
}
return $_hash;
});
$decode = new Func(function($_hash = null) use (&$CONST_MULT, &$Math, &$set) {
$decoded = ""; $positionsInSet = new Arr();
for ($i = 0.0; $_hash > $CONST_MULT; $i++) {
set($positionsInSet, $i, call_method($Math, "floor", (float)(to_number($_hash) % to_number($CONST_MULT))));
$_hash /= 37.0;
}
for ($i = to_number(get($positionsInSet, "length")) - 1.0; $i >= 0.0; $i--) {
$decoded = _plus($decoded, get($set, get($positionsInSet, $i)));
}
return $decoded;
});
I realize that this question was asked well over a year ago and I'm only just stumbling on it right now but seeing as there hasn't been an answer I figured I'd answer it.
You used a third party JavaScript to PHP converter utility and expected the demo to work out of the box. You should have read up on it's usage as it clearly states in the ReadMe.md that, ...this tool is using esprima JavaScript parser with rocambole to walk the AST and escope to figure out the variable scope, hoist function declarations and so on...
The developer goes on to say, After AST manipulation tools/codegen.js generates the PHP code by walking the tree. Now here's where it gets good. Pay attention now..
Various constructs get wrapped in helper functions, for instance,
property access, method calls and + operator. The runtime helpers
can be found in php/helper and there are a bunch of classes in
php/classes for Array, RegExp and such. All this PHP gets packaged
into your output file, or you can save it to a standalone runtime and
reference that from your output file like so:
js2php --runtime-only > runtime.php
js2php --runtime runtime.php example.js > example.php
You can also specify the output file using -o or --out and you can
compile multiple input files into one output file like so:
js2php -o example.php file1.js file2.js
So as you can see my friend, to get your code to work you merely need to include the runtime helpers functions so your converted script can be interpreted. I'm not sure as to which files it'll take to get your script to parse correctly, however now that I've pointed you in the right direction I'm confident you'll be able work it out yourself.
Happy coding..
=)
Instead of assigning the inline function with new operator to variable, create a separate functions encode and decode where you can do the hashing and matching the hash code.
Let me give you the snippet of how to do it. I am assuming that your using plain PHP.
/* Call to function encode which returns you the encoded value and store in $encode variable */
$encode = encode($par1, $par2);
/* Call to function decode which returns you the decoded value and store in $decode variable */
$decode = decode($par1, $par2);
/* Function to encode your code */
function encode($par1, $par2){
return $encode_value
}
/* Function to decode your code */
function decode($par1, $par2){
return $decode_value
}
I have written this in Javascript to generate both Hash String and Number
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var gen = gen_hash('kppracg');
document.write("kppracg hash value is ", gen);
document.write('<br><br>');
var gen = gen_hash('iorocks');
document.write("iorocks hash value is ", gen);
var hash = 675217408078;
var gen_rev = gen_hash_rev(hash);
document.write('<br><br>');
document.write("675217408078 hash value is ", gen_rev);
function gen_hash(s) {
var h = 7;
var acegikoprs = "acegikoprs";
for(var i = 0; i < s.length; i++) {
h = (h * 37 + acegikoprs.indexOf(s[i]));
}
return h;
}
function gen_hash_rev(hash) {
var arr_values = ['a','c','e','g','i','k','o','p','r','s'];
var min = 0;
var max = 99999999;
while (min <= max) {
var final_result = "";
var tempInt = parseInt(((max - min) / 2) + min);
var arr_tempInt = num_array(tempInt);
for(var i = 0; i < arr_tempInt.length; i++) {
final_result = final_result + arr_values[arr_tempInt[i]];
}
var result = gen_hash(final_result);
if(result < hash) {
min = tempInt + 1;
}
else if( result > hash) {
max = tempInt - 1;
}
else {
return final_result;
}
}
}
function num_array(num){
var output = [],
sNumber = num.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
return output;
}
</script>
</body>
</html>
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.
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.
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
Ok, I've been banging my head up against the wall on this and I have no clue why it isn't creating the element. Maybe something very small that I overlooked here. Basically, there is this Javascript code that is in a PHP document being outputted, like somewhere in the middle of when the page gets loaded, NOW, unfortunately it can't go into the header. Though I'm not sure that that is the problem anyways, but perhaps it is... hmmmmm.
// Setting the variables needed to be set.
echo '
<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/shoutbox.js"></script>';
echo '
<script type="text/javascript">
var refreshRate = ', $params['refresh_rate'], ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName(\'div\');
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
var is_counted = 0;
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
else
{
if (divName.indexOf(\'dp_Reserved_Counted\') == 0)
{
is_counted = 0;
shoutCount++;
continue;
}
else
{
shoutCount++;
is_counted = 1;
}
}
// Empty out the name attr.
alldivs[i].name = \'dp_Reserved_Counted\';
var shoutId = \'shoutbox_area\' + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement(\'div\');
shoutHolder.setAttribute(\'id\', [shoutId]);
shoutHolder.setAttribute(\'class\', \'dp_control_flow\');
shoutHolder.style.cssText = \'padding-right: 6px;\';
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
if (is_counted == 1)
{
startShouts(refreshRate, shoutId);
break;
}
}
}
</script>';
Also, I'm sure the other functions that I'm linking to within these functions work just fine. The problem here is that within this function, the div never gets created at all and I can't understand why? Furthermore Firefox, FireBug is telling me that the variable divName is undefined, even though I have attempted to take care of this within the function, though not sure why.
Anyways, I need the created div element to be inserted just before the following HTML:
echo '
<div name="dp_Reserved_Shoutbox" style="padding-bottom: 9px;"></div>';
I'm using name here instead of id because I don't want duplicate id values which is why I'm changing the name value and incrementing, since this function may be called more than 1 time. For example if there are 3 shoutboxes on the same page (Don't ask why...lol), I need to skip the other names that I already changed to "dp_Reserved_Counted", which I believe I am doing correctly. In any case, if I could I would place this into the header and have it called just once, but this isn't possible as these are loaded and no way of telling which one's they are, so it's directly hard-coded into the actual output on the page of where the shoutbox is within the HTML. Basically, not sure if that is the problem or not, but there must be some sort of work-around, unless the problem is within my code above... arrg
Please help me. Really what I need is a second set of eyes on this.
Thanks :)
When you're testing divName, switch the order of your conditions from this
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
to this:
var divName = alldivs[i].getAttribute(\'name\');
if (!divName) // this is sufficient, by the way
continue;
else if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
The problem is that when the script finds a div without a name, it tries to call the indexOf property of a non-existent value and therefore throws an error.
There were a number of issues in the loadShouts method. First being the comparison of a string "undefined" instead of a straight boolean check, which will match. I also removed a bunch of un-needed logic. Beyond this, the id attribute being assigned to the new shoutHolder was being passed in as an array, instead of a direct property assignment.. See if the following works better.
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
Ok, just wanted to let you know how it went. And I thank both you greatly Tracker1 and Casey Hope. Especially Tracker for the excellent rewrite of the function. You all ROCK. Here's the final function that I'm using bytheway, just a tiny bit of editing to Tracker1's Answer, which is why you got my vote hands down!
echo '
<script type="text/javascript">
var refreshRate = ' . $params['refresh_rate'] . ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
</script>';
Thanks Again, you are the BEST!