string literal contains an unescaped line break - javascript

I have an error in console
Uncaught SyntaxError: '' string literal contains an unescaped line break
'<ul>\n' +
'<?php for ($i = 1; $i < 31; $i++){
echo '<li onclick="updateBasket('.$i.','+value['basketID'].')"><?= $i ?></li>';
}
?>'+
'</ul>\n' +

Try this. This will replace your PHP loop with the same thing but in JavaScript. Replace everything including the lines that open and close the <ul>.
// End previous concatenation.
'<ul>\n';
// Insert 30 list items.
for (let i = 0; i < 30; i++)
tr += '<li onclick="updateBasket(' + i + ', ' + value['basketCount'] + ')">' + i + '</li>';
// Continue your concatenation as before.
tr +=
'</ul>\n' +

Related

$.getJSON and for loop with an array and how to get them to work together - for loop completes before JSON is returned

I am trying to cycle through an array and with each value in the array, use $.getJSON to return some JSON and populate an HTML table with the return values.
I have been following this post, but seem not get this to work:
$.getJSON calls misbehaving inside a for loop
Here is my function:
$("#selectProviderTop").click(function() {
var restURL = window.location.protocol + "//" + window.location.hostname + (window.location.port == "" ? "" : (":" + window.location.port)) + "/restGetProvider/";
var selected = [];
var providerKey;
var providerID;
var providerLegacyID;
var providerName;
var finalURL;
var tr;
// First, create an array from the User Provider Keys...
var userProviderKeys = $("#hiddenUserProviderKeys").val();
selected = userProviderKeys.split(",");
console.log("selected: " + selected);
var tableHTML = "";
var focus = $("<div></div>"); // either match an existing element or create one: '<div />'
var arrayLength = selected.length;
for (var i = 0; i < arrayLength; i++) {
(function(i) {
console.log("i: " + i);
providerKey = selected[i];
console.log("providerKey: " + providerKey);
// Get that provider and populate the table...
finalURL = restURL + providerKey;
console.log("finalURL: " + finalURL);
focus.queue('apicalls', function(next) {
$.getJSON(finalURL, function(jsonObject) {
tableHTML += "<tr>";
tableHTML += "<td><a href=\"#\" onclick='selectProvider(\"" + providerKey + "\")'>" + jsonObject["providerName"] + "</a></td>";
tableHTML += "<td>" + jsonObject["providerID"] + "</td>";
tableHTML += "<td>" + jsonObject["providerLegacyID"] + "</td>";
tableHTML += "</tr>";
console.log("tableHTML: " + tableHTML);
next();
});
});
})(i);
}
// Replace table’s tbody html with tableHTML...
console.log("final tableHTML: " + tableHTML);
$("#tableProviderSelect tbody").html(tableHTML);
$('#modalSelectProviderForPTP').modal('show');
});
The userProviderKeys value is 0be32d8057924e718a8b6b4186254756,2dc5f826601e4cc5a9a3424caea4115f
The code never makes the $.getJSON call it just completes the for loop.
How do I update this code to get the first value in the array, grab the JSON, create the HTML, and then cycle through the loop?
I have tried setTimeout but that didn't help me out.
If you have some ideas, could you update my existing code - I understand better when I see the code itself. Thanks.
I don't know why you're doing this using queues. But you are, so I'm not going to rewrite your code to do it some other way.
The last few lines need to be called after all the queued functions have run, which means they should be called asynchronously. (Yes, you could make the whole thing synchronous as Marcus Höglund suggested, but that's no way to write scalable applications in javascript.) You could do this by adding another function to the queue containing these lines. Like this:
$("#selectProviderTop").click(function() {
var restURL = window.location.protocol + "//" + window.location.hostname + (window.location.port == "" ? "" : (":" + window.location.port)) + "/restGetProvider/";
var selected = [];
var providerKey;
var providerID;
var providerLegacyID;
var providerName;
var finalURL;
var tr;
// First, create an array from the User Provider Keys...
var userProviderKeys = $("#hiddenUserProviderKeys").val();
selected = userProviderKeys.split(",");
console.log("selected: " + selected);
var tableHTML = "";
var focus = $("<div></div>"); // either match an existing element or create one: '<div />'
var arrayLength = selected.length;
for (var i = 0; i < arrayLength; i++) {
(function(i) {
console.log("i: " + i);
providerKey = selected[i];
console.log("providerKey: " + providerKey);
// Get that provider and populate the table...
finalURL = restURL + providerKey;
console.log("finalURL: " + finalURL);
focus.queue('apicalls', function(next) {
$.getJSON(finalURL, function(jsonObject) {
tableHTML += "<tr>";
tableHTML += "<td><a href=\"#\" onclick='selectProvider(\"" + providerKey + "\")'>" + jsonObject["providerName"] + "</a></td>";
tableHTML += "<td>" + jsonObject["providerID"] + "</td>";
tableHTML += "<td>" + jsonObject["providerLegacyID"] + "</td>";
tableHTML += "</tr>";
console.log("tableHTML: " + tableHTML);
next();
});
});
})(i);
}
focus.queue('apicalls', function(next) {
// Replace table’s tbody html with tableHTML...
console.log("final tableHTML: " + tableHTML);
$("#tableProviderSelect tbody").html(tableHTML);
$('#modalSelectProviderForPTP').modal('show');
next();
});
});
Edit: Sunshine has pointed out that the linked stackoverflow post has mysterious references to the .dequeue method. In the accepted answer, this method is called explicitly after the tasks have been queued. I don't know whether this was necessary or not. I had thought that the problem was that the $.json bit wasn't happening until after the $("#tableProviderSelect tbody").html(tableHTML); part. But now I realise you wrote: "The code never makes the $.getJSON call it just completes the for loop." In that caseSunshine may have been right, and you need to add focus.dequeue('apicalls'); just after the last focus.queue(...);.

How to break part of code using label and break statement in JavaScript?

I want to make some part of my code stop looping, but keep looping for another variable. How can I possibly do that ? I tried this code but it's not working
// Looping based on number of data
for ( var i = 0; i < data.length; i++ ) {
// Looping HTML table data output
if ( !search || data[i].some(someSearch) ) {
// Output table HTML + indexing number
outputTable: {
output += '<tr>';
output += '<td>' + index + '</td>';
for ( var j = 0; j < data[i].length; j++ ) {
output += '<td>' + data[i][j] + '</td>';
}
output += '</tr>';
index++;
}
// Data display limitation
// based on combobox value
if ( index > parseInt(searchLimit.val()) ) {
break outputTable;
}
}
// Count filtered data
searchFiltered++;
}
From that code, I want to break the part of code inside outputTable label, but keep searchFiltered looping. Can someone help me? Thanks :)
No need to use break statement here. Put if condition like this. Every time the index value check it is lesser than parseInt(searchLimit.val()). if it is not it exit the if statement.
if ( index < parseInt(searchLimit.val()) ) {
outputTable: {
output += '<tr>';
output += '<td>' + index + '</td>';
for ( var j = 0; j < data[i].length; j++ ) {
output += '<td>' + data[i][j] + '</td>';
}
output += '</tr>';
index++;
}
}

