jQuery Ajax - scripts are contained, even if page is empty - javascript

I am using jQuery ajax to render an HTML page which also contains javascript functions.
my code is:
function ChartBook() {
$.ajax({
url: '/Charts/ChartBook',
dataType: 'html',
id: 1,
traditional: true,
type: 'GET',
success: function (content) {
$(document.body).empty();
$(document.body).html(content);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An unexpected error occured.');
}
});
}
The page Chartbook contains a function "GetChartData()".
It runs fine, but when I call another page in same manner, The Chartbook page is now not in the body, but I can still get alert message from function "GetChartData".
How can scripts be still there, while I have removed the page from html body with $(document.body).empty()?
EDIT:
Another problem is that, if I recall the "Chartbook" page and return to the previous page, The alert message comes twice from the function "GetChartData()". the number of alert message increases each time I load Chartbook page and return to previous page.

The scripts are usually placed on top of the body in a header section. Therefore they will not be removed by $(document.body).empty(); which you could also write as $('body').empty();.

Doesn't matter if you remove all html they are still in DOM check this

Related

jQuery Ajax - Failed Resource or Uncaught Error

I'm running jQuery 1.9.1
On certain links in a Digital Library, I have the following code:
<a class="removeLink" onclick="getDigitalLibrary('removeFromLibrary.action?itemId=1000122007&searchType=ALL')">
Which calls THIS ajax call:
function getDigitalLibrary(urltoremove) {
$.ajax({
url: 'ecom/'+urltoremove,
async: false,
success: function(data) {
$("#ajaxrequest").html($(data).find('#ajaxrequest').html());
},
error: function(data){
alert("An error occurred");
}
});
return remaining;
}
Sometimes when I load the page, I get this error:
Failed to load resource: net::ERR_CACHE_MISS
And whenever I click the link, the entire source code is returned as a
Uncaught Error: Syntax error, unrecognized expression: <!doctype html>...
What am I missing here? If I simply put the full link that is supposed to be created with the Ajax call into the URL bar of my browser.. it works fine: it reloads the page and removes the item from the library.
Use jQuery.parseHTML(data) to parse data and then pass it to $():
success: function(data) {
$("#ajaxrequest").html($($.parseHTML(data)).find('#ajaxrequest').html());
},
In your case $(data) supposes that data is a selector string. parseHTML will make data be supposed as HTML code.
http://jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring

unable to run script on dynamically json parsed content

