js .append html element do not have javascript lib - javascript

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

Related

Functions inside iframe execute before js libraries are loaded

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?

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();
});
}
});

Display View in New Window

I have developed an ASP.NET MVC application that will run several prescreen functions based on user input.
The plan is to call this new mvc app from an existing HTML/JavaScript application. I would like to display the controllers's view in a new browser window outside of the calling application.
My AJAX call will look something like this
$.support.cors = true;
$.ajax( {
url: "http://mvc_url/prescreen",
data: jsonObject,
type: "POST",
processData: false,
dataType: 'html',
contentType: "application/json; charset=utf-8",
timeout: 60000,
//dataType: "json",
success: function ( msg )
{
...on success msg = html rendered from view...
},
error: function ( XMLHttpRequest, textStatus, errorThrown )
{
...error handling...
}
} );
I've tested this and on success msg does contain the fully rendered HTML from the view. My question is how do I open a new window using the rendered HTML?.
I've tried the following:
var newWindow = window.open( "", "", "" );
newWindow.document.write( msg );
and that seems to work. sort of. The new window opens and the html is displayed, but then my style sheets and included javascript files, for the view, are missing. So if using the above window.open code is correct, then how do I bring down the necessary stylesheets and javascript files?
EDIT
Utilizing the suggestion provided by AndyJ, I've modified my view to include relative paths based on my base application. Here is the returned mark up from my MVC
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offer</title>
<link href="../css/site.css", type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container body-content">
... Page Content ...
<script src="/baseapp/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="/baseapp/js/someInclude.js" type="text/javascript"></script>
<script type="text/javascript">
InitializeForm();
</script>
the InitializeForm method is defined within the someInclude.js.
Based on the above and assuming the files are locates in the paths, everything should link up, correct? So what else might I be doing wrong?
In addition to the help provided by Andy J (Thank you), I also found that when the response was rendered in the new window, the JQuery library was loading AFTER my initialization script. To circumvent this, I simply added my event handlers to the inline attributes of the controls.
This may be a work around, but for now it seems to be working for me.
If you are returning raw HTML in the AJAX request you will probably need to add the CSS and JS references there. You are not really returning a view that would normally have a layout that includes the references.

Only getting html standard tooltips when using bootstrap tooltips

I am trying to use the bootstrap tooltips on an element by I am not getting the bootstrap style, only the html style:
I have used these many times, but I feel like I have been up for too long and am getting sloppy... can someone point me to the error?
code:
home.php
<a href="#" id='award-value' rel='tooltip' data-toggle='tooltip' title='My Tooltip'>450</a>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script src='assets/js/chosen.jquery.js'></script>
<script type="text/javascript">
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({
allow_single_deselect:true
});
</script>
<script src="assets/js/jquery-form.js"></script>
<script src="assets/bootstrap/js/bootstrap.js"></script>
<script src="assets/js/session.js"></script>
and I am including the bootstrap css
EDIT:
I fixed it, I had the elements i wanted to be tooltips added dynamically, fetched using ajax... I just put the $(this).tooltip() in the success callback of the .ajax() call like so:
function fetch_live_feed(){
$.ajax({
type: "GET",
url:"includes/php/live_feed.php",
success:function(data){
$("#live-feed-loading-port").html(data);
$(".live-feed-row a").tooltip();
}
});
}
Please let me know if this is a wrong thing to do...
Thanks :)

GSP tags in JavaScript

I had the following in the <head> of a GSP
<script type="text/javascript>
$("button.remove-item").click(function() {
$.ajax({
url: "${createLink(action: 'remove', controller: 'cart')}",
type: 'POST'
});
});
</script>
Notice that I'm using the Grails createLink tag to construct the URL that the AJAX request will post to. When I moved this code into checkout.js and replaced the block of code above with:
<script type="text/javascript" src="${resource(dir: 'js', file: 'checkout.js')}"></script>
the createLink tag is no longer evaluated by Grails. So it seems that Grails tags within <script> blocks are evaluated, but tags within .js files included by GSPs are not - is there a way to change this?
Check out the GSParse plugin to have css and js parsed as a gsp file:
http://nerderg.com/GSParse
http://grails.org/plugin/gsp-arse
You are right .js files are not evaluated by grails! but the GSP are! so thats why when u were setting a tag it was working.
I would suggest you to have a differente approach of how to grab that link! as u are using jquery I would do like this:
<input type="button" class="remove-item" data-url="${createLink(action: 'remove', controller: 'cart')}" value="GO" />
checkout.js:
$("button.remove-item").click(function() {
$.ajax({
url: $(this).data('url'),
type: 'POST'
});
});

Categories

Resources