I use $.ajax() to load this piece of html into a div
<div class="board-container">
<form method="post" action="functions.php">
<input type="hidden" name="function" value="set_boards">
<div class="row-fluid">
<div class="span6">
<h3 class="dark">Student Board</h3>
<textarea id="board_students" name="board_students">
</textarea>
<br>
</div>
<div class="span6">
<h3 class="dark">Instructor Board</h3>
<textarea id="board_instructors" name="board_instructors">
</textarea>
<br>
</div>
</div>
Update Boards
</form>
</div>
<script src="libs/tinymce/tinymce.min.js"></script>
<script src="js/board.js"></script>
And in the board.js, there's simply a TinyMCE initiation function.
$(function()
{
tinymce.init({
menubar : false,
height: 700,
selector: "#board_students"
});
});
The ready() function should be called automatically due to ajax request. I've tested with alert and I know the function gets called.
The code works if the html is in the div by default, but when loaded through ajax, nothing happens. Why is that?
This happens because your ajax loads content asynchronously and your tiny initialization function happens synchronously, may be the initialization happens before the content is placed into your dom. The another thing is you shouldn't load scripts in html data .
To solve this
If you want to load script async means you have to create a script tag element using js like
var jsonp = document.createElement("script");
jsonp.type = "text/javascript";
jsonp.src = "libs/tinymce/tinymce.min.js";
document.getElementsByTagName("body")[0].appendChild(jsonp);
or You can include tinymce.min.js in page itself and initialize the div after the content is loaded like
$.ajax({
url: url,
type: type,
data: data,
success: function(htmlData){
$('#DivId').append(htmlData);
//here internalize tiny mice when its available in dom
tinymce.init({
menubar : false,
height: 700,
selector: "#board_students"
});
}
});
Try this and let me know if this works ... !!!
The reason this is happening is because, The ajax adds your content AFTER --page load--. Therefore, it's not reading and adding your code to the DOM, because you're adding this after the page is already loaded.
As many said, you can preload this info, or if you want to use AJAX.
The easiest way to initialize your code would be to add a .complete function at the end of your ajax call. This says that when the ajax function is done running, continue with this action.
$.ajax({
type: "POST", #GET/POST
url: "some.url",
data: {}
})
.complete(function() {
tinymce.init({
menubar : false,
height: 700,
selector: "#board_students"
}
});
Jquery Ajax Call
The <script> blocks in your case will start execute in the same moment asynchronous, and just because tinymce is the biggest script, tinymce.init will fail.
You need load the scripts as additional cascade of ajax call:
$.get(...., function (){// first level, getting the html
$.getScript(...., function (){// second level, getting <script src="libs/tinymce/tinymce.min.js"></script>
// executing or loading js/board.js
});
});
Related
I have a button which I use to load a partial view via jquery ajax call, which on success, just replace a div holder by the json string being returned.
The partial view consists of some javascript and html tags. I have to set the jquery.ajax dataType: "html" in order to get the javascript executed in the partial view when it is loaded.
In the parent view:
$("#test2Div").on("click", function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetMainSolution", "Solutions")',
data: { IdEjercicioSolucion: 9 },
cache: false,
dataType: "html",
success: function (response) {
$("#placeHolder").html(response.ViewContent);
}
});
});
The problem is that this is only working fine for the first time I load the partial view. Once it is executed for the first time, it seems that those javascript included in the partial view being rendered are not being executed anymore or something is missed in the DOM. If I refresh the whole page, with F5 and load the partial view again, it will work again for the first time.
Please, any ideas?
EDIT 1: add more sample code:
Parent view: This is the main view. It displays another another partial view which has some fields and a button. Clicking that button invoke UpdateChViewerLayoutForm function, which trys to load the following partial view into aqviewerholder div.
<div id="dvContainer">
<div class="container">
<div class="row">
#Html.Partial("SolutionsCursoSelectedPartial", Model)
</div>
<div class="row">
<div id="aqviewerholder"></div>
</div>
</div>
</div>
<script type="text/javascript">
function UpdateChViewerLayoutForm(s, e) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSolucionsAQV", "Solutions")',
data: { IdES: s.GetValue() },
success: function (response) {
$("#aqviewerholder").html(response.ViewContent);
}
});
}
</script>
Partial view (SolutionsAQv):
#Code
If Model IsNot Nothing Then
#Html.Raw(Model.TextoHTML)
End If
End Code
<script src="~/Content/AQv/rm.js" type="text/javascript"></script>
<script src="~/Content/AQv/bm.js" type="text/javascript"></script>
<script src="~/Content/AQv/nn.js" type="text/javascript"></script>
Please note that the content delivered to model needs to be parsed using the scripts in partial view.
This is working properly in the first load, but not in the following ones. If refresh the whole page, it works again.
I guess it may be something related to the fact that partials views via ajax do not execute javascript? or that javascript is not finding the target in the DOM in the following exceutions?... but I dont really know how to continue...
Thanks a lot
One possibility is that your partial view includes same jQuery or other javascript bundles as the ones in 'main view'. Once they are rendered for the first time, you will have two such sets (one from your main view and one from your partial view). Make sure you have only one bundle on your webpage and not repeating bundles.
This happened to me.
P.S: This is one possibility! No way I'm saying this is the only reason. I just thought this could be a possibility
So I am using an AJAX loader on my WP installation and one of the pages I am loading has a script in it.
<div id="register-form">
<div id="register-one"></div>
<div style="text-align:center;padding-top:10px;"></div>
<div class="horizontal-rule"></div>
<div id='register'>
<div id="register-character">
</div>
</div>
<div class="post">
<form action="" method="post" id="register-form" >
What's your Name:
<input class=in id='register_name' name="register_name" onkeydown='register_step1_keydown();' onkeyup='register_step1_keyup();'>
<input class="next-submit-button" type="submit" id="register-step-one" value="" />
<input type="hidden" name="submit" />
</form>
</div>
</div>
<script type="text/javascript">
$("#register-step-one").click(function() {
$.ajax({
type: "POST",
success: function() {
$('#register-form').html("Test");
}
});
return false;
});
</script>
The issue is however, when the page is loaded through the AJAX, the script doesn't work. Yet if I refresh the page the script works. Obviously the script doesn't like running from an AJAX call.
Is there a way to make the script work when it is loaded through an AJAX call? I know I could put the script in to the main page's footer or something but I was hoping I could get around this as I will end up with a ton of scripts in the main page.
Before anything else, you should wrap your function in a .ready() to ensure all DOM elements are loaded before you do something to those elements
Also, scripts within HTML that are returned via ajax functions in jQuery are executed only when the HTML is appended in the DOM. Since you did not append the html containing the code, the script in that returned content won't run.
Take a look at the .ajax() function's parameters, under dataType
dataType:
...
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
...
I am creating a WordPress theme and using AJAX to load new archive pages. The problem is that the whole < script type="text/javascript">//something//< /script> is not returned in the newly-acquired content.
Suppose I have these codes initially :
<div id="post-1">
<script type="text/javascript">
//some codes here//
</script>
<div class="content">
</div>
</div>
After navigating to the next page and back to this original page using AJAX, I will get these (in Firebug) instead :
<div id="post-1">
<div class="content">
</div>
</div>
The whole chunk of Javascript codes will not be returned, but under the 'Inline' script in 'Script' tab of Firebug, they are still there.
So, I'm wondering what have I done wrong in retrieving the new content using AJAX? Below is the code that I'm using :
jQuery('.ajax-pagination a').live('click', function(e){ //check when pagination link is clicked and stop its action.
e.preventDefault();
var link = jQuery(this).attr('href'); //Get the href attribute
jQuery.ajax({
url: link,
dataType: "text",
context: document.body,
beforeSend: function(){jQuery('#container').fadeOut(500)},
success: function(html) {
var newhtml = $('#container', $(html))
$('#container').html(newhtml);
$("container").find("script").each(function(i) {
eval($(this).text());
});
jQuery('#container').fadeIn(500);
},
error: function() {
alert('Error');
}
});
});
I am trying to run the Javacript loaded via AJAX, but the problem seems to be that the Javascript itself isn't even returned together with the rest of the content.
Thanks for reading such a long question and I really appreciate your help!
The .html() method strips <script> tags from inserted HTML.
You'll need to traverse the HTML before you try to insert it to find all of the script tags and then use jQuery.globalEval to execute their contents.
success: function(html) {
var newhtml = $('#container', $(html));
// execute included script tags - assumes inline for now
$('script', newhtml).each(function() {
$.globalEval($(this).text());
});
$('#container').html(newhtml).fadeIn(500);
}
I'm receiving this HTML document via AJAX:
<form enctype="multipart/form-data" method="POST" action="admin.php?do=media&action=file-upload">
<div id="uploadForm">
<div id="fileList">
</div>
[Select File]
[Start Upload]
</div>
</form>
<script type="text/javascript">
// $(function(){}); not working when data loaded with ajax request
var ajaxUpload = new plupload.Uploader({
runtimes: 'gears, html5, flash',
url: 'upload.php',
browse_button: 'selectFile',
});
ajaxUpload.bind('Init',function(param){
console.log(param);
console.log($('selectFile'));
});
$('#uploadFile').click(function(){
alert('Something');
});
ajaxUpload.init();
</script>
When I append this to the main document, the JavaScript inside it will immediately run and not be able to find the referenced DOM elements.
It works when I add a time-out on the code, but I would like to know a better way at achieving this.
Update
Modified to reflect the true intent of the question.
This is not possible in the manner which you've described, because the JavaScript is not bound to a condition to run, so it runs immediately.
The code inside the document you're receiving via AJAX should be wrapped inside a function by providing side:
function onDocumentReady()
{
// your code here
}
Then from the loading code:
// get the HTML and JavaScript in data
$('#container').append($(data));
// fire the function to let JavaScript run
onDocumentReady();
If you have multiple requests, the providing side should make the onDocumentReady function unique by adding random alphabets to the function name, e.g. onDocumentReady_123()
Wrap your code inside a $(document).ready. This will ensure that your JavaScript doesn't run until the DOM is loaded and the elements you're targeting will be available on the page:
$(document).ready(function() {
var ajaxUpload = new plupload.Uploader({
runtimes: 'gears, html5, flash',
url: 'upload.php',
browse_button: 'selectFile',
});
ajaxUpload.bind('Init',function(param){
console.log(param);
console.log($('selectFile'));
});
$('#uploadFile').click(function(){
alert('Something');
});
ajaxUpload.init();
});
For more information on how this works, see the documentation for jQuery ready. The site also has information on other useful jQuery commands that may be helpful, and I encourage you to check it out and try the examples that are there. Good luck!
UPDATE:
If I understand correctly, you're getting something like this HTML from the server:
<!-- Pulled HTML from the server using AJAX -->
<div id="uploadForm">
<div id="fileList">
</div>
[Select File]
[Start Upload]
</div>
And maybe trying to inject it dynamically into this:
<form action=""> <!-- inject HTML here --> </form>
If my understanding is correct, then this should allow you to inject the HTML and then only run the JavaScript once the AJAX request completes, and the new DOM has been injected. Keep in mind that, since I don't have all of your code, this is just a conceptual example:
$.ajax({ url:"/somepathtoGetData",
success: function(data) {
// your HTML is in the variable "data", and this injects the HTML into
// the form element on the page
$('form').html( data );
// now that the DOM elements are loaded from the AJAX request, do your
// other stuff with the uploader here
var ajaxUpload = new plupload.Uploader({
runtimes: 'gears, html5, flash',
url: 'upload.php',
browse_button: 'selectFile',
});
ajaxUpload.bind('Init',function(param){
console.log(param);
console.log($('#selectFile')); // added # for id attr
});
$('#uploadFile').click(function(){
alert('Something');
});
ajaxUpload.init();
}
});
UPDATE
Say I have two php files, one is main.php, having such codes: (not including jQuery src, please add your own)
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#b').click(function(){
$.post("ajax.php",
{
taskaction: "getFormAndJs"
},
function(data){
$('body').append(data);
// $(document).trigger("ready");
},
"text");
})
});
</script>
<body>
aaaaaaaaaaaaa
<input type=button id="b" value="click" />
</body>
another is ajax.php, like this:
<?php
if ($_POST['taskaction'] == 'getFormAndJs') {
echo '
<div id="uploadForm">222</div> <input type=button id="a" value="upload" />
<script>
$("#a").click(function(){
alert(123);
})
</script>
';
}
?>
It seems work on my side (click button a and alert "123"), whether I add the
$(document).trigger("ready");
or not.
Does this look like your situation?
This code below is loaded via ajax:
<div class="main">
//some content
</div>
<div class="advanced">
//some content
</div>
<div class="other">
//some content
</div>
<div class="pass">
//some content
</div>
<script>$('.advanced,.other,.pass').hide();</script>
They hide fine when loaded normally, but when loaded via ajax it doesn't work anymore. Why is it so? I'm not really sure if $.on() would really help here.
If the example above is loaded via jQuery ajax, why not just call the
$('.advanced,.other,.pass').hide();
upon completion of the ajax request?
For example:
$.ajax({
url: "Your AJAX URL",
dataType: 'html',
type: "POST",
success: function (json) {
// Add you elements to the DOM
},
complete: function () {
$('.advanced,.other,.pass').hide();
}
});
According to jQuery
any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string.
this could mean that your script executed first, before you managed to do anything with it.