I have the following javascript code that attempts to insert HTML code dynamically. I have an error the syntax but I do not know how to correct it. Please can someone advise?
loadNextContainer.innerHTML = '<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\''+numDownloadSoFar+'\', \''+maxDownloadLimit+'\', \''+folderName+'\', \''+jsonHashTags+'\', \''+fromDate+'\', \''+toDate+'\', \''+lastScanId+'\')">LoadNext</span>';
ERROR MESSAGE:
Uncaught SyntaxError: Invalid or unexpected token
I believe the error revovles around the function variables. In particular the JSON variable. I cannot change the use of double quotation marks for each element in the JSON. So that has to stay in any solution.
You could try it using backticks like this.
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords('`+numDownloadSoFar+`', '`+maxDownloadLimit+`', '`+folderName+`', '`+jsonHashTags+`', '`+fromDate+`', '`+toDate+`', '`+lastScanId+`')">LoadNext</span>';
Or just escape the double-quotes instead of the single quotes. The way you're doing it, you're unintentionally opening up the string when you try to escape it.
loadNextContainer.innerHTML = "<span class=\"sr_43\" id=\"srloadnext_2\" onclick=\"srt.loadNextMatchRecords('"+numDownloadSoFar+"', '"+maxDownloadLimit+"', '"+folderName+"', '"+jsonHashTags+"', '"+fromDate+"', '"+toDate+"', '"+lastScanId+"')\">LoadNext</span>";
Judging from your image of your variables, none of the template literal solutions are going to help you, because at least one of your parameters is an array.
Yes, it would be possible, with enough effort, to convert that array into a string representation that would work with innerHTML. But it's going to be very difficult. You'd end up needing to use JSON.stringify to get the string version of your array at least.
An easier solution is actually going to be to create the element and then add the onclick operator through pure javascript, like this:
var s = document.createElement('span');
s.className = 'sr_43';
s.id = 'srloadnext_2';
s.innerText = 'LoadNext';
loadNextContainer.appendChild(s);
s.onclick = function(e) {
srt.loadNextMatchRecords(numDownloadSoFar, maxDownloadLimit, folderName, jsonHashTags, fromDate, toDate, lastScanId);
};
Try it with template literals:
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\'${numDownloadSoFar}\', \'${maxDownloadLimit}\', \'${folderName}\', \'${jsonHashTags}\', \'${fromDate}\', \'${toDate}\', \'${lastScanId}\')">LoadNext</span>`;
Edit:
As others already mentioned. Sorry.
Related
I appreciate this has been asked numerous times before, as I have just spent the last nine hours reading the questions and answers, over and over, however, I cannot resolve the issue.
I want to pass my php object businessSectors to the html data attribute data-sectors, convert it to JSON, so I can pass it to a javascript function, where I will parse it in to a javascript object.
<td><input type="checkbox" class="minimal"
name="template[]" data-sectors="{{json_encode((array)$template->businessSectors)}}" value="
{{$template->_id}}" {{$template->display ? "checked" : ""}}></td>
Error:
Uncaught SyntaxError: Unexpected token E in JSON at posostion 0 at JSON.parse`
I believe therefore, and correct me if I am wrong, that whatever is being passed to the JSON.parse method is not a valid JSON string.
I've tried therefore to manipulate the value of the data-sectors attribute in my .blade.php in numerous ways, to resolve the issue. I almost certain there is a character that needs escaping but the solution is avoiding me.
Inspecting source gives me:
<input type="checkbox" class="minimal" name="template[]" data-sectors='["Education and
Training"]' value="5d3eb15110560b0a800f359c" >
Could someone please kindly point me in the right direction, and by "point me in the right direction", I mean, please explain in terms that a frustrated layman can understand, exactly what the problem is, and how to go about resolving the issue.
Edit:(Please see the javascript)
<script>
$(document).ready(function(){
let businessSectorData = {!! json_encode($businessSector) !!};
let $businessSector = $("#businessSector");
$businessSector.select2(stdSelect2(businessSectorData));
$businessSector.on("change", function (e) { log("change",e) });
function log (name, evt) {
$("input[name='template[]']").each(function(){
let $this = $(this);
let sectors = JSON.parse($this.data("sectors"));
var i = 0
});
}
})
The jQuery .data() method detects attribute values that look like JSON and parses them automatically. You don't have to call JSON.parse() yourself. The return value of $this.data("sectors") will be an already-parsed JavaScript array.
You have to be careful however about dropping a JSON string into an attribute value, because your serialized value may include single-quote characters. You can escape those easily with a regular expression substitution.
I would recommend base64 encoding the array before adding it to data-sectors. You won't have to worry about unescaped values, and it is a common approach.
You can then decode and parse the array successfully.
Here is an example:
<input
type="checkbox"
class="minimal"
name="template[]"
data-sectors="WyJFZHVjYXRpb24gYW5kIFRyYWluaW5nIl0="
value="5d3eb15110560b0a800f359c"
/>
<script>
(() => {
const element = document.querySelector(".minimal");
const sectors = JSON.parse(atob(element.dataset.sectors));
console.log("data", sectors);
})();
</script>
You can use the PHP function base64_encode() to do the encoding.
This is using Mirth Connect which uses E4x and js.
Basically I have a variable that I want to populate the XML with.
var memberid = "1234";
var fieldsxml = new XML(<fieldvaluelist></fieldvaluelist>);
fieldsxml.field += <fieldvalue templatefieldid="446" value=#memberid/> //memberID
But its giving an error on the 3rd line: (I also tried just memberid without quotes)
DETAILS: TypeError: Open quote is expected for attribute "value"
associated with an element type "fieldvalue".
It works if the third line is this:
fieldsxml.field += <fieldvalue templatefieldid="446" value="memberid"/>
But that just adds the literal string "memberid" . I actually want value="1234" instead.
How can I do this?
Edit: The final XML should look like this.
<fieldvaluelist><fieldvalue templatefieldid="446" value="1234"/></fieldvaluelist>
You're almost there. Instead of using #memberId, use {memberId}:
fieldsxml.field += <fieldvalue templatefieldid="446" value={memberid}/>;
I have a (simple, I guess) problem with quotes, single quotes, double quotes.
I have a JS that sends data to a php file, which responds sending some data back with json. In the code below, row.Dispon is part of the response (and is working OK). But I want to "echo" row.Element inside getElementById with no success. I've tried "+row.Element+", or "'+row.Element+'". What I'm doing wrong?
if (row.Dispon=="ImageReload") {
var text='Image changed';
document.getElementById(+row.Element+).value="due";
}
Considering your code snippet only, this should do the job for that specific problem:
if (row.Dispon == "ImageReload") {
var text = 'Image changed';
document.getElementById(row.Element).value = "due";
}
You would need quotes (or double quotes) and + operators if you were trying to build a string. See this example:
var id = 42;
document.getElementById('myId' + id).value = 'something';
Assuming that row.Element contains a string already, you can directly pass it to getElementById().
Some advice here:
Read more about functions on MDN
Read more about Document.getElementById on MDN
Consider using Document.querySelector
I want to escape javascript entities on client side. For example :-
If my input string is tes"t result should be tes\"t
Is there any inbuilt function provided by jquery for this ?
This is a really crazy, almost stupid shot in the dark on my part, but...
If you're using a server-side language like PHP to output variables' contents into JavaScript, you should use json_encode as this handles ALL escaping for you, regardless of the type of variable.
On the other hand, if you're (I really hope you're not) doing something like this:
var input = "test"t";
And trying to escape that properly while in JavaScript... that's not going to work. It's a syntax error. You need to escape your literals manually.
Kevin van Zonneveld provide a JavaScript equivalent of PHP’s addslashes here :
http://phpjs.org/functions/addslashes/
function addslashes(str) {
// example 1: addslashes("kevin's birthday");
// returns 1: "kevin\\'s birthday"
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0');
}
Based on this function, I guess you might want to add this function to prototype of the String like this.
if (!String.prototype.addslashes) {
String.prototype.addslashes = function () {
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};
}
var str = 'tes"t';
alert(str.addslashes()); // shows 'tes\"t'
DEMO: http://jsfiddle.net/naokiota/6F6aN/6/
Hope this helps.
I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}
Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.