I declare php arrays, i fill them with strings taken from query.
I have to pass this arrays to a handler of a element in the page.
Handler can't read this arrays.
PHP:
$names = $paths = $infos= [];
$i = 0;
while($row = $result->fetch_row())
{
$names[$i]= $row[0];
$paths[$i]= $row[1];
$infos[$i]= $row[2];
$i++;
}
...
for($i = 1; $i < ($length/8)+1 ; $i++)//arrotonda per eccesso
{
$jsNames = json_encode($names);
$jsInfo = json_encode($infos);
$jsPaths = json_encode($paths);
//echo $jsNames."<br>";
//echo $jsInfo."<br>";
//echo $jsPaths."<br>";
?>
<?php echo $i ?>
JS:
function changePhoto(num,names,paths,infos){
//nothing
}
Browser error: Uncaught SyntaxError: Unexpected token }
Opening browser debugger:
(function(event){changePhoto(2,[ })
You will have a problem with quotes here. Your jsons will have some " in it, and your html-attribute is enclosed in ", too.
So change
onClick="changePhoto(<?php echo $i.','.$jsNames.','.$jsInfo.','.$jsPaths ?>)"
to
onClick='changePhoto(<?php echo $i.','.$jsNames.','.$jsInfo.','.$jsPaths ?>)'
// note the single-quotes here!
Sidenote:
You should put these lines $jsNames = json_encode($names); outside the loop, as they won't change anymore. But now you're doing the same work several times.
Related
I am fetching an array from a MySQL result into a array variable. I can successfully use a simple php echo line in the javascript beneath to grab the first $row element, but I want to use json_encode to get the whole array at once.
When I do this and try to set a javascript var to the first array element something goes wrong and even the single var method stops working.
<?php
.
.
.
while($row = $result->fetch_array(MYSQLI_NUM)) {
$row1 = $row[0];
}
?>
<script type="text/javascript">
var RowArray = <?php echo json_encode($row); ?>;
var RA1 = RowArray[0];
window.alert(RA1);
var Row1 = '<?php echo $row1; ?>';
window.alert(Row1);
</script>
Make an array containing all the records:
$rows = [];
while ($row = $result->fetch_array(MYSQLI_NUM))
{
// do custom modifications to $row if neededed
$rows[] = $row; // push to array
}
Or just:
$rows = $result->fetch_all(MYSQLI_NUM);
And then use json_encode() with $rows.
My index.php page includes a config.php file, which returns an array that I have defined some variables in by using "define('var1' , 10)".
I am trying to validate my forms input, but I can't figure out how I can reference var1 from within the JS function. What is the easiest way to do this?
Just echo it to a javascript variable:
<script type="text/javascript">
var var1JS = "<?php echo $var1; ?>";
</script>
Not quite sure I am full understanding without seeing the code but, you could echo the variable from the PHP array in the JS function (as above answer).
Or Echo the entire JS query:
$y = count($PHPdata_array);
echo "function exampleFunction() {";
echo "var ArrayName = [";
for ($i = 1; $i <= $y; $i+=2) {
echo "{" . $PHPdata_array[$i] . "," . $PHPdata_array[$i-1] . "},";
}
echo "];";
I fetch some information from DB - shown here:
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle = $link->prepare("SELECT dropAddress FROM mv_bookingEst WHERE userID='$userID'");
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
//print_r($result);
$x = 0;
foreach($result as $obj){
$resultArray[$x] = $obj->dropAddress;
$x++;
}
and then in my javscript:
var count = "<?php echo json_encode($resultArray); ?>";
However I get the following error:
Syntax error: unexpected number -->
var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
If I replace json_encode($resultArray) with echo ($resultArray[0]) the values pass fine. Not sure how to fix it because everything I've read uses this method. TIA
var count = "<?php echo json_encode($resultArray); ?>";
You are returning the result of the json_encode inside of a JavaScript string. Your syntax error shows this:
Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
Unless there's a failure in coversion, json_encode returns valid JavaScript syntax, so you should just use it as-is without any adornments in your javascript:
var count = <?php echo json_encode($resultArray); ?>;
If you want to take into consideration the possibility of failure, then you can use this instead:
var count = <?php
$tmp = json_encode($resultArray);
echo ($tmp === false ? 'null' : $tmp);
?>;
I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.
I am getting error in Firefox SyntaxError: unterminated string literal when i try to include following code:
<script>
function makeProdiv(data){
var tbl_body = "";
var tbl_row = "";
tbl_row +="<?php foreach($data as $row) {} ?>" (Error at this line)
tbl_body += tbl_row;
return tbl_body;
}
</script>
If i remove this row then error disappears.
What i am trying: I am trying to loop through the result returned from DB and display values.
Please anyone can assist?
You most likely have double quotes in the content generated by PHP. You need to escape them properly, or, providing you don't have single quotes in the PHP content, you could do:
tbl_row +='<?php foreach($data as $row) { /* ... */} ?>';
As noted in the comments, having newlines in your PHP content might also cause this issue. Remove or replace them.
Try something like this:
<?php foreach ($data as $row) { ?>
tbl_row += <?php echo json_encode(whatever); ?>;
<?php } ?>
Using json_encode() will ensure that the PHP value is correctly encoded for Javascript.
Try this:
<?php foreach($data as $row) {?>
tbl_row +=<?php echo $row;?>
<? }?>
what it contain?the
'data' that is passed to this function "makeProdiv(data)"
& $data.
I guess $data is an array of "tr" fetched from db.