ajax-loaded script not functioning - javascript

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.

Related

after ajax success refresh / reload page but prevent page blink

as title you see, I meet some problem with my website,
I use ajax to read my API, and after ajax success, I need to reload page to display some data,
Unfortunately, the page sometime will blink and then reload, but sometime will not.
And I use setTimeout to achieve that, because I'm writing shopping cart page,
It allow user edit their shopping carts' goods.
My idea is: after user stop click plus or minus button or stop typing quantity about 1 second,
ajax will execute to read my API, after ajax success, reload page.
So, is there have any ways to prevent page blink?
Or maybe I can made a loading gif to display on the page?
My code will be like:
var timeout = null;
$('.num').on('keyup', function() {
var newNum = $(this).val();
var pid = $(this).attr("name");
clearTimeout(timeout);
timeout = setTimeout(function() {
if(newNum <= 0){
alert("At least 1 product!");
$(this).val("1");
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: 1
},
dataType: "json",
success:function(data){
window.location.reload(true);
},
});
}else {
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: newNum
},
dataType:"json",
success:function(data){
window.location.reload(true);
},
});
}
}, 1000)
});
You can add a loader gif as you want then remove when document loaded.
<div class="loader-fix" style="position:fixed;height:100vh;width:100vw;background:#ffffff;">
<img src="your.gif" />
</div>
<script>
$(window).on('load', function (e) {
$('.loader-fix').fadeOut('slow', function () {
$(this).remove();
});
});
</script>
What is the point in using ajax when you want to reload the page to show updated data...?
success:function(data){
window.location.reload(true);
}
What is the use of above piece of code..?
For your purpose a simple form submission thing was enough, but you have used ajax getting data but not using it anywhere.
If you want to reload the page, then better go with solution by Şahin Ersever.
If you want a dynamic site, where data is fetched from backend in background and updated on frontend without refreshing the page, do something like this.
<html>
<body>
<h1> Dynamic load using AJAX </h1>
<div class="dynamic_div">
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
</div>
<button onclick="letsload()">Load</button>
<script>
function letsload(){
$.post("someurl",{ data1: "value1", data2 : "value2"},
function(data, status){
if(status == "success"){
$('.dynamic_div').html(data);//Loading updated data
}
});
}
</script>
</body>
</html>
On data variable, you can echo out desired html/json or a success/error code, and handle the data/code in ajax function accordingly.
Edit :-
Looking at your comment But I check my website, if ajax success, I use console.log to print my data, it's not working, but if reload page, it can work.
I have a quick and easy solution for this.
Let's take above example, which I have given.
Suppose if I want updated data to be displayed in dynamic_div what I will do, is I keep the element to be shown inside that div in separate file.
eg:- updated.php
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
Now What I do is on success of my ajax, I will load this div in to my .dynamic_div like this.
success:function(data){
$('.dynamic_div').load("updated.php");//Load the inside elements into div
}
Now you will get updated data, as you have already updated it somewhere in backend, so load() will load a page inside a division, without refreshing the whole page.
Comment down for any queries.
AJAX Read data from a web server - after a web page has loaded
Update a web page without reloading the page
Send data to a web server in the background
What is Ajax
If you want to reload page then don't use ajax call,
but if you want to load data using ajax then update your html using JavaScript in ajax success message.

Javascript included in MVC partial view only runs the first time

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

jquery loading script when preparing document

I have a problem with jquery and would appreciate a help from stackoverflow community to solve following problem
Lets assume that there a server side script which creates doc file and following links calls it
<a class="prepare_doc_file" href="somepage.php?action=docfile">docfile</a>
what i need is jquery script, which shows loading image, when doc file if being prepared (or when the link is clicked) and hide it after getting download popup.
I see loading circle in the tab in browser. I need the same thing inside the html document
Thank you
You need to use AJAX, and generate a tempfile to download.
Your php can generate file and save to some temp path. After downloading you can delete this file.
<a class="prepare_doc_file" id="downloadfile" href="somepage.php?action=docfile">docfile</a>
function loadFile(){
document.getElementById('downloadfile').innerHTML='loading, please wait';
$.ajax({
url: 'somepage.php?action=docfile',
complete: function (data) {
document.getElementById('downloadfile').href='path to file'; //path may be returned on php.
document.getElementById('downloadfile').innerHTML='docfile';
}
});
}
<div id="myDiv">
<img src="loading gif image url">
</div>
<script>
$.ajax({
type: "POST",
url: "url to the page where the contnt is",
data: 'parameters if any' ,
success: function(result){
//logics
$("#myDiv").html("<a class="prepare_doc_file" href="somepage.php?action=docfile">docfile</a>");
});
</script>

TineMCE doesn't initiate ajax-loaded textarea

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

<script> not returned in AJAX

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

Categories

Resources