Parse Error Where Nothing Is Wrong - javascript

I'm making a mobile site using Dashcode to help me creating better UIs, but the problem is that I'm getting a strange Parse Error on my code, where nothing is wrong... This is the code:
function get_currency(from, to) {
var XMLHttp; // Create the Ajax handler
XMLHttp = new XMLHttpRequest();
var url = "http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to + "=X";
XMLHttp.open("GET", url, true);
XMLHttp.onreadystatechange = function() {
if(XMLHttp.readyState == 4) {
/* Once the server has completed its tasks display the result */
var response = XMLHttp.responseText;
var parsed_reply = response.split(',');
document.getElementById('txtAmount').value = parsed_reply[1];
}
XMLHttp.send(null);
}
function btConvert_Click(event)
{
get_currency("BRL", "USD");
}
The error is occurring(According to the debugger) at the line 209(the last line of the code), which is the } a the end of this code that I gave. What's wrong?

You're missing a closing } for your onreadstatechange handler, causing the parser to puke at the end of the script. Given the indentation, it's the closing } for the if(XMLHttp.readyState...) check

You're missing a }
Based on your spacing, you haven't closed the { from
if(XMLHttp.readyState == 4) {

Related

Track javascript runtime errors

Is there any way to capture all type of console errors?
Actually, I want to store all console errors to the database so I can fix serious issues of my PHP website.
Here is my current code to catch errors but this code is not capturing internal server errors and some other kind of errors like
www-widgetapi.js:99 Failed to execute 'postMessage' on 'DOMWindow':
The target origin provided ('https://www.youtube.com') does not match
the recipient window's origin
Current script that I have
function ErrorSetting(msg, file_loc, line_no) {
var e_msg=msg;
var e_file=file_loc;
var e_line=line_no;
var error_d = "Error in file: " + file_loc +
"\nline number:" + line_no +
"\nMessage:" + msg;
if(logJsErrors){
theData = "file="+file_loc+"&line="+line_no+"&err="+msg;
ajaxCtrl(
function(){
return true;
},Helpers.RootURL()+"/logs/index",theData
);
}
if(isDebugging){
console.error(error_d);
}
return true;
}
window.onerror = ErrorSetting;
I really appreciate your efforts.
Thank you :)
You could perform a kind of prototype of console.log, when you call console.log an ajax is fired, so you could do somethig like this:
(function () {
var postCons = console.log;
console.log = function (err) {
var xhttp = new XMLHttpRequest();
postCons.apply(this, arguments);
xhttp.open("POST", "log.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {//you could avoid this step
alert(this.responseText);//response from php
}
};
xhttp.send("data="+encodeURI(err));
}
})()
In log.php you could do whatever you want with $_POST['data'] , you could use something like urldecode($_POST['data']) .

Jena Fuseki not working when making an insert query from javascript. No Update parameter error

I have this JavaScript function which aims to insert a keyword in a named graph which belongs to the project Dataset.
function insert(keyword) {
var query = "INSERT DATA {GRAPH <http://test1> {<subj> <pred>'" + keyword + "'. }}";
var endpoint = "http://localhost:3030/project/update";
sparqlQueryJson(query, endpoint, showResults, true);
}
I have executed Jena Fuseki with the --update option. The sparqlQueryJson function is as follows:
function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
var querypart = "query=" + escape(queryStr);
// Get our HTTP request object.
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Code for older versions of IE, like IE6 and before.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Perhaps your browser does not support XMLHttpRequests?');
}
// Set up a POST with JSON result format.
xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
// Set up callback to get the response asynchronously.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// Process the results
callback(xmlhttp.responseText);
} else {
// Some kind of error occurred.
alert("Sparql query error: " + xmlhttp.status + " " + xmlhttp.responseText);
}
}
};
xmlhttp.send(querypart);
};
The showResults function is, in my opinion, not very important here, since it takes the results of the query and show them in HTML.
I followed what is discussed here and here, executing the query using the http://localhost:3030/project/update. The thing is that if I execute the same query on top of the local Fuseki server with the same endpoint url by using the web, it works, but from the JavaScript code, it raises the error:
"SPARQL query error: 400 Error 400: SPARQL Update: No 'update=' parameter".
I'm using Ubuntu 16.04 and Jena Fuseki - version 2.4.1.
To solve this problem the =query parameter has to be changed to =update. In addition, a parameter with the type of the query has to be handled, i.e., update or query.
if(type==="update"){
var querypart = "update=" + escape(queryStr);
}else if(type === "query"){
var querypart = "query=" + escape(queryStr);
}
...
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if(type==="query"){
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
}

JSON parse error: Cannot read property

