Uncaught SyntaxError: Unexpected end of input line 1 - javascript

Hi there I am trying to figure out what is going wrong. I am getting the error
Uncaught SyntaxError: Unexpected end of input in line 1
which is
var itemList = new Array();
A snippet of the code is included
var itemList = new Array();
$( document ).ready(function(){
var $newItem = $('#newItem');
var $itemList =$('#itemList');
var itemTouchStart;
var itemTouchEnd;
var itemTouchStartX;
var itemTouchEndX;
if( window.localStorage) //when application starts check if there is data
{
itemList = JSON.parse(window.localStorage.getItem('itemList'));
}
if(null !== itemList)
{
for (i=0;i<itemList.length; i++)
{
var itemNew = '<li data-key="'+ itemList[i].key +'"><span>'
+itemList[i].item +'</span></li>';
$itemList.append(itemNew);
}
}
else
{
itemList = new Array();
}

The line number of the error is wrong. The problem is at the end, you never close the function you're passing into ready or the call to it. Add }); at the end.
If that's missing only because you quoted a
...snippet of the beginning of the code...
...then the answer is that there's nothing wrong with line 1 that's apparent from your question. Weird errors like that can sometimes be down to invisible characters in the source, but I would expect to see an illegal character error rather than unexpected end of input. Unexpected end of input is pretty much what it says: You have a control structure of some kind open and haven't closed it when the parser reaches the end of the code text.
I find the Meteor JavaScript parser page is quite handy for diagnosing syntax errors.

Related

How to loop through ViewData with Javascript in ASPX View

I have populated ViewData item with an array of questions so that I can store the json data in local storage:
string[] jsonQuestions = new string[StudentExam.QuestionCount];
for (int i = 0; i < StudentExam.QuestionCount; i++)
{
jsonQuestions[i] = new JavaScriptSerializer().Serialize(StudentExam.QuestionsE[i]);
ViewData[i.ToString()] = jsonQuestions[i];
}
During testing I loaded the ViewData into the localstorage like this (hard coded) for the exact amount of questions:
localStorage.setItem("obj0", JSON.stringify(<%=ViewData["0"]%>));
localStorage.setItem("obj1", JSON.stringify(<%=ViewData["1"]%>));
localStorage.setItem("obj2", JSON.stringify(<%=ViewData["2"]%>));
localStorage.setItem("obj3", JSON.stringify(<%=ViewData["3"]%>));
//...etc.
In the view I am trying to now dynamically load the ViewData into the browser localstorage like this using javascript:
<script>
var mod = "<%=Html.Raw(Model.TotalNumberOfQuestionsForTest.ToString())%>";
for (var i = 0; i < mod; i++) {
localStorage.setItem(
"obj" + i.toString(),
JSON.stringify(<%=ViewData[i.toString()]%>));
};
</script>
Now this gave me an error that it cannot find i, since we "escaped" the client side code. So I changed it to :
for (var i = 0; i < mod; i++) {
var s = <%=ViewData[%>i.toString()<%]%>;
localStorage.setItem(
"obj" + i.toString(),
JSON.stringify(<%=ViewData[%>i.toString()<%]%>));
};
This is the part where I'm stuck at. I keep getting these errors on this line:
JSON.stringify(<%=ViewData[%>i.toString()<%]%>));
Error 7 Invalid expression term ';'
and
Error 8 ; expected
and when I run the web app this is all I get on inspect element:
Compilation Error
Description: An error occurred during the compilation of a resource
required to service this request. Please review the following specific
error details and modify your source code appropriately.
Compiler Error Message: CS1525: Invalid expression term ')'
Source Error:
Line 278: localStorage.setItem( Line 279:
"obj" + i.toString(), Line 280:
JSON.stringify(<%=ViewData[%>i.toString()<%]%>)); Line 281: Line 282:
};
Is there a way to escape the <%%> tags, into the javascript again for the javascript variable to use in the ViewData? Or another way to do this?
UPDATE:
I went on and played around with the code a bit more and this is the closest I have gotten to what I need to happen by doing it like this:
$(function () {
<% for (int i = 0; i < 1; i++){%>
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify('"%><%=ViewData[i.ToString()]%>"'))"
<%}%>
});
So this does loop through my questions and put the value in where I needed, but the last issue I have is that now by having to put the javascript in quotations :
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify('"%><%=ViewData[i.ToString()]%>"'))"
The last quotation mark is needed to close the string between the <%%> tags. but this quotation mark is giving me the error:
Invalid or unexpected token
as my javascript to store the localstorage looks like this now:
localStorage.setItem("obj1", JSON.stringify("my json query"))" //this quotation is the problem
Any assistance or help will be greatly appreciated.
I finally fix the problem. The issue with the quotation was that I was "stringifying" a string and the moment I removed the single quotation marks from the code:
$(function() {
<% for (int i = 0; i < Model.TotalNumberOfQuestionsForTest; i++){%>
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify("%>
<%=ViewData[i.ToString()]%>
<%="))"%>
<%}%>
The json object was successfully stored in the localstorage of the browser.

Regex escaping bracket in javascript not working

I've got a chunk of code that is doing something really strange.
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
var isThankyou = getQuerystring('CONFIRMATION');
This function checks the URL for a parameter (in this case CONFIRMATION). From what I can tell everything is correct, but when the browser loads the code it throws an error in the console.
Uncaught SyntaxError: Invalid regular expression: missing /
Ultimately this chunk of code is used to determine if a user is on the confirmation page of the URL. If they are then it triggers some google analytics code to track ecommerce purchase information in GA.
The line that is giving me trouble is:
key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
When I load the page in the browser and look at the source this is what shows up:
key = key.replace(/[\[]/,'\\\[').replace(/[\/,'\\\]');
with two ]] showing up just before
Here's the weird thing. When I duplicate the line commenting out the first one, the error doesn't get thrown (the ]] still shows up however):
//key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
I've tried everything I can think of with no success, I've even tried unchaining the replace method in case that was causing the issue.
key = key.replace(/[\[]/,'\\\[');
key = key.replace(/[\]]/,'\\\]');
Which results in the following in the browser source:
key = key.replace(/[\[]/,'\\\[');
key = key.replace(/[\/,'\\\]');
In any case, the issue seems to be with the second .replace not escaping the one ] or even keeping the two ]] for some reason.
I've also tried erasing cache, cookies, and turning off all plugins. I've tested in Chrome, Firefox, and Safari with the same results on all 3 browswers.
Here is the page that you can see the full block of code (last in the head): https://secure2.convio.net/ccod/site/Ecommerce?store_id=2841
Your code looks a bit complex. Here's something simpler:
function getQueryString(key) {
var index, url, parts, i, subparts;
url = window.location.href;
index = url.indexOf("?");
if (index === -1) {
return null;
}
url = url.substr(index);
parts = url.split("&");
for (i = 0; i < parts.length; i += 1) {
subparts = parts[i].split("=");
if (subparts[0] === key) {
return subparts[1];
}
}
return null;
}
(untested)
This causes an error: key = key.replace(/[\/,'\\\]') because you escape the forward slash at the end of the regex with a back-slash like this: /[\/
Try this instead key = key.replace(/[\\/,'\\\]')

jQuery: Getting syntax error after split() or text()?

What I need to do is grab the first <p> tag within an element, loop through all of the words, and wrap them in <span> tags. I wrote a script for this, which I thought worked, but it appears to break when some characters are in the <p> tag. I don't know which character(s) that causes it to break though.
Here is my current code:
$(document).ready(function(){
// Transform is set on html tag by modernizr
// Apply this on all .quote boxes, even if there are multiple (most likely aren't)
$('.csstransforms .quote').each(function() {
// Get data
var elem = $(this).find('p:first'),
html = elem.text(),
words = html.split(" "),
charCount = html.length
$(this).append('<p class="fixed"></p>');
// Add new words
var tmpWord = '';
for(i=0; i< words.length ; i++) {
tmpWord = $.trim(words[i]);
if(tmpWord && tmpWord != "") {
// Maybe replace with $(elem).next('.fixed') or something?
$('.csstransforms .quote .fixed').append('<span>'+ tmpWord +' </span>');
}
}
// Check word count, make size smaller if needed
if(charCount > 150) {
// Add class to .quote box
$(this).addClass('smaller');
}
// Hide original <p>
$(elem).hide();
});
});
The error i'm getting is as follows, and what you see in the text is the actual quote:
Uncaught Error: Syntax error, unrecognized expression: "In the decade or so, science has discovered a tremendous amount about the role emotions play in our lives. Researchers have found that even more than IQ, your emotional awareness and abilities to handle feelings, will determine your success and happiness in all walks of life, including family relationships". – John Gottman, Ph. D.
Any ideas as to what is causing this, and how to fix it? Been chewing on it on a while without success.
Update: Jsfiddle showing same error: http://jsfiddle.net/Uugbc/
Just for clarification. Your fiddle has
charCount = $(html).text().length;
but your variable html is not a jQuery object.
This will work better
var elem = $(this).find('p:first'),
html = elem.text(),
words = html.split(" "),
charCount = html.length; // here you had $(html).text().length;

err variable space is undefined why?

I run next code and I miss somthing, for me it seem OK :
window.onload = TitleFieldInit;
function TitleFieldInit() {
var str = document.cookie.split("=")[1];
var space = str.split("=")[1];
space = space.split(";")[0];
alert(space);
// while( space.indexOf('%20' )+1) space = space.replace(/%20/,' ');
if (document.cookie != "") {
document.getElementById("TitleField").innerHTML = "Your Title is : " + space;
}
}​
and I got err in FireFox rror"space is undefined" why ?
In chrome "Uncaught TypeError:Cannot call method'split' of Undefined"
Thx for helping.
This code will never work for any input.
str is a already part of result of split by =, i.e. it contains no = symbols.
Then you split that result again by =, which of course will return you one-element array and str.split("=")[1] will always be undefined.
Looks like you're trying to read cookie value... but second .split("=") is not needed at all.
Ah, and you got different results in different browsers, cause they contain different data in their cookies.
PS: Instead of while( space.indexOf('%20' )+1) space = space.replace(/%20/,' '); you may write space = space.replace(/%20/g,' '); to replace all of them at once.

Error creating a Javascript Object

The line of code below, which I thought creates a javascript object, gives me the following error:
Uncaught SyntaxError: Unexpected token {
This is the line of code:
var flyer2 = {"id":20,"img_url":"http://images.awfbeat.com/48395b02-59e5-4e26-b7bc-8c603008c9c4","img_width":0,"img_height":0,"popularity":0,"color":"#67c547","tag":"Jul 10","category":"festivals","title":"Darth Vader\\\u0027s \\\"Annihilator\\\"","title_slug":"darth-vader-s-annihilator-","performer":"","performer_sort":"xxxx","posted":"2012-03-11 04:09:20.0","facebook_event_id":"","venue_postal":"90802","venue_name":" Aquarium of the Pacific","venue_street":"100 Aquarium Way","venue_city":"Los Angeles","venue_region_abbr":"CA","venue_lat":"33.762226","venue_lng":"-118.19686","needs_info":false};
What exactly am I doing wrong?
You're html-encoding the quotes.
Not 100% sure, but I guess the ampersand is parsed as the bitwise and operator, semicolons as line end symbols.
If this is serverside code then
the solution is:
var flyer2 = "{"\""id"\"":20,"\""img_url"\"":"\""http://images.awfbeat.com/48395b02-59e5-4e26-b7bc-8c603008c9c4"\"","\""img_width"\"":0,"\""img_height"\"":0,"\""popularity"\"":0,"\""color"\"":"\""#67c547"\"","\""tag"\"":"\""Jul 10"\"","\""category"\"":"\""festivals"\"","\""title"\"":"\""Darth Vader\\\u0027s \\\"\""Annihilator\\\"\"""\"","\""title_slug"\"":"\""darth-vader-s-annihilator-"\"","\""performer"\"":"\"""\"","\""performer_sort"\"":"\""xxxx"\"","\""posted"\"":"\""2012-03-11 04:09:20.0"\"","\""facebook_event_id"\"":"\"""\"","\""venue_postal"\"":"\""90802"\"","\""venue_name"\"":"\"" Aquarium of the Pacific"\"","\""venue_street"\"":"\""100 Aquarium Way"\"","\""venue_city"\"":"\""Los Angeles"\"","\""venue_region_abbr"\"":"\""CA"\"","\""venue_lat"\"":"\""33.762226"\"","\""venue_lng"\"":"\""-118.19686"\"","\""needs_info"\"":false}";
else
var flyer2 = {"id":20,"img_url":"http://images.awfbeat.com/48395b02-59e5-4e26-b7bc-8c603008c9c4","img_width":0,"img_height":0,"popularity":0,"color":"#67c547","tag":"Jul 10","category":"festivals","title":"Darth Vader\\\u0027s \\\"Annihilator\\\"","title_slug":"darth-vader-s-annihilator-","performer":"","performer_sort":"xxxx","posted":"2012-03-11 04:09:20.0","facebook_event_id":"","venue_postal":"90802","venue_name":" Aquarium of the Pacific","venue_street":"100 Aquarium Way","venue_city":"Los Angeles","venue_region_abbr":"CA","venue_lat":"33.762226","venue_lng":"-118.19686","needs_info":false};
or else use single quota.

Categories

Resources