AJAX success callback - issues executing javascript - 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.

Related

AJAX Code Ignored #Irrelevant

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?

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.

How to change external script url onclick?

I have been struggling to find a solution for my issue. I'm not that of a experience person with javascript, but I am looking for a way to slighty change the external js url depending on an onclick event on an ahref.
Right now I have this in my head tags:
<script type="text/javascript" src="http://www.domain.com/loader.php?GID=126&go=&sid="></script>
I want the SID parameter to be set to 1 or 2 based on an onclick on an anchor tag. The loader is called with this piece of code, but the SID would have to change right before the loader is being called.
<a href="/#download" onclick="javascript:Load_126(); return false;">
Is there anyone that could tell me if it's possible? And maybe point me towards the right direction?
Regards,
Sedoc94
EDIT 1: I have been pointed in a direction and figured I could get this done with jQuery.getScript() But still have no clue how I should utilize it for my case.
EDIT 2: As the script need to be pulled from an external domain, I will have to go with the $.ajax() function.
Right now I have:
function loadGame(sid){
$.ajax({
url: 'http://www.domain.com/loader.php?GID=126&go=&sid='+sid,
dataType: "script",
crossDomain: true,
success: gLoad_12603()
});
}
With an ahref onclick I'm calling the loadGame function, but the console says: Uncaught ReferenceError: gLoad_12603 is not defined. It should be working. But I'm guessing that it somehow gives this error because the function only exists in the script code that is returned from the external URL.
Any ideas how I can make it work?
You need to provide a success callback that will be executed when the AJAX request completes. Right now you are actually saying gLoad_12603() with parathesis and executing the function BEFORE the AJAX request is even initiated. You can't just remove the parathesis because jQuery might try to obtain a reference to the gLoad_12603 function before the AJAX request is actually initiated as well. So you have to wrap your call to gLoad_12603() in a function to ensure everything works out:
function loadGame(sid){
$.ajax({
url: 'http://www.domain.com/loader.php?GID=126&go=&sid='+sid,
dataType: "script",
crossDomain: true,
success: function() {
gLoad_12603();
}
});
}
jQuery.getScript()
function loadScript(sid) {
$.getScript("http://www.domain.com/loader.php?GID=126&go=&sid="+sid, function(script, textStatus, jqxhr) {
//code you want to be executed after the script is loaded inside the page
//you can delete this callback if you don't need it
});
}
And use it this way, changing the sid on each anchor to have different scripts loaded:
<a href="/#download" onclick="javascript:loadScript(126); return false;">
<a href="/#download" onclick="javascript:loadScript(127); return false;">
Try removing the parenthesis "()" in "success: gLoad_12603()".

How do you load a Javascript file inside of the success function for $.ajax()?

I am using jQuery's $.ajax() to get some data. I'd like to include that data in a popover dialog. I'm using the Twitter Bootstrap popovers.
It's not working; I believe the problem is that the JS for the popovers gets loaded before the data arrives.
How do I do something like:
<script src="{{ STATIC_URL }}js/bootstrap-popover.js"></script>
inside of my $.ajax() success function?
var request = $.ajax({
url: requestUrl,
dataType: "jsonp",
success: function(data) {
...
}
you can use jQuery's $.getScript method:
success: function(data) {
$.getScript("myurl/js/bootstrap-popover.js");
}
In trying to offer you a better solution, your tentative conclusion doesn't make sense to me. You should be able to include the popover javascript long before your ajax call and then use code to actually invoke the popover or configure it on any newly added content in your success handler.
There is no reason I'm aware of to load the popover js inside the success handler. Load it beforehand (in the normal way you load your other scripts) and then use it in the success handler for your ajax call. To help with how you'd use the popover script, we'd need to know more about what you're trying to do with it.

Difference between $("#id").load and $.ajax?

Does anyone know what is the difference between $("#id").load and $.ajax?
Let me clarify things for you a little bit :
$.ajax() is the basic and low-level ajax function jQuery provides which means you can do what ever you want to like you can work with XmlHttpRequest object. But once upon a time jQuery Developers thought that actually besides $.ajax(), they could provide more specific methods to developers so they wouldn't need to pass more parameters to make $.ajax() method work the way they want. For example they said instead of passing json as a parameter to $.ajax() to indicate return data type, they provided $.getJSON() so we would all know that the return type we expected was json, or instead of indicating send method as post or get, you could use $.post() or $.get() respectively.
So load() is the same thing, it can help you inject html data into your html. with load() method you know that an html portion is being expected.
Isn't that cool ?
I think I've been fallen in love.
For more information, you can visit jquery.com, they are even providing their new library and api tutorial page.
Edit :
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
is the same as below :
$.post("some.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Now as you can see it is the simplified version of $.ajax(), to make post call, you need to pass some information of send method type which is post as shown at the first example but instead of doing this you can use $.post() because you know what you are doing is post so this version is more simplified and easy to work on.
But don't forget something. Except for load(), all other ajax methods return XHR (XmlHttpRequest instance) so you can treat them as if you were working with XmlHttpRequest, actually you are working with it tho :) and but load() returns jQuery which means :
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
in the example above, you can easly inject the return html into #objectID element. Isn't it cool ? If it wasn't returning jQuery, you should have been working with callback function where you probably get the result out of like data object and inject it manually into the html element you want. So it would be hassle but with $.load() method, it is really simplified in jQuery.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});
You can even post parameters, so according to those parameters you can do some work at server-side and send html portion back to the client and your cute jQuery code takes it and inject it into #feeds html element in the example right above.
load() initiates an Ajax request to retrieve HTML that, when returned, is set to the given selector.
All the jQuery Ajax functions are simply wrappers for $.ajax() so:
$("#id").load(...);
is probably equivalent to:
$.ajax({
url: "...",
dataType: "html",
success: function(data) {
$("#id").html(data);
}
});
A more concise summary and the most important difference is that $.ajax allows you to set content-type and datatype.
These two are important for making JSON requests, or XML requests. ASP.NET is more fussy with a missing content-type field (atleast when you use [WebMethod]) and will simply return the HTML of the page instead of JSON.
$.load() is intended to simply return straight HTML. $.ajax also gives you
caching
error handling
filtering of data
password
plus others.
From the documentation ...
$(selector).load(..)
Load HTML from a remote file and inject it into the DOM.
$.ajax(...)
Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation.
load is specifically for fetching (via GET unless parameters are provided, then POST is used) an HTML page and directly inserting it into the selected nodes (those selected by the $(selector) portion of $(selector).load(...).
$.ajax(...) is a more general method that allows you to make GET and POST requests, and does nothing specific with the response.
I encourage you to read the documentation.
Here's the source code for the load function: http://github.com/jquery/jquery/blob/master/src/ajax.js#L15
As you can see, it's a $ajax with some options handling. In other words, a convenience method.
The above answer may not be valid anymore in light of the use of deferred and promise objects. I believe that with .ajax you can use .when but you cannot do so with .load. In short, I believe that .ajax is more powerful than .load. For example:
some_promise = $.ajax({....});
.when(some_promise).done(function(){.... });
You get more granular control over the html loading. There is also .fail and .always for failure and "no matter what" cases. You don't get this in load. Hope I am correct on this.

Categories