Using ajax to read text data from an outside source - javascript

So I am working on something that would allow me to read JSON data from an outside server, and print it out in a more human-readable format. So far I have this:
var address = "example.com";
//not the actual site
$.ajax({
url: address,
dataType: "JSONP",
success: function(data)
{
var obj = JSON.parse(data);
//Misc printing code goes here
},
error: alert("Error")
});
However, I am consistently receiving the error alert.
The console tells me "Unexpected token &". Looking at a few other sources, the issue seems to be that the actual data present on the site is nothing more than raw text.
I changed the dataType field to "text" to try and fix this, but the console error instead changed to tell me that I wasn't allowed access.
I tried retrieving the data and treating it as text with "JSONP text", but it simply returned to the previous "Unexpected token &" error.
Is there any way I can receive text data from an outside server? If not, is there some workaround I could use, such as saving the data to a document and importing it into my code from there?

Related

defect in dojo/request/iframe for reading xml response

I am using dojo/request/iframe to do file upload. The file is uploaded fine, but when I am trying to get the response in XML, I always get this error (I tried in FF):
"TypeError: xmlText is undefined"
I have set the handleAs property to "xml" and based on the documentation of dojo/request/iframe, for responses in xml and html I don't need the response to be inside tag. I used Firebug and I can see that my response is in xml format.
I have read a post about the possibility of this become a defect from dojo library, but there's no follow up on this: http://grokbase.com/p/dojo/dojo-checkins/12c7qyynnx/dojo-toolkit-16440-dojo-request-iframe-js-xmltext-is-undefined-error-in-ff-and-ie9
Does anybody know if this is actually a defect from Dojo? and is there any workaround? Thanks in advance
I had a similar problem. But maybe it's misleading: The response, your xmlText is no Text, but an object. For me something like
iframe(myForm.action, {
handleAs: "html",
data: data
}).then(function(xmldoc){
require(["dojo/dom-construct"],function(domConst){
var new_elem = query("#"+myid,xmldoc)[0];
if(new_elem)
domConst.place(new_elem, elem, "replace");
});
}, function(err){
// Handle the error condition
});
did work fine.

How to get contents of URL into a string variable using JavaScript

I'm trying to get the JSON from this URL into variable
This bit of code successfully puts it in a div element
$("#siteloader").html('<object data="MYURL">');
But I want the contents of that div inside a string variable rather than in the div.
I've also tried the following:
$.ajax({
type : "GET",
dataType : "jsonp",
url : "MYURL", // ?callback=?
success: function(data){
// do stuff with data
}
});
But this shows a syntax error "Uncaught SyntaxError: Unexpected token : " "getfixes:1" in the javascript console when I try it in chrome.
Is it possible for me to just get the contents of a URL as a string in the data variable?
there is a external library according to this post: String URL to json object
http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

Bad formatting in JSON ajax response

