Functions inside iframe execute before js libraries are loaded - javascript

I have an iframe that contains the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_container"></div>
<script>
$.ajax({
type: 'post',
dataType: 'json',
contentType: 'application/json',
url: 'some_url',
success: function(data, status, xhr) {
console.log(data.html); // <div><link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css' rel='stylesheet'><script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js'></script><script> $('.input-select2').select2();</script><select class='input-select2'></select></div>
$('#my_container').html(data.html);
},
});
</script>
As you see the script inside the iframe pulls a string of HTML/js from an external resource and appends it to #my_container. The pulled HTML/js is:
<div>
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css' rel='stylesheet'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js'></script>
<script>
$('.input-select2').select2();
</script>
<select class='input-select2'></select>
</div>
But when the appended scripts run, I get the following error:
Uncaught TypeError: $(...).select2 is not a function
So apparently the select2 function is executed before the library is loaded. If I move the select2.min.js library one level up to the jquery.min.js library everything works just fine. Or if I wrap my select2 function in setTimeout(function(){ ... }, 20); it also works.
So what can I do?

If I understood, it seems that your jquery snippet is executed before select2 was loaded.
Maybe can you dynamically load the select2 lib with an ajax call, to ensure the library loading.
$.ajax({
url: "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js",
dataType: "script",
success: function(){
$('.input-select2').select2();
}
});
As you say, you can also wrap your select2 initialization in a setTimeout() function. It's an unelegant known solution but it works.
See this post: Why is setTimeout(fn, 0) sometimes useful?

Related

Sample AJAX call not working

Trying to do a simple AJAX call (teaching myself). I have a .txt file in same folder as html. What am I doing wrong here? Thanks.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#poo").submit(function(e){
e.preventDefault(); //stop submit
$.ajax({
type: "GET",
url: "data.txt",
data: "",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
}
});
});
});
</script>
</head>
<body>
<form id="poo">
<input type="text"> </input>
<input type="submit"> </input>
</form>
<br>
<br>
<div style='display: none;'>
<p id="foo">this shows</p>
</div>
Start Over
</body>
</head>
</html>
This is a convenience function that loads remote files via AJAX and uses .innerHTML() to load it into any elements in your jQuery selector.
// Does the exact same thing as the entire block of code you wrote..
// These jQuery methods are chainable so you can do this in 1 statement.
$("#foo") // Contains the DOM reference,
// so no need to use getElementById().
.load("data.txt") // Loads "data.txt" into "#foo".
.show(); // Makes "#foo" visible.
Relevant:
jQuery selectors and method chaining
jQuery load() method
jQuery show() method.
Per your comments, you had some other issues.
You said you weren't sure if jQuery was loaded. jQuery is just javascript, so you include it in <script></script> tags. The easiest way is to use jQuery's CDN. Click on the link, then choose the version and format you want. There will be a pop-up containing the script tag, just copy it into the page, preferably before any other Javascript you have on the page. If you're not sure which version/format to use, v1.x, minified is the way to go.
You mentioned that you were running it locally. The problem is, Javascript isn't supposed to have direct access to your filesystem. It will attempt to request the file over the http protocol, without having server software you can only request files over the file:// protocol.
There are zillions of topics on this all over the internet, but to solve it you should install a server. XAMPP is a good one and it's cross platform. Download that and your application will work in all your browsers. It will work in your browsers when you upload it to a server as well
try to add the dataType: "text"
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
})

Load Javascript after AJAX-fetched HTML is fully loaded

I have a situation where the HTML part is loaded with AJAX into a DIV with ID="dynamic content" using main.js script. This script is situated inside the HEAD part of main.php and it goes like this:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
}
});
The Javascript file responsible for controlling that content is situated in another JS file named secondary.js. This file is placed just before the closing of BODY again inside main.php.
main.php Document Structure:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
....
<div id="dynamic-content"></div>
....
....
<script type="text/javascript" src="js/secondary.js"></script>
</body>
</html>
Sometimes the content of content.php is too large, and secondary.js file loads before the content is fully loaded. Hence some elements are not targeted and i have problems.
Is there a way for me to delay for 1-2 seconds the execution of secondary.js, just to make sure that the content is fully loaded?
ps: all above files are hosted on the same server
Thanks in advance.
What you're trying to achieve is async behaviour. Whatever secondary.js does, put it inside a function and call it inside the ajax callback. If you do so, you won't even need two JavaScript files.
Don't try to manage this by timeouts or loading order. This will not be failsafe. You cannot know the exact time the browser needs to load your content. For example, what if you are on very slow internet connection? Don't try to predict those things, that's what the callback is for :-)
Your code could look sth like this:
function doSthWithLoadedContent() {
// whatever secondary.js tries to do
}
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
doSthWithLoadedContent();
}
});
You could possibly load the script using $.getScript once the output has been applied to the html tag:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
$.getScript('js/secondary.js');
}
});
https://api.jquery.com/jquery.getscript/
The best way to do this would actually be to hand a callback to the function that does your ajax call. I probably wouldn't put this in html but it demonstrates the method:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
<script lang="javascript>
function doWhenLoaded(someCallback)
{
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
someCallback();
}
});
}
$(document).ready(function(){
doWhenLoaded(function(){
$.getScript('js/secondary.js');
});
})
</script>
</head>
...
</html>
Instead of using $.getScript you could also load in secondary.js with main.js and wrap it in a function call (i.e. doStuff = function() { /* your code here */ }). Then you could call doWhenLoaded(doStuff) in $(document).ready.
You have to add script after ajax call.
$.ajax({
url: 'url of ajax',
type: "POST",
data: data,
dataType: "html",
success: function (data) {
$('#instructions').html('<div>' + data + '</div>');
$.getScript("js/html5lightbox/html5lightbox.js", function() {
$('body').find('.html5lightbox').html5lightbox();
});
}
});