I have created some little jt code, but it gives me error
function Mind(){
var request = "request";
var reply = "reply";
var words = '';
this.Reply = function(){
if(request == words.nouns[0].noun){
reply = words.nouns[0].noun;
}
else
reply = this.words.nouns[0].noun;
}
this.SetRequest = function(req){
request = req;
}
this.GetReply = function(){
return reply;
}
this.Parse = function(u){
var xmlhttp = new XMLHttpRequest();
var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
return result;
}
this.Construct = function(){
words = this.Parse('mind/words.json');
}}
var mind = new Mind();
mind.Parse('mind/words.json');
and here is my json file
{
"nouns": [
{"noun": "child"},
{"noun": "father"}
]
}
In command live all goes well, but when I run this code, appears error
Uncaught TypeError: Cannot read property 'nouns' of undefined
Mutliple errors. The most fundamental one is that your code ignores that XMLHttpRequest is async, and wont return a value in the same way as "regular" functions. Read about it here: How to make a function wait until a callback has been called using node.js. The TL;DR is that you have to pass in a "callback-function" to your parse-method and "return" your value using that function, instead of using a return-statement. Google for "javascript callbacks" and read a few tutorials if this concept is new to you!
You also have some minor errors, like returning result from Parse, but never actually setting result to anything. Also words is being assigned in multiple places in a way that doesn't really make sense. But both of these things will go away when you solve the sync/async issues.
EDIT:
Essentially the fix looks like this:
this.Parse = function(u, callback){ // this "callback" is new
var xmlhttp = new XMLHttpRequest();
var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
callback(null, words); // we're "returning" the words here
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
// no return statement here!
}
this.Construct = function(){
this.Parse('mind/words.json', function(error, words) {
// here you can use your words!
});
}}

I am trying to implement an AJAX call. What am I doing wrong?

This is my HTML text:
<input type="text" class="resizedsearch" name="searchdb">
<button id="submit" onclick="ajaxCall()">Search!</button>
This is Javascript:
ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
}
And this is where I am trying to display the response that I am receiving from the PHP file:
<b><font size="24" face="Cambria"><p id="democity"></p></font></b>
<font size="6" face="Cambria"><p id="demodes"></p></font>
</br>
The output of the PHP file is stored in $outp and it is in the JSON format.
Any help appreciated. Thank you.
!!UPDATE!!
function ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
}
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
This is how the improvised code looks. Still not working.
Example by FactoryAidan is not going to work as it violates Same Origin Policy (unless you'll run the code in browser console on Google page). Try replacing http://www.google.com with your local address. I tested the code with a little modification and it works, or at least gives alert, so the function is called. Here's it is:
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080"; /* but make sure the url is accessible and of same origin */
xmlhttp.onload=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here');
}
Your code update after my first answer looks like it was done in haste and I think makes the question a little harder. The .open() and .send() methods ended up inside your .onreadystatechange function definition but they need to be outside. Your first one didn't have those placement issues. The code I wrote below has your exact building blocks but with no placement issues so you should be able to follow along with how it matches your example code. I also tested it and it sucessfully sends and receives data back and successfully calls the myFunction() callback function.
Nonetheless, I took your code and rewrote it a bit. If you get an alert('') message when you run it, that means that your xml request worked perfectly. If you don't see an alert('') message. It means your xml request is returning a http 404 error, which means your request URL is bad. Try changing your request URL to something you know won't give you a 404 error, like 'http://www.google.com'. If it works and you get the alert message, then the only problem is that your localhost:8080 url is a bad url.
Also, in your myFunction callback function, javascript treats line-breaks as the end of a line of code. So you must write assignments that use an '=' sign on the same line with no line-breaks. Due to this javascrit principle, you also don't need a semicolon ';' at the end of a single line like you would in PHP script.
Finally, a big cause of errors can be the JSON.parse() call. The data received MUST be a valid json string. So if the URL you call returns anything other than pure json... your myFunction() callback function will break on the JSON.parse() command.
Lastly, if there is an error in your myFunction() callback function, your browser inspector will not report it in a useful way and will instead throw an error that points to your xmlhttp.onreadystatechange=function(){} as being the culprit because that is where the browser thinks the error resides (being the calling function), even though the real error is in your myFunction() callback function. Using my edit of your ajaxCall(){...} code and with a valid url, you can be positive that the ajax call works and any errors you have are in your myFunction() callback function.
Lastly again, You have to be careful in your callback function because there are so many things that could break it. For example, document.getElementById() will cause an error if no html element exists on your web-page with the id you provided. Also, if the JSON you received back from the ajax call is missing any properties you mentioned like (city or latitude) it is likely that the innerHTML will be set to 'undefined'. But some browsers may treat the missing json properties as an error instead of just saying they are 'undefined' when you try to call them.
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://www.google.com";
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here')
/*
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML = obj.city
document.getElementById("demodes").innerHTML = obj.description
document.getElementById("latlon").innerHTML = obj.latitude + "," + obj.longitude
*/
}

Write line to text file with AJAX XMLHttpRequest

Here is my javascript function that reads from the file every second and outputs it:
var timer;
var url = "http://.../testdata.txt";
function ajaxcall() {
var lines;
var alltext;
request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState === 4) { // document is ready to parse.
if (request.status === 200) { // file is found
allText = request.responseText;
lines = request.responseText.split("\n");
document.getElementById("test").innerHTML = "";
for (i in lines) {
document.getElementById("test").innerHTML += lines[i] + "<br>";
}
}
}
}
request.send();
}
timer = setInterval(ajaxcall, 1000);
I haven't got the hang of AJAX yet so I tried to make a similar way to write into the file using what I read on the internet:
function chat() {
request = new XMLHttpRequest();
request.open("POST", url, true);
request.send("\n" + document.getElementById("chatbox").value);
}
However that does absolutely nothing and I don't understand why. The element "chatbox" is input type textbox and chat() is called by input type submit.
You cannot write to a file using just a POST call. In fact, you cant write to a file using only JavaScript/AJAX. You will need a server-side script in for example PHP that will write to the file for you, and then you need to call this script using AJAX.

Categories