I am having some odd problems with data coming back from a jquery Ajax call that I cannot figure out.
I have a c# asp.net web page that binds a valid JSON data blob to the UI with client side JavaScript on page load. This part works just fine. I set up a jquery Ajax post back that returns the same data and calls the same JavaScript data binding method, and this throws an error when I attempt to bind the data. It looks like the JSON written to the page on load is properly treated as a JSON object, but the data returned by the ajax call isn't.
Here is the ajax call:
jQuery.ajax({
type: 'POST',
data: "{'move_list': '1-2,3-2'}",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
url: 'Puzzle.aspx/ProcessMove',
complete: OnComplete,
success: function(data){BindData(data);},
error: OnError
});
Here is a sample of the JSON data that is being processed:
{"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]}
Here is the code that loads the data when the page is first loaded:
<script type="text/javascript">
// method returns JSON object above.
// client side code appears like this:
// BindData({"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]});
BindData(<%=Game.SerializeToJson()%>);
</script>
and finally, the JavaScript binding function:
function BindData(data)
{
try
{
document.getElementById("square1").className = data.game[0].color;
// much more of the same....
}
catch(exception)
{
alert(exception.message);
// error thrown here is 'data.game is undefined'.
// the data object is being treated like a string and not a JSON object.
// so the indexing into the object fails.
}
}
I have double checked the JSON data with several online JSON parsers, and the data is formatted correctly. The server side code generates the same output in either case.
I tried to change the jquery Ajax call to...
success: function(data){BindData(JSON.parse(data));},
...to see if it was just treating the returned data as a string as opposed to a JSON object, but that just generates this message:
SyntaxError: JSON.parse: unexpected character
BindData(JSON.parse(data));
Completely stumped by this one. I have been reading everything I can find and trying all sorts of things, but nothing seems to work.

jQuery.get() method doesn't work

I'm trying to perform a xquery and get its result, with the following code:
$.get('http://localhost:8984/rest/lod?query=/*:teiCorpus//*:TEI',
function(data) {
alert(data);
});
I was expecting a xml response, but so far I don't get a thing.
Firebug display the following error:
XML Parsing Error: no element found Location: moz-nullprincipal:{a9dddfb7-5488-424b-8ab1-76913e889282} Line Number 1, Column 1: ^
I don't understand what I'm doing wrong.
Any ideas?
EDIT:
When I place:
http://localhost:8984/rest/lod?query=/*:teiCorpus//*:TEI
in my address bar, I get
<TEI xmlns="http://www.tei-c.org/ns/1.0" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:svg="http://www.w3.org/2000/svg">
<teiHeader type="text" xml:id="Fr1">teiHeader</teiHeader>
<text>teiText</text>
</TEI>
and that's exactly what I need to retrieve with the get.
It looks like your URL has some illegal characters, try this
$.get('http://localhost:8984/rest/lod',{ query: '/*:teiCorpus//*:TEI' },
function(data) {
alert(data);
});
putting it in as the data parameter will hopefully escape the illegal characters
EDIT:
Looking into your problem more - there could be 2 more things it could be:
1 ) Your trying to do a cross domain request - this is not allowed with XML (you can determine this by looking at the URL in your browser, if it's not the same as http://localhost:8984 its cross-domain)
2 ) Your xml response you are returning is incorrect

JSON.parse causes Chrome tab to crash ("Aw, Snap") despite use of try/catch

I'm loading some JSON data from an AJAX query:
$.ajax({'url': url, type: params.method, 'data': data, timeout: this.settings.timeout, success: function(d,a,x){
console.log('request Complete',params.endpoint,params.params);
var json = null;
try {
json = JSON.parse(d);
} catch(e) {
console.error(e);
}
console.log('json');
// omitted for brevity...
}
});
I'm seeing occasional "Aw, Snap" crashes in chrome where the last console.log is the "request Complete" (the error or 2nd log never get shown).
I suppose that it's important to note that the data may be large (sometimes as big as ~15Mb), which is why I'm not printing out d on every request and looking for malformed JSON (yet... I may result to that). FWIW, I've also tried $.parseJSON instead of JSON.parse
Research I've done into the "Aw, Snap" error is vague, at best. My best guess atm is that this is an OOM. Unfortunately, there's not much I can do to decrease the footprint of the result-set.
Is there any way I could, at the least, gracefully fail?
What happens when you tell jQuery the response data is JSON via the dataType property? Doing so should cause jQuery to pre parse and just give you the data. If you're right about what is going on, it seems this might cause a crash too. jQuery does some sanity checks before parsing, though.
$.ajax({
url: url,
type: params.method,
data: data,
dataType: 'json',
timeout: this.settings.timeout,
success: function (d, a, x){
// `d` should already be parsed into an object or array, and ready to use
}
});
If that doesn't help, please post your actual JSON response for us to take a look at.
"#the system" nailed it. 15MB of info coming back is too much for your browser to handle. I tripped upon this trying to see why my 64 Byte encoded image string is crashing the chrome tab, and it's only 200-500KB.
To 'gracefully fail', it seems you will need to have server side logic in place to prevent this from happening; perhaps limit the size of the JSON string. Only have X characters of length in the initial JSON string and add a property for 'isFinishedSending: false' or 'leftOff: [index/some marker]' so you can timeout for a bit and hit your server again with the the place you left off.

Categories

Resources