I would like to give a high level explanation of what's my issue because I can't put up complete code which is too complex.
I have a button. when I click on the button, it pulls data from fb parses it and adds it to the page. Now after it is loaded to then page.. I want to run a script on the loaded content. I am running the script after the data is parsed but somehow it shows that element is not loaded by the time script started running. can some one throw some light.
$("somebutton").on("click",function(){
LoadAndParseFbData();
});
function LoadAndParseFbData(){
//loaded the json, parsed it and added to the page.
anotherScript();
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
This is what i am trying on high level. please help thanks :)
$("somebutton").on("click",function()
LoadAndParseFbData();
});
function LoadAndParseFbData(){
FB.api(path, method, params, function(){
//loaded the json, parsed it and added to the page.
anotherScript();
});
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
Run anotherScript() from within the ajax success callback:
$J.ajax({
url: url2,
type: "post",
data: { data: "yourdata", },
success: function (data, textStatus, jqXHR) {
anotherScript();
},
error: function(jqXHR, textStatus, errorThrown) {
/*error handling code here*/
}
});

table positioning with AJAX to PHP post

I have a jQuery script that sends POST data via AJAX to a php file that then creates a table. I have used firebug to check the console and everything gets created properly. On the success: I reload the window and the table isn't displayed.
I know the table html was created properly from the php file because I commented out the reload so I could see exactly what it created) I have lots of things displayed on my page and would like the table in a particular spot. How can I get the table to actually display where I want it to?
<script>
$(document).ready(function () {
$("#stayinfobutton").click(function () {
var id = $('#id').val();
var dataString = {
id: id
};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/table_auto_guests.php",
data: dataString,
cache: false,
/*success: function(html)
{
window.location.reload(true);
}*/
});
});
});
</script>
The window.location call will reload a new page in the browser window, this will loose the data returned to the ajax call by the server.
Usually the response to Ajax calls is loaded directly into your page, something like:
success: function(html)
{
$('#guestsTable').html(html);
$('userForm').hide();
}
I made up the guestsTable div and userForm names, ;).
The return data may need some coercing to make it into html (I'm assuming your using JQuery), hopefully the php script will set it to html/text in the header, also dataType: html can be passed in the $.ajax({...}) call.
Alternatively, if the classes/table_auto_guests.php returns a full page which you want to load in the browser, Ajax may not be what you are looking for. This post contains code on how to submit the data as a form, and load the result as a new page.

Wierd delay in retrieving dom element

I have created a loading screen plugin. The scenario is that i am doing page navigation using ajax loading. So before loading a page using ajax, i would show an loading screen using the code $('body).loadingMask('show') and once the page is loaded completely loaded, i would remove the loading screen using the code $('body').loadingMask('hide).
The problem is that, there is some delay in retrieving the target dom element inside the plugin.
This is the general structure of the code
$('body').loadingMask('show');
$.ajax({
url : 'views/next.html',
async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
$('body').loadingMask('hide');
The problem is that , inside the show function of the loadingMask plugin, There is a delay in retrieving the target dom element(i.e body) . So pratically, the code $('body).loadingMask('show') runs only after the ajax page is finished loading.
In order to make it work , i have added a time delay. Which seems to work fine.
This is the modified code
$('body').loadingMask('show');
setTimeout(function(){
$.ajax({
url : 'views/next.html',
async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
},500);
$('body').loadingMask('hide');
Now i can see the loading screen, while the page loads.
If you remove async:false you can call your plugin withing the ajax success, right after the content gets added.
async:false is deprecated and often leads to unforeseen problems
$('body').loadingMask('show');
$.ajax({
url: 'views/next.html',
success: function(content, textStatus, jqXHR) {
$('body').append(content).loadingMask('hide');
},
error: function(content, textStatus, jqXHR) {
/* likely need to remove maske here and add something to content to advise user*/
throw "Unable to load template. Please check the path and name of the template"
}
});

AJAX: why isn't my javascript loading with the content?

This is my first time using AJAX. I'm trying to load one of my pages when a link is clicked (I know I can just do <a href="something.html"> but I am doing it just for the sake of using AJAX, and ran into an issue where my page loads but the javascript of the page doesn't. Is this a normal AJAX consequence? I'm guessing it has to do with dataType: html? Here's my code:
function getContent(filename) {
$.ajax({
url: filename,
type: "GET",
dataType: "html",
beforeSend: function(){
$('html').html('<img src="../images/loading.gif">');
},
success: function (data, textStatus, xhr) {
if (filename == "second.html") {
setTimeout(function (){
$('html').html(data);
}, 2000);
} else {
$('html').html(data);
}
},
error: function(xhr, textStatus, errorThrown) {
$('html').html(textStatus);
}
});
}
Can you check chrome's network monitor? First off, does anything get a 404? Is the file literally second.html? If so then there shouldn't be path issues. Next what is the "response" that appears for that item? Does that response look ok?
Next, why don't you try moving the JS from head into the body for the second page? JS should always be right before the closing body tag for performance reasons. Also, there may be an issue with JS being in head and it not getting executed for that reason.
You should be able to load anything on your domain without any issues via AJAX, but there are path issues to watch out for.
This is because the ajax page is only returning rendered content, but does not run like a normal page would. You can use PHP on the ajax page for example, the server renders it and then sends it through, because PHP is pre-render, javascript runs after the page is rendered, as far as I know.

Categories