Will these ajax calls delay page elements further down? - javascript

I am using this pseudocode to retrieve some json files and put their content into the content div.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Test</title>
</head>
<body>
<div id="content"></div>
<script type="text/javascript" charset="utf-8">
var my_files = ['http://example.com/file.json', 'http://example.com/file2.json'];
var params = {
format: 'json'
};
function _populate_content(arg){jQuery("#content").text(arg)}
jQuery(my_files.each(function() {
jQuery.ajax({
url: url,
dataType: 'jsonp',
data: params,
jsonpCallback: "_populate_content",
});
});
</script>
<div id="more_content"></div>
</body>
</html>
It might take some time to retrieve the remote files. My question is: Will this code delay the loading and rendering of the "more_content"-div?
Would it be better to enclose the ajax retrieval in a $(document).ready() block?

Will this code delay the loading and rendering of the "more_content"-div?
No, because the Ajax call is asynchronous (not blocking).
Would it be better to enclose the ajax retrieval in a $(document).ready() block?
Yes. This will execute the Ajax call once the whole DOM is rendered.
While it might work without, you cannot be 100% sure that element with ID content is available when the Ajax call returns. As #BiAiB pointed out, the element will be available. It is still good practice though.
Btw, if you want your code to work in all browsers, you should use jQuery's each and not the built-in one:
jQuery.each(my_files, function() {
jQuery.ajax({
url: url,
dataType: 'jsonp',
data: params,
jsonpCallback: "_populate_content",
});
});
Maybe this is only a stripped down example, but does it make sense to load both URLs? The second call will override the results of the first one...

Short answer: no. Since you haven't defined 'async:false' in the .ajax() parameters, the javascript will execute asynchronously. This means that your my_files array will loop through and fire off asynchronous calls then continue on loading the page.
You may want to wrap your logic in $(document).ready(), but before doing that place a throbber in your more_content div to let the user know information is coming shortly.

ajax calls are made asynchronous (unless you specify otherwise). So it won't delay your page loading.

the ajax call is asynchronus, so no delay.
if you put it into a document ready block,
you enshure that the browser did render the whole page before doing the call ..

Yes. The browser will block while those calls are made. You should instead do the work on page load so that the page is visible/rendered while the work is being done:
$(document).ready(function() {
jQuery(my_files.each(function() {
// etc...
}));
});

Related

How to trigger the event manually once the ajax content's script is executed completely?

I am loading a html page with script section(render the JQuery UI) via AJAX. This html page contains more number widgets. In success function of Ajax, I am accessing the UI controls by its JQuery UI class names, but none of the class names are added i.e., script is not executed. If I access the same after 100ms using setTimeOut its working.
Please refer the below code:
var self = this;
$.ajax({
url: url,
dataType: "html",
cache: true,
success: function (str,sta,xhr) {
$("#samplefile").html(str);
setTimeout(function() {
self.reg($("#samplefile .ui-widgetui"));
},100);
}
});
Its working fine but I want to access this without settime out. Can anyone please suggest on this?
It sounds perhaps that you are trying to access the DOM before everything is initialized. Have you tried wrapping the initialization of you ajax request in a jQuery $(document).ready() call? This makes sure that your DOM is in a initialized state before getting triggered.
https://learn.jquery.com/using-jquery-core/document-ready/

PHP Ajax load file with jQuery inside file

I am loading a PHP file using Ajax below which works great except I want to be able to load some javascrip/jQuery items within that file to function on the main index page.
prices();
function prices()
{
$.ajax({
type: "GET",
url: "inc/load_prices.php",
cache: false,
success: function(response){
$("#prices").hide().html(response).fadeIn(500);
}
});
}
setInterval(prices, 600000);
Inside load_prices.php I have some stock ticker type output which works fine outside the AJAX call using the below. However when loading the contact via AJAX it wont trigger the webticker.min.js file and wont render properly.
<!-- If loading this without AJAX the ticker works fine -->
<script src="js/jquery.webticker.min.js"></script>
<script>
$("#ticker").webTicker({
duplicate:true,
hoverpause:false,
});
</script>
How do I allow the contents of the prices() AJAX function to render properly when needed to reference jQuery?
Not sure but in load_prices.php
src="../js/jquery.webticker.min.js"
as both are in different directory
If interpret Question correctly, use $.getScript() to load webticker.min.js once. Not certain what purpose is of calling .webTicker() every 600000 ms?
$.getScript("js/jquery.webticker.min.js")
.then(function() {
$("#ticker")
.webTicker({
duplicate:true,
hoverpause:false
});
});

JQuery dynamic Script-Tag and the Execution

The goal is to load script-Tags per ajax, execute the scripts and show the content of the script-tag (a iframe with a video).
The scenario:
The scenario is a video page. If i click on "video-text" the id in the dom will be determined. After that an ajax-php-request will be executed with the determined id. This request will responese with a script tag. And this is the problem: How can i get the iframe?
Have anyone a tip for me?
ajax-call:
$.ajax({
type: "GET",
url: "/get-embed-by-id/"+$(this).find('.views-field-nid .field-content').html(),
success: postToPageTwo,
error : postToPageTwo,
datataype: "html",
});
This call returns a script like this one
<script type="text/javascript" src="http://exampleurl.de/video/7"></script>
The content of this script is for example:
(function(){
document.write('<iframe id="video_11" class="mediacube_video"
src="http://exampleurl.de/video/11.html?" scrolling="no"
align="center" frameborder="0" framespacing="0" width="725" height="409">
</iframe>');
})()
EDIT
the code to use with $.getScript:
$.getScript("http://exampleurl.de/video/5", scriptResponse);
and the code of scriptResponse:
function scriptResponse(data) {
console.log("data:");
console.log(data);
}
but the data is always undefined. or did i anything wrong?
jQuery has .getScript() to load and execute scripts for you. no need to call an ajax to return an html to load another script (that's a lot of round trips) just to call a script.
$.getScript('http://exampleurl.de/video/7');
if the initial request really matters (maybe some parsing on the back-end to determine the link of the script), you can have the initial response return just the url of the script. then use that returned string for the .getScript()
$.get('initial_url',function(returned_url){
$.getScript(returned_url);
});
but still, too many round trips.

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

Javascript doesn't load after AJAX call

Ok the following HTML code is parsed when I load a page:
<div id="clip-wrapper">
<script type="text/javascript">
alert("bla");
</script>
</div>
This obviously leads to an alert saying "bla", after my AJAX call, the parsed HTML code looks like this:
<div id="clip-wrapper">
<script type="text/javascript">
alert("ajaxbla");
</script>
</div>
This on the other hand, doesn't result in an alert. Why? And how do I fix this?
If there are any scripts loaded into your dom from an Ajax call, they will not be executed for security reasons.
To get the script to execute, you'll need to strip it out of the response, and run it through eval
Ideally though, you'll want to run your script as a callback for when your ajax request completes. If you're using jQuery, this would be the success event of your ajax call, and if you're doing it natively, it would be the readyStateChange event of your xhr object.
EDIT
If you really want to opt for the eval option, you could try something like this:
document.getElementById(contentDiv).innerHTML = xmlHttp.responseText;
eval(document.getElementById("clip-wrapper").innerHTML);
put you code in
$(document).ready(function()
{
alert(msg);
});
or make use of readysatchange event of XMLHttp object.
XMLHttpobject.readyStateChange( furnction() { alert('msg'); } );
Edit
if you are using jquery than go for
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
here in sucess event you can write your code which get executed once you are done with the ajax.
any code inside body in between script tag will executed only while loading the document.
in ajax call,make use of callback or success: or oncomplete: to handle the ajax response if you are using jQuery.
You mean the second html code is coming as an ajax response?? Did you even inserted the html to the current page?
Something like,
document.body.innerHTML = ajax_response;
But even with innerHTML replacement I don't thing the script inside it will be auto executed. The browser will parse the script but won't auto execute it. (For eg, if you have a function definition in the html, after the ajax call you will be able to call those functions)
Another option is to use document.write, it will replace the whole page content with the new html and the script tags in it will be auto executed.
document.write(ajax_response);
Hope this helps,

Categories