AJAX Code Ignored #Irrelevant - javascript

When attempting to use the following code:
<script src="lib/jquery-2.0.3.js"></script>
<script>
function readXML()
{
$(document).ready(function(){
$.ajax({
url: "myXML.xml",
type: "GET",
dataType: "xml",
success: function(xml){
alert(xml);
}
});
});
}
</script>
for some reason the code is ignored entirely. When I used the alert() before $.ajax it worked, but for some reason the entire AJAX code within is ignored. Other types of jQuery codes don't work, either. The rest of the code works perfectly fine - everything that has nothing to do with AJAX or jQuery. What am I doing wrong?
Also, when I try adding "complete" or "error" the entire page wouldn't load. When I replace success with done/error I get the exact same result - the code is ignored entirely. I know I'm doing something wrong, but having tried an awful lot of codes from here, I have no idea what else to do. Help?
UPDATE:
error finally did work and got me this result:
"NetworkError: failed to execute send on XMLHttpRequest: failed to load file myXML.xml"
However, I read that's the only way to import xml without loading everything to a server here: Using XML in HTML page without using a server
What am I missing?

Related

JQuery - Random "XML Parsing Error: mismatched tag"

I have the following (jquery) javascript:
$.ajax({
type: "GET",
url: "%URL HERE%",
dataType: "xml",
async: false,
success: function(xml) {
console.log(xml);
var root = $(xml).find("root");
var child = root.find("child");
console.log(child);
},
error: function(){
console.log("error encountered while fetching xml");
}
});
Which fetches the following XML file:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child id="test1">Content</child>
</root>
Which does do what it should do, except a little bit after successfully executing the code and logging the correct data, the following error pops up in the console:
XML Parsing Error: mismatched tag. Expected: </input>.
Location:
Line Number 1, Column 15:
I am utterly confused as to what causes this error. The actual script runs successfully and nowhere in my files there's an <input> (or <input />).
After isolating, this is the only javascript left in the file (together with the link to a jquery cdn) so it's also not the case of another piece of code throwing this instead.
It doesn't seem to interrupt code at all either, it's just this random error popping up each time a bit after having done the ajax call - in particular after having done the $(xml).find("root"). If I comment this out, the ajax request happens but the error doesn't pop up - but well my code obviously doesn't work either then!
I hope anyone can give me some insight as to why this error pops up as I've been staring at this for many hours now and I only seem to understand it less and less...
The error stopped showing up after using a newer version of jQuery. I was somehow using jQuery 1.10.1 before, now 3.3.1 and that got rid of the error.

Strange ajax behavior with Zepto and Cordova

Something strange is going on with an Ajax call I'm making and I can't figure out why its happening, maybe someone can shed some light.
This is the call
$.ajax({type:'POST', url: apiURL+"misc/"+cola, headers: {'apikey':localStorage.apiKey}, dataType: 'html', success:function(data) {
$("#pagina").html(data);
postCarga("pagina");
}, error: function() {
sinConexion();
}});
Now, this should take the "data" received from Ajax and fill div#pagina with it, but the div stays empty.
Here's the strange part, I called console.log(data) to see if the data is getting through and then it not only logs to the console but properly fills in the div#pagina with the returned data.
If I just try to fill it in directly, the div stays empty, but if I do anything beforehand (even something like var xxx = data;), it gets filled in correctly.
I worked around it by moving the filler function into postCarga so my final code looks like this:
$.ajax({type:'POST', url: apiURL+"misc/"+cola, headers: {'apikey':localStorage.apiKey}, dataType: 'html', success:function(data) {
postCarga(data,"pagina");
}, error: function() {
sinConexion();
}});
,but that feels strange.
// EDIT //
Here's the whole function
function postCarga(datos,que) {
$("#"+que).html(datos).animate({top:'0%'},350,'ease-in',function() { $("#cargando").css("display","none"); });
}
,originally, all it did was animate and then hide the loader, the html(datos) is part of my fix.
Ok, I just found the reason. I was testing out different things by side-stepping the received data and just trying $("#pagina").html("Hello") and other things, after all of those worked I went trough the html returned by the Ajax call and that's where I found the answer.
I changed the return from the API to send just
<h1>Hello</h1>
and it worked fine, afterwards I manually built up the whole HTML string until I had a carbon copy of what the script generated, sometimes it would load and sometimes not, which was stranger still.
I passed the returned HTML through various lints and checkers and only one of them returned an error, one of the images in the block returned a 404, so I removed that image (and only that image) from the returned HTML and it loaded fine.
In essence, it seems that when Ajax is set to html (dataType: 'html'), each and every thing - direct or remote - in the entire block must be valid html and return a success when called, or it will be silently ignored.
Changing dataType to "text" makes it skip that check and just inject everything into the div as intended.