Call a php function in a javascript with params

I need to call a PHP function with params from JavaScript when I click on some text in a html file; yeah, I know, it sounds like $##!$##
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
$('#detailed').click(function(){
$('#main').load('parse.php?file=gz.xml', function() {
/// can add another function here
});
});
}); //// End of Wait till page is loaded
</script>
<a><div id="detailed">Stuff1</div></a>
<a><div id="detailed">Stuff2</div></a>
<div id="main">Hello - This is my main Div that will be reloaded using jQuery.</div>
What I want to make, is when I click Stuff1 on page, to call function parseLog('Stuff1'), and when I click Stuff2, to call function parseLog('Stuff2').
function parseLog(), is a PHP function, in functions.php
Anybody know a solution?
Thanks!
Javascript is client side script and PHP is server side script. So if you think, you need a call to that function over the network and get the response over the network. you should try using a coding method called AJAX. To make life easier and cross browser compatible use jQuery library and its ajax functionality.
Look at this post for a quick intro to jQuery and AJAX.
It helped me , hope this helps you too.
You should try something like this :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function myFunc (myData) {
$.ajax( {
type: "POST",
url: "parse.php?file=gz.xml",
dataType: 'json',
data: { param: myData},
success: function( result ) {
$("#main").append(result);
}
}
}
Stuff1</div>
Stuff2</div>
<div id="main"></div>

js .append html element do not have javascript lib

I'm trying to use $.ajax to get html string from php file and append to current html div. when i try to use php echo, everything works fine, but when i try to dynamically load using $.load or $.ajax, javascript library doesn't load or apply to the div.
included js libs in header:
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="MetroJs.lt.min.css">
<script src="MetroJs.lt.min.js" type="text/javascript"></script>
script file in header:
function getdatafromphp() {
$.ajax({
type: 'POST',
url: "autoload_process.php",
data: {group_no : track_load},
dataType: 'html',
async: true,
success: function(html) {
$("#results").append(html);
track_load++; //loaded group increment
loading = false;
}
})
}
html code in body:
<div id="results"></div><div class="animation_image" align="center"><img src="ajax-loader.gif"></div>
i put rest of css and js right after the div:
<link rel="stylesheet" type="text/css" href="index.css"/><script src="index.js" type="text/javascript"></script>
The html can be loaded into div, but it does not have any js effect to it (css is fine)
I suspect is because i use $(document).ready in both js scripts, but changing it does not help.
here is my test site: http://www.zsm.me/test/newindex/
Please help if you have any thoughts.
Thanks.
Try to bring in the data (html) into the specified div, then initialize the plugin for each of the elements inside the html.For ex:
success: function(html){
$("#mybutton").buttonset();
$("#dateofbirth").datepicker();
}
Today i find a new method by adding
<?php echo $script; ?>
in the header.
I have no idea why this works but it does...
well, hope this helps

jQuery client for REST webservice with jersey

I am new in jQuery and I'm trying to develop a client for my web service. I've tried something simple, just for testing, but still it doesn't work, although it seems ok to me.
I have the jQuery library in my tomee/webapp folder, along with my html and javascript files. If I write some non-jQuery code in my javascript file, it works.
I have the following code:
index.html
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="client.js"></script>
</head>
<body>
<input type="button" id="getAllButton" value="Get all books" onclick="return getAllBooks()"/>
<div id="messageBox"></div>
</body>
</html>
client.js
function getAllBooks() {
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
});
}
The problem is that no alert will appear. If a write pure javascript (I mean without jQuery), alerts will do appear.
Why do alerts not appear? Any advice?
Thank you!
Sorin
Lets try to find out what works and what not; try changing your client.js to:
alert(1);
function getAllBooks() {
alert(2);
window.open(rootURL + '/books');
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(3);
},
error: function (data) {
alert(4);
}
});
}
If you see the alert #1 (when your html page loads) then your client.js path is OK. If you see alert #2 (when you click the button) then at least the function is being called.
Verify if window.open() shows what your web service is supposed to show you (even a error message will guide you throw the right path). And of course, if you see alert #3 or #4 then your problem was mysteriously solved by it self.... it sometimes happens :-)
NOTE: If you know how to use the javascript console of your browser use console.log() instead of alert() for debugging;
Thanks charlietfl for your tips! They helped me solve the problem.
The problem was that it didn't know who rootURL is. I found rootURL in an example and I thought that is something defined in jQuery. It seems it isn't.

Categories

Resources