jQuery.get() method doesn't work - javascript

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

Related

How do I pass a string to an Ajax GET request as a query param without the string getting encoded?

I am trying to pass a list of subject id's as a query param in an Ajax get-request, so that it only returns data pertaining to the subject id's I passed in. The API is set up to receive a subjectId param as a single number, or string of numbers separated by commas. I have made sure that what I am sending is exactly that -- "13,14,15" -- but when I make the request, the get URL encodes the string so that it looks like this: 13%2C14%2C15%2C.
The URL I want to generate is (I'm just using placeholders for the domain name and session token) https://get-url.com/get-filter-counts?sessionToken=abcdefg&subjectId=13,14,15. When I test this out in the browser, it works.
The URL I'm actually generating is https://get-url.com/get-filter-counts?sessionToken=abcdefg&subjectId=13%2C14%2C15%2C
I've tried researching this issue but I'm not even sure what it is that's happening there. I've looked at a ton of examples of passing strings as query params in an Ajax request, and as far as I can tell I'm doing it correctly. I've hard-coded a string into the params below just to demonstrate:
$.ajax({
type: "GET",
url: getURL,
dataType: "JSON",
data: {
sessionToken: sessionToken,
subjectId: "13,14,15"
},
//process the returned result of the Ajax call
success: (ajaxResult) => {
console.log("subject id list:", subjectId);
console.log("Ajax result:", ajaxResult);
},
In the success method, the console returns the correct subjectId list as well as the data pertaining to those subject id's. But I am unable to get the results in the browser because of this URL issue.
How can I remove the encoding (if that's what's happening?) from the string in the url? Thanks.
The issue is with using commas in-between numbers. The string you are sending from the frontend is getting encoded and hence the URL you see. If you try encodeURIComponent(13,14,15) you'll see the same response.
The solution would be using something other than commas and handling that on the backend or simply sending an array.
Well, I was sending the string of numbers with a trailing comma at the end (I didn't think that would be an issue), and it turns out that's why the server wasn't properly handling the encoded URL. Just sharing in case this is useful for anyone else who looks at this question.
The comment from #Quentin was essentially correct, except the issue was in fact a frontend typo.

Using ajax to read text data from an outside source

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?

$.getjson not working / json storage

I'm trying to do a getJSON call to a page within my domain that is simply a json array, which is not returning anything given the script in my webpage:
<script>
$('#genButton').click(function() {
console.log("click");
$.getJSON("http://mygithub.github.io/repository/quotedb.json", function(data){
console.log("executing");
var entry = data[Math.floor(Math.random()*data.length)];
console.log(entry);
$("#quoteDisplay").text(entry);
}).fail(function() {
console.log( "error" );
});
})
</script>
When the button is clicked, the console logs the "click", but never logs "executing", but also doesn't log any errors related to the getJSON. The debugger also never pauses within the getJSON function.
My question is, 1. Is it valid for quotedb.json to be literally a webpage with just a single json array? Or does the page need to be annotated in some way so that the getJSON request knows where to pick up the json from? 2. If (1) is fine, then are there any other reasons you can see why nothing from the getJSON return function would appear?
The json is again one array of json objects, in the form:
{
"character": ""
"quote": ""
}
EDITS
With the edited code, it now outputs "click" followed by "error" from the .fail() method of the $.getJSON call now.
I tried removing the ?callback? section of the url as suggested below, which did not work.
The /repository/ section of my url seems to be necessary to access the file.
Try without ?callback=? at end of url, see jQuery.getJSON()
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.

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.

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