Passing PHP array to javascript using json_encode giving errors? - javascript

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);
?>;

Related

Error passing php array with json_encode to js handler

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.

passing array data from PHP to Javascript

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.

Populating jQuery datatables from mysql using ajax

I am trying to populate datatables on button click which will send a date to process.php which in turn will query the database and output a json array.
Here are my code:
Javascript:
var dailyCollTable = $("#dailyColl").DataTable();
$("#dailyBills").click(function(){
var date = $("#billDate").val();
$.ajax({
type:'post',
url:'process.php',
data:{date:date},
dataType:'json',
success:function(s){
console.log(s);
dailyCollTable.fnClearTable();
for(var i = 0; i < s.length; i++){
dailyCollTable.fnAddData([ s[i][0], s[i][1], s[i][2], s[i][3], s[i][4], s[i][5] ]);
}
}
});
});
And this is my process.php
<?php
$connection = mysqli_connect("localhost", "root", "", "database");
$date = $_POST['date'];
$query = mysqli_query($connection,"SELECT CustomerName,BillNumber,BillDate,BillAmount,PaidAmount,PaymentDate FROM billentry WHERE Status=1 AND PaymentDate='$date'");
while($fetch = mysqli_fetch_array($query)){
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5]);
}
echo json_encode($output);
?>
I checked browser console. the array is coming fine. The error I am getting is
Uncaught TypeError: dailyCollTable.fnClearTable is not a function
I have included all the necessary libraries.
The exact same code worked on my earlier tables.
There is mistake at the end of query ...PaymentDate='$date'
You should write ...PaymentDate='" . $date . "'

Assigning PHP Variables To Javascript Variables Not Working

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.

SyntaxError: missing ; before statement with AJAX

I came across this error while doing an ajax request and after looking over if I simply can't find the problem. Here is the code below.
$('#post_submit').click(function() {
var poster_id = <?php echo $session_user_id; ?>;
//firebug syntax error shows the line below is the problem
var profile_user_id: <?php echo $user_id; ?>;
var post = $('#post').val();
$.post('ajax_submit_post.php',
{
profile_user_id: profile_user_id,
poster_id: poster_id,
comment_type : comment_type,
post: post
},
function () {
$('#status').append('<li class="hide">Posted</li>').hide(1000);
});
});
I think you meant to use the equals sign?
var profile_user_id = <?php echo $user_id; ?>;
instead of
var profile_user_id: <?php echo $user_id; ?>;

Categories

Resources