ReferenceError: $output is not defined in javascript(Jquery) - javascript

I'm making an API where I would like to get all users and then display them in some sort of table. However now I'm getting a ReferenceError: $output is not defined when running the code. I tried this out in another project and it doesn't give that error there.
My JavaScript code:
function displayData(data) {
$('.content').empty();
console.log(data.length);
for (var i = 0; i < data.length; i++) {
$output += '<div>' + data[i].ContactName + '</div>';
$(".content").append($output);
}
}
Which I'm trying to output to this div:
<div class="content">
</div>
I have no idea why I am getting this error while it is running without on another project. Thanks in advance for helping me out!

Please Refer Below Fiddle..
Fiddle
JavaScript
var $output = '';
var data = [{'ContactName':'ABC'},{'ContactName':'EFG'}]
$( document ).ready(function() {
displayData(data);
});
function displayData(data){
$('.content').empty();
console.log(data.length);
for (var i = 0; i<data.length; i++) {
$output+= '<div>'+data[i].ContactName+'</div>';
$(".content").append($output);
}
}
HTML
<div class="content">
</div>
Declare $output as a Variable.
var $output = '';

Related

Display laravel variable using javascript

when i try dd($conv) the data are there, but I still can't display them inside the script.
Anyone know whats the problem, I have tried many ways but they doesn't seem to work.
<h4>{{$row->transcript_text}}</h4>
<?php $conv = json_encode($row->transcript_text); ?>
<script type="text/javascript">
function splitArray() {
var myStr = <?php echo $conv; ?>;
var strArray = myStr.split(/(?= \| \d)/);
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
})
}
splitArray();
</script>
I don't know which version of Laravel you're using but the recommended way to embed plain PHP in your HTML templates is with the #php notation (cf doc).
Anyway, that's something I'd try to avoid. Instead, Laravel blade has native ways of doing what you're trying to do.
#if(! empty($history))
#foreach($history as $row)
<script type="text/javascript">
function splitArray() {
var myStr = JSON.parse("{{json_encode($row->transcript_text) }}");
var strArray = myStr.split(" | 0");
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
}
}
</script>
<body onload="splitArray()" style="color: lime">
</body>
#endforeach

Passing values of array into HTML text box

Let say I have a function that populates an array
function 1(){
var array = []
//do things
//array.push("stuffs")
How can I pass or iterate through this array into an HTML text box?
Edit for clarity
I am working with google apps script.
I have a .gs file which runs server side.
I have an .html file which populates my UI.
In the .gs file I am populating an array based on information from a google sheet.
once I have this array I want to populate a text box in the .html file.
I am about 12 hours into html so I may not even understand this enough to articulate my questions correctly.
var html = '';
var array=['apple', 'peach','pear'];
$.each(array, function(index, item){
html+='<input type="text" value="' + item + '"/>';
});
$('body').append(html);
FIDDLE
Code.gs:
function doGet() {
var t = HtmlService.createTemplateFromFile('index');
t.data = SpreadsheetApp
.openById('1234567890abcdefghijklmnopqrstuvwxyz')
.getActiveSheet()
.getDataRange()
.getValues();
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
index.html:
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
You can use same for input i guess.
Reference

Pagination of table data from json

I want to paginate results obtained thusly:
function processResponse(response){
var myObj = JSON.parse(response);
var weighInData = myObj["WEIGH-INS"];
var weights = []; // re: weigh-in count and calculating highest/lowest
var userDisplayEl1 = document.getElementById("user-display-weigh-in-data");
var weighInCountEl = document.getElementById("weigh-in-count");
var weightLowEl = document.getElementById("weight-low");
var weightHighEl = document.getElementById("weight-high");
var weightgoalEl = document.getElementById("weight-goal");
var dataRows = document.getElementById("data-rows");
userDisplayEl1.innerHTML = "";
weighInCountEl.innerHTML = "";
weightLowEl.innerHTML = "";
weightHighEl.innerHTML = "";
weightgoalEl.innerHTML = "";
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) {
weights.push(weighInData[obj].weight);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
dataRows.innerHTML += row;
// pagination here?
} // if ... === selUser
} // for var obj in weighInData
var weighInCount = weights.length;
var weightLowest = Math.min.apply(null, weights);
var weightHighest = Math.max.apply(null, weights);
userDisplayEl1.innerHTML = weighInData[obj].user + "'s weigh-ins:";
weightLowEl.innerHTML += weightLowest;
weightHighEl.innerHTML += weightHighest;
weighInCountEl.innerHTML = weighInCount;
} // processResponse
It seems that, because I'm executing Math on the results (after the for loop), I cannot use a limit in my db query, else the math would be inaccurate (executing only on the chunks of data, and not on the entirety of the data). So it seems I'll have to paginate on the client, but I have no idea how to proceed given how I'm currently loading/displaying the data. I have looked briefly at a couple of pagination plugins but since I wasn't clear on how to implement them given my extant code, I prefer the learning curve of achieving this w/out a plugin (or jQuery).
Any suggestions/pushes in the right direction, with the assumption that I con't substantively alter what I have now (which works, and which I understand, will be most appreciated.
Btw, my server-side code, fwiw:
$table = "`WEIGH_IN_DATA`";
if ($mysqli) {
$user = $_GET['selUser'];
$i = 0;
$jsonData = '{"WEIGH-INS": [';
$stmt = $mysqli->stmt_init();
$query = "SELECT * FROM $table WHERE USER = '$user'";
$result = $mysqli->query($query) or die("Error in the query (?)" . mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)) {
$i++;
$user = $row["USER"];
$date = $row["DATE"];
$weight = $row["WEIGHT"];
$jsonData .= '{"user": "'.$user.'", "date": "'.$date.'", "weight": "'.$weight.'" },';
}
$jsonData = chop($jsonData, ","); // kill the trailing comma
$jsonData .=']}';
echo $jsonData;
}
Thank you,
svs
To save time, using a plug-in might be your best bet. I'm sure there are tutorials on building your own pagination plug-in on the internet which you can google.
I picked a random jQuery pagination plug-in (datatables), appended some data via js (similar to your code), then called the plug-in on the result table. Something like this may/may not work for you. Also, this is dependent on jQuery, and I'm not sure if you can include this library or not on your website.
Here's an example using dataset and jquery: http://codepen.io/anon/pen/IbBxf
Link to datatables: http://www.datatables.net/
$(document).ready(function(){
// append some data to an existing table in the DOM
for (var i =0 ; i < 10; i++) {
var $nr = $('<tr><td>A-' + i + '</td><td>B-' + i + '</td></tr>');
$('#myTable').append($nr);
}
// after table is populated, initiate plug-in and point to table
$('#myTable').DataTable(
{ "lengthMenu": [[5, 10, -1], [5, 10, "All"]] });
});
If you can't use jQuery:
Vanilla JS: It looks like this library can do pagination, however you'll need to read through the docs:
http://listjs.com/docs/plugins/pagination
This link also looks promising for your case (vanilla JS only):
http://www.tekgarner.com/simple-pagination-using-javascript/
HTML/CSS: If you don't need a lot of features, maybe you could also look at just adding a scrollbar to your HTML table results.
How to display scroll bar onto a html table