javascript/json nested for and for/in loops in framework7 popups

Hi all I hope someone can help Im a bit stuck single developer on own , with the below what im trying to do is nest for loops, I have data back at the var = I; but not at the next two for statements, when the popup is called only the last record comes back I can see in console the data is there and the ids for the link and the data within do illicitate around , however only the last record appears I haven't uploaded the json because its a really long script any help on this would be very appreciated I have been playing with nested loops and got them to work just not in the bellow I normally use for/in apparently that's bad practice from what ive read up so changed to flat for loops.
<pre> $.getJSON('myurl', function (data) {
console.log(data);
var data = data.sponsor;
var output = "";
var myApp = new Framework7();
var $$ = Dom7;
output += "<ul>";
for (var i = 0; i < data.length; i++) {
output += "<li class='list-block media-list sponsors list-block-search '>";
output += "<div class='item-media-auto'>" + data[i].images + "</div>"; //working
output += "<div class='item-inner'>";
output += "<div class='item-title-row'>";
output += " <div id='name' class='item-title'>" + data[i].title + data[i].id +"</div>";
output += "</div>";
output += "<a href=" + data[i].custom['panaone_sponsorurl'] + " target='_blank'>";
output += data[i].custom['panaone_sponsorurl'];
output += "</a>";
output += ' <p>Create Popup</p>';
output += "</li>";
document.getElementById("placeholder").innerHTML = output;
output += "</ul>";
}
for (var l = 0; l < data.length; l++) {
$$('.create-popup'+ data[l].id).on('click', function () {
for (var j = 1; j < data.length; j++) {
var popupHTML = '<div class="popup '+ data[j].id + '">'+
'<div class="content-block ">'+
'<p>Popup created dynamically.'+ data[j].id + '</p>'+
'<p>Close me</p>'+
'</div>'+
'</div>'+
myApp.popup(popupHTML);
}
});
}
});
}
</pre>

