Okay so I know this has been asked before and I've tried the solutions, but for some reason they don't work for me so I'm asking for some help. I haven't used JSON yet so maybe it's something silly but I have no clue...
Here's the code:
<?php
$array;
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<divShow>
</divShow>
<script>
function showArray(){
var array = <?php echo json_encode($array); ?>;
//Failed attempt to display array in the div field show
document.getElementById("divShow").appendChild(array);
//Failed attempt to display the array with an alert.
for(var i=0; i<2; i++){
alert(array[i]);
}
};
</script>
</html>
So what do you guys think? Am I missing something? Is it possible that the array was successfully passed to javascript but for some reason won't show?
Thanks,
-Alex
EDIT:
So I'm getting a series of arrays from a text file. I use these arrays as strings to display on the page and then convert them to float arrays. When I echo one of the float arrays such as $Z_Ausmass with:
echo json_encode($Z_Ausmass);
I get [25.39999961853,121.48651123047]. However, when I use the following to display the array through javascript:
function calc(){
var Z_Ausmass = <?php echo json_encode($Z_Ausmass); ?>;
for(var o=0; o<Z_Ausmass.length; o++){
var textnode = document.createTextNode(Z_Ausmass[o]);
document.getElementById("divCalc").appendChild(textnode);
}
};
it does not work. It's vital I get the float arrays in the script because the script needs to make calculations based on them and then display the calculations to the user.
When i execute the code it works ok.
The first attempt fails because you can't append the complete array. You need to append each element in the array seperately.
The second attempt works correctly. You only need to remove the first attempt to make it work because the first attempt stops the execution of the javascript.
edit
I tried to fix the code for you. I used a simple array with only text.
The element you wanted to show in did not have the id you where referencing to
<divShow></divShow>//wrong
<div id="divShow"></div>//right
to loop trough the complete array you do not want to hard code the max # of elements use arr.length as max for the 'for'-loop.
You can't directly append raw text to an html element. You need to make a TextNode of it and then append that node to the html element.
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
So The working code will be something like this:
<?php
$array = array("test","text","show");
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<div id="divShow">
</div>
<script>
function showArray(){
var arr = <?php echo json_encode($array); ?>;
//Put the text in a text node, append to the div
for(var i=0; i< arr.length; i++){
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
}
};
</script>
</html>
Related
I am developing a narrowcasting system for my school and I am currently using a JavaScript to rotate between URL's for the iFrame on the main display page.
I want to be able to change these values through a backend with PHP. However I can't figure out how to put 2 rows (module_url and module_time) into a array and echo it to JS.
Browsing through stackoverflow I tried a variety of code and this one kinda works, except it will throw out URL's like: "var arrayObjects = ["https:\/\/domain.eu\/dir\/page.php","https:\/\/domain.eu\/dir\/page.php"]".
(I want the array to display: "var arrayObjects = ["https:\/\/domain.eu\/dir\/page.php", 20]". Where the URL stands for the new iFrame source and the 20 for the time the page will be displayed.)
So my main question is, how do I make 2 rows fit into 1 array and how do I make sure the array will display correct links aswell as the module time.
<?php
$mysqli = new mysqli('localhost', 'user', 'pw', 'db');
if ($stmt = $mysqli->prepare("SELECT module_url FROM db")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
ALL OTHER JS CODE
</script>
Edit: module_time is not added to the MySQLi query at the moment.
First your PHP array should be multi-deminsional like:
$result_array[] = array($name, <time here>);
Then since you already use json_encode and assigned it to JS array, it is indeed already an array in Javascript, that is you can already access the elements like:
arrayObjects[0][0]; <---- first element URL
arrayObjects[0][1]; <---- first element time
Printing JavaScript array to HTML will show it as text like:
http://www.google.com,20,http://www.google.com,30
By the way you can use JSON.stringify() to print the actual Javascript array instead of the text, sample:
var array = JSON.stringify(<?php echo $json_array; ?>);
document.write(array);
Will output:
[["http://www.google.com",20],["http://www.google.com",30]]
I do have a problem with my split function, it's throwing a error see image:
error inside console
Hidden Input field inside php file:
<input class="file-id" name="_file-id" type="hidden" value="<?php echo esc_attr($file_ids); ?>" />
I saved already values inside it see image:
values inside hidden input field
Code:
jQuery(function($){
var savedIds = $('.file-id').val();
var savedIdsArr = savedIds.split(',');
for(i = 0; i < savedIdsArr.length; i++) {
savedIdsArr[i] = parseInt(savedIdsArr[i]);
}
console.log(savedIdsArr);
});
img(savedIdsArr)
if i do watch the console my code is working fine but it still's show me the error of the split function.
Hopefully someone can explain it to me and knows the solution.
you cann't use split() over javascript array . Split is a string function.
If you are directly getting ids in savedIds(here), iterate it you will get one by one values as required
I have build a dynamic list from an array and must print the onclick event inline, I don't know of anyway other way to do this.
<?php
$dataArray = $_POST['dataArray']; // This is a valid array
ECHO '<div id="colorSelectorBox">';
for ($btn = 0; $btn < sizeof($dataArray); $btn++){
ECHO '<div class="btn-group">
<button onclick="buildGroupList("'.$dataArray.'")">' .$dataArray[$btn].'</button>
<button><div ..Stuff..></div></button>
</div><br>';
}
ECHO '</div>';
?>
The problem is that the JavaScript function buildGroupList() does not receive an array from this instead the line looks like this in my developer tool:
onclick="buildGroupList(Array)"
How can I pass in an array of values through to JavaScript?
OR
How can I re-write this so that the call is not inline?
The shortest answer is: use json_encode() which will convert the array to a json string, but it's not good practice anyway.
Because you are trying to print the array as if automagically transforms itself into javascript array, that is, a string of its values separated by a comma (that is what it needs to output to the html, something the browser understands).
For that you need implode:
string implode ( string $glue , array $pieces )
Join array elements with a $glue string.
ECHO "<div class=\"btn-group\">
<button onclick=\"buildGroupList(['".implode("','",$dataArray)."'])\">" .$dataArray[$btn]."</button>
<button><div ..Stuff..></div></button>
</div><br>";
It takes every element in the array and puts $glue string between every one of them. The end result looks like this:
//let's assume this is your array in PHP
<?php
$dataArray = array('one','two','three');
?>
<!-- then your HTML looks like this -->
<button onclick="buildGroupList(['one','two','three'])">...</button>
Remember that PHP and Javascript don't know each other.
I'm trying to pass an array of data from php to java script for "onclick" event.
I do it by converting the array data into JSON string in order to parse it back in the js function and work on it.
The problem is that JSON string contains double quotes , so it arises an error as the double quotes break the html string (Uncaught SyntaxError: Unexpected token ILLEGAL ). I did see several questions similar to this, but didn't find a solution to what I need, or maybe I didn't understood the correct solution. So I bring it up here with my specific case.
<?php
..some php code here..
$aData = array("You","Me",76,array(3,6));
$sJSONstr = json_encode($aData);
?>
<input type="button" name="formSubmit" value="Delete" onclick="analyze('<?php echo $sJSONstr; ?>')">
<?php
..some php code here..
?>
and the js function is as follows:
function analyze(i_sInputDataJSONStr)
{
var aInputData = JSON.parse(i_sInputDataJSONStr);
.. So something with the input data array..
}
Use single quotes for the onclick attributes instead of double quotes. Single quotes is equally valid as double quotes.
One more thing, since you already have your data in JSON format, there is no need to put it as a string in the analyze function call, since your JSON data is a valid JavaScript array (that's what JSON stands for: JavaScript Object Notation).
Therefore, you don't have to parse the input string in your analyze function declaration.
Consider the following example, this is perfectly valid code.
<?php
$arr = ["Hello", "World"];
$json = json_encode($arr); // $json = '["Hello","World"]'
?>
<div id="myDiv" onclick='doSomething(<?php echo $json; ?>)'>Click me</div>
<script type="text/javascript">
function doSomething(data){
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
}
</script>
create a javascript string and pass it:
<script type="text/javascript">
var myjson = '<?php echo $sJSONstr; ?>';
</script>
and then:
onclick="analyze(myjson)"
<input type="button" name="formSubmit" value="Delete" onclick='analyze(<?php echo $sJSONstr?>)'>
Replace the double quotes with single quotes in onclick='';
Worked like a charm for me.
i want to acheive this :
for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid****')./* my actions goes here */
}
here i want to put the counter I of the javascript in the selector
how could i do that ???
Sorry i don't know PHP but i hope you wanted to do something like below
for (i = <?php echo $current_i ?> ;i<max;i++){
$('#div'+i)/*do the rest*/
}
the + is for concatenation, i hope it is same in PHP. Also you could cast i to string.
Just for OP's understanding
in line 2 $('#div'+i) i is a integer type and others $(#div) are of type string. For jquery needs a string selector to retrieve a matching dom node and for that i needs to also be casted/converted to a string variable so that it could concatenate/add/attach with the prefix string which is in this example #div. in c# you add 2 strings like this var result = "#div" + i.ToString(); and i did not know PHP equivalent for + in c#,hence a sorry at the start of post. Now do you understand?
for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid' + i)./* my actions goes here */
}
you can just concatenate it to the string of your selector.
That's not very "jQuery-ish". Assuming the elements have IDs with a continuing part and are in order, you can give every element a common class and use slice [docs] and each [docs]:
$('.commonClass').slice(<?php echo $current_i ?>, max + 1).each(...
You could provide better solutions if you explain more about your problem. E.g. giving each element an increasing ID does not seem to be a deliberate solution.
P.S.: I wouldn't put the PHP variable there either, maybe assign the value to a JavaScript variable first.
it would be a lot cleaner if you split up the php and javascript like this.
js_var.php
<?php
$phpvars = array(
'max' => 12,
'fop' => 22
);
function phpvar($key = NULL){
global $phpvars;
return ($key)
? json_encode($phpvars[$key])
: json_encode($phpvars);
}
?>
usage
<?php include('phpvars.php');?>
<script type="text/javascript">
window.phpvars = <?=phpvar()?>;
var max = phpvars.max;
for (var i=0;i<max;i++){
console.log(i);
}
console.log(php);
</script>