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();
});
}
});
Related
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?
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 years ago.
Why does my ajax not work?
These are my pages.
I'm using JQuery to check click event and using ajax to load the responder page.
What is wrong in this code?
index.php
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#clicket').click(function() {
$.ajax({
url: 'res.php?rand=' + Math.random(),
type: 'GET'
success: function(results) {
alert(results);
}
});
});
});
</script>
</head>
<body>
<button id="clicket">Hi</button>
</body>
</html>
Responder page:
res.php:
<?php
echo "Worked!";
?>
UPDATE:
I changed my javascript code above.
Put your logic in a document ready. Since your script is in your head, the markup in the body hasn't been loaded into the DOM yet. In order to make your script wait until the DOM has been built, put the logic in a document ready to delay it until that time.
$(document).ready(function() {
$('#clicket').click(function() {
$.ajax({
url: 'res.php?rand=' + Math.random(),
type: 'GET',
success: function(results) {
alert(results);
}
});
});
});
Try using full URL for your ajax call. If you are on live server then write your full domain name, like www.your_domain.com/res.php?rand=.
I am trying to have my site use Ajax from another file but it never works unless the code is actually in the view.
The site successfully calls my other Javascript file but does not seem to recognize the one with Ajax in it.
The following is in my external Javascript file with Ajax in it (ajax.js):
$(document).ready(function(){
$("#idForm").submit(function(e) {
$.ajax({
type: "POST",
url: "{{ url('/auth/login') }}",
data: $("#idForm").serialize(),
success: function(data)
{
location.reload();
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
And the following is in my master layout file that successfully uses the form.js file but not ajax.js .
<html>
<body>
<!--Other Stuff-->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/forms.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/ajax.js"></script>
</body>
</html>
Any ideas?
By default, external js file don't support blade syntax. So, to send the ajax request from external js file need to do the followings:
create a global variable to ur template.blade.php file as follows:
var SITE_URL = "{{URL::to('/')}}";
then when to send the ajax request do:
$.ajax({
url: SITE_URL + '/route_name'
});
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>
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.