Javascript for loop variable not working

I am having a problem with my for loop inside a javascript function. The variable i is not working as an argument for the function showAlbum(i). Why is that happening?
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td><a href=''onclick='showAlbum(i);' >"+
arr[i].artist +
" - " +
arr[i].title +
"</a></td></tr>";
}
out += "</table>";
Because i wrapped in quotations is the literal character i, not the value held within your i variable. You need to evaluate it outside of the quotations:
out += "<tr><td><a href=''onclick='showAlbum(" + i + ");' >"
The i is within the string literal, so variables are not parsed from the string.
Break out of the string like so:
out += "<tr><td><a href=''onclick='showAlbum(" + i + ");' >"+
// ^^^^^^^^^
Try changing the formatting to:
var i,
out = '<table>';
for (i = 0; i < arr.length; i++) {
out += '<tr><td><a href="" onclick="showAlbum(' + i + ')" >' +
arr[i].artist +
' - ' +
arr[i].title +
'</a></td></tr>';
}
out += '</table>';

SyntaxError: unterminated string literal

Hi I am trying to load some comtent in my html page from js.
js code(relevant)-
for(i=0; i<4 && 4*i+j<data.response.length; i++)
{
html += '<div class="grids_of_4">';
for(j=0; j<4 && 4*i+j<data.response.length; j++)
{
pi1 = data.response[4*i+j].p_image1;
pn = data.response[4*i+j].p_name;
pp = data.response[4*i+j].p_price;
pa = data.response[4*i+j].p_amount;
pid = data.response[4*i+j].p_id;
html += "<div class='grid1_of_4'>";
html += "<div class='content_box'>";
html += "<a href='details.html'>";
html += "<div class='view view-fifth'>";
html += "<img src='/bokaroration/media/" + pi1 + " ' class='img-responsive' alt=''/" + ">";
html += "<div class='mask'>";
html += "<div class='info'>Quick View</div></div></a></div>";
html += "<h4><a href='details.html'> " + pn + "</a></h4>";
html += "<strike>Rs. " + pp + "</strike> Rs." + pa;
html += "<input type='number' id='" + pid + "' min='0' max='100'/" + ">";
html += "<button type='button' style='margin:5px' class='btn btn-sm btn-success' onclick=add(" + pa + ",'" + pid + "','" + pn + "')"
html += ">+</button>";
html += "</div></div>";
}
html += "</div>";
alert(html);
}
and it is alerting correctly but when I click on the button it gives error -
SyntaxError: unterminated string literal
and when I checked inspect element I found problem in button tag -
<button class="btn btn-sm btn-success" rice')="" gate="" onclick="add(180,'qhfghds.;k[','India" style="margin:5px" type="button">
+
</button>
I don't know why it is happening.
Someone please help me.
Thanks in advance.
The short answer is: Because you are constructing HTML by mashing together strings.
You've got an HTML attribute value that is delimited by ' characters. Inside that value you are putting a ' without escaping it (as "). Since it isn't escaped, it terminates the attribute value.
Use DOM (createElement, setAttribute, appendChild, etc.) instead.

Categories