How to create an ajax request within google scripts with '$' variable error?

I'd like to use the ajax() method to perform an AJAX Request. I've tried to create the below functions within scripts.google.com, but I get the following error:
function AjaxCall() {
var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'https://worker-aws-us-east-1.iron.io/2/projects/',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
}
Error:
ReferenceError: "$" is not defined. (line 5, file "Code")
Is there a way to get around this issue?
It appears that jquery isn't sourced in your HTML. Keep in mind that jquery is a client side, javascript library -- so the browser needs to load the jquery javascript file. In other words, a valid reference needs to be in the HTML that is returned to the client browser.
Your comment indicated that you tried:
<script src="code.jquery.com/jquery-2.1.1.min.js"></script>
Try updating that to:
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
If you don't include the "http://" (or "https://" or "//") in the front of the URL, the browser thinks it's a relative path and will try to load that from the current directory (and that probably isn't what you were trying to do). So, if the page that you were viewing was
http://www.examplesite.com/example.html
Then, the script tag you showed in your comment would try to load jquery from
http://www.examplesite.com/code.jquery.com/jquery-2.1.1.min.js
This is likely returning a 404 error -- check your javascript console to see if it's receiving an error when trying to load the jquery script.
Also, in most cases, it's recommended that you put the script tag at the bottom (right before the closing body tag). This keeps the page rendering from being blocked as the browser download the js file. This is not likely causing the problems you were originally seeing -- just thought I'd mention it since your comment potentially indicated that you were loading it right before the ajax call.

problem CasperJS POST via AJAX not working

I'm working on a scraper of my bank statements with CasperJS, so far I've managed to login and get to the statements page. I accomplished to get the table with the first page of the statement, but I need to get it complete.
The bank's web have the option to export to a .txt file (sort of a CSV actually), but in order to download it I have to be able to download the file that comes as an attachment in the response header of a POST request when I submit a form by clicking a button.
So I figured that I could do the POST via AJAX, get the response and output it. I tried running the code on the firebug console and it works, but for some reason it just doesn't work in CasperJS.
Btw, I have tried using --web-security=no , still doesn't work
This is how I'm trying to do it:
this.then(function() {
eurl = "http://bankurl.com";
response = this.evaluate(function() {
params = $("#lForm").serialize();
$.ajax({
type: "POST",
url: eurl,
data: params,
success: function (data) {
return data.responseText;
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
I wasn't able to test this with the code you provided, but it looks as though you just aren't returning anything back from the evaluate().
return __utils__.sendAJAX(url, 'POST', params);
You would probably also need to call CasperJS with the following:
casperjs --ignore-ssl-errors=true /path/to/script.js
Well, after struggling finding a way to solve this I finally did, I just put the ajax call inside a try catch and found that the error was that it wasn't reading the eurl variable (I declared it outside the evaluate). I put it inside and it worked. Thanks for your help

AJAX success callback - issues executing javascript

When using AJAX to trigger a python handler (in GAE) upon load, it correctly loads the HTML template page, but for some reason it does not execute the Javascript that is in the template page. It also does not return that javascript in the success callback function.
This is the code from the index.html file that is triggering the handler upon load:
<div id="daily_emails"></div>
<script>
$.ajax({
url: "/gviz",
cache: false,
success: function(data){
$("#daily_emails").html(data);
}
});
</script>
The gviz handler generates a html template that has a custom Google Chart Tools table in it. It creates it without any problem on its own, but once I call it from another html file (like above), it strips the javascript content and as a result returns the plain, unaltered, html. As the javascript code itself uses template tags (for the data in the Google Chart Tool), I can't just run it from the above index.html file.
If it would help, I could post the full code of the template that is being rendered by the gviz handler.
You need to make sure your calls are made when the page is ready
<script>
$(document).ready(function() {
$.ajax({
url: "/gviz",
cache: false,
success: function(data){
$("#daily_emails").html(data);
}
});
});
</script>
Which browser are you using? Browsers will parse the returned HTML, and may strip out illegal HTML. This might happen if there's an error in the returned HTML. It'll be helpful if you include the results of '/gviz'.
Since it sounds like you're returning a template that may not contain purely valid HTML, you may need to return the results with the content-type set to 'text/plain' so the browser doesn't attempt to parse it.

Categories