Updating PHP from JavaScript for loop

I currently have a JavaScript for loop which increments 'i'. I want to use this to increment a string within a PHP function call like so:
for (var i=1; i <= <?php echo $totalPages[0] ?>; i++){
if(selection=="page"+i){
<?php
$test = 'page'.+i;
?>
document.getElementById("commentid").value = "<?php query2($test,$_SESSION['courseID'], $_SESSION['userID']) ?>";
}
}
This function should call the function query2('page1,2,3,4...',$_SESSION['courseID'], $_SESSION['userID']) incrementing 'pagei'. Although i get the following error:
Uncaught SyntaxError: Unexpected token <
JavaScript is client-side, PHP is processed on the server side and will not be in the HTML output/the environment the JavaScript will run in. What you are attempting is simply not possible.
So you would like sth similar to:
var totalPages = <?php echo $totalPages[0] ?>
var comments = [''<?php
for($i=1;i<$totalPages[0];$i++)
echo(",'".query2("page".$i,$_SESSION['courseID'], $_SESSION['userID'])."'");
?>]
for (var i=1; i <= totalPages; i++) {
if(selection=="page"+i){
document.getElementById("commentid").value = comments[i];
}
}

Javascript get title value from <li>

In general: What I want is to have PHP output an unordered list with books. When the user clicks on one of the titles, the details will be pulled from the DB and inserted into the page using AJAX.
I can't seem to figure out how to pull the title value from the < li > using javascript, so I can pass that to AJAX.
(To simplify the example code, I left out the AJAX part and am using an alert instead.)
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var shelve = document.getElementById( 'books' );
var books = shelve.getElementsByTagName( 'li' );
for( var i=0; i < books.length; i++ ){
books[i].onclick = function(){
alert(books[i].title); //I know this doesn't work
};
}
}
</script>
</head>
<body>
<div id="txtHint"><b>Book info will be listed here using AJAX.</b></div>
<?php show_allBooks(); ?>
</body>
</html>
<?php
function show_allBooks(){
db_connect();
$query = "Select * from tblBooks order by title";
$result = mysql_query($query);
echo "<ul id='books'>";
while ($row = mysql_fetch_array($result))
{
echo "<li title='" . $row['id'] . "'>" . $row['title'] . "</li>";
}
echo "</ul>";
db_close();
}
?>
I tried fooling around with variations of the following code, but this did not seem to work either.
books[i].getAttribute("title")
Can anyone point me in the right direction? Any help would be greatly appreciated.
By the time your onclick handler gets called, i has been incremented to books.length. Instead, you can reference this to get the element.
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = function () {
alert(this.title);
};
}
http://jsfiddle.net/gilly3/cPMAU/
However, if you do need to know the value of i in the click handler, you can do it by creating your handler in a factory, that is a function that returns a function:
function createBookHandler(books, i) {
return function() {
alert(books[i].title);
};
}
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = createBookHandler(books, i);
}
http://jsfiddle.net/gilly3/cPMAU/1/
Start with
books.item(i)
Then it depends how title is stored in the list. If its
<li title="">
then
books.item(i).getAttribute("title")
But the closure related answer is probably more important.

Categories