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

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.

Related

Browser is stuck while another tab is loading

On my website, there is a page that is doing ajax call that can take a few minutes.
While the ajax is working, if we open a new tab and try to load other pages in the website, they won't load until the ajax is completed.
The internet is working, and we can load other websites while the ajax is working.
So it seems that there is something in the browser that is not allowing loading a new page from the same website, while there is an ajax call still in progress for the same website.
This is the outline of my ajax call that is blocking other loading of pages from my site:
$.ajax({
type: "post",
timeout:150000, //TIMEOUT AFTER 150 SECS
data: {
mydata: mydata
},
complete : function(result) {
console.log("ajax complete");
},
cache: false,
dataType: 'json',
error: function (xhr, ajaxOptions, thrownError) {
console.log("error :AJAX completed w/error." +xhr.status+" "+thrownError);
},
success:function(obj ){
console.log("ajax success");
}
});
Any ideas if there is something to fix this issue?
UPDATE
the returned data is pretty small. the server usage is low when this happens, since most of the wait is related to an api call to a 3rd party server.
also, this happens only if the pages are loaded from the same browser. If ajax is called from one browser and another page is loaded from a different browser, there is no delay.

How to replace the entire html webpage with ajax response?

Before going to the specific question I need to explain a few basic steps.
First, the application in question deals with the management of appointments online by customers.
The customer after filling a form with the treatments for the beauty center and providing their information comes to the confirmation page.
Now this page performing an ajax request to store the appointment on the database.
If everything is successful is shown a page containing the details of the appointment with the success message.
The problem is that the page is currently displayed only in the response, that is, in the tab network console browser.
So my question is simple: How can I replace the entire structure of the html page with actual one shown in the response?
I found a lot of questions on the web even on StackOverflow. But all of this is limited on an append to a div. I do not need to hang but also replace the <html>, how to rewrite the html page. I have no idea how to do this and I need some advice from you.
For completeness, this is the code that comes back to me ajax response html:
$.ajax({
'type': 'POST',
'url': 'backend_api/ajax_save_appointment',
'data': postData,
'success': function(response)
{
console.log(response);
},
'error': function(jqXHR, textStatus, errorThrown)
{
console.log('Error on saving appointment:', jqXHR, textStatus, errorThrown);
}
});
If your response includes the <head> and <body> tags:
$("html").html(response);.
If not, and it's only content, then do:
$("body").html(response);.
if the response is the html content, you can use this line of code:
...
'success': function(response)
{
$("body").html(response);
}
...
update:
this will be hard to replace the html tag, but what you can do:
...
'success': function(response)
{
$("html").html($("html", response).html());
}
...
you parse the response with jquery, getting the content of html and replacing the content of the current html
this question has already been treated here:
Replace HTML page with contents retrieved via AJAX
Basically, you may try (My bad this is not working on IE):
document.open();
document.write(newContent);
document.close();
or, since you are using jquery
$("body").html(data);
Regards
Perhaps you can use following code in your 'success'-function to redirect to a different route.
window.location.href = 'http://host.local/path/to/appointment-details';
#JudgeProhet It seems to me that you do not need AJAX request for this purpose. There is no advantage in doing it this way. If the entire page is updated it could be done by an ordinary HTTP request. If you want to use AJAX, you could simply use JavaScript to redirect to new page, which contains appointment details.
$.ajax({
'type': 'POST',
'url': '/backend/ajax_save_appointment',
'data': postData,
'success': function(response)
{
console.log(response);
// redirect browser to new location
window.location.href = '/backend/appointment_details';
},
'error': function(xhr, status, error)
{
console.log('Error on saving appointment:', xhr, status, error);
// display error message to the user
}
});
I don't have enough reps to leave a comment (!!) but the UPDATE answer by #fribu-smart-solutions (https://stackoverflow.com/a/33914275/1428972) should be marked as the correct one, using:
$("html").html($("html", response).html());
This fully replaces the page via ajax. This does the job properly whereas others even using "html" doesn't fully work.
I know this is an old post but it just solved my problem on the same issue! :)

HTML automatically refresh page but check for connection prior

I have a Python based flask web application which shows some SQL information on a html page.
This page is semi-realtime, it gets refreshed every 15 minutes with a simple html refresh:
<META HTTP-EQUIV="refresh" CONTENT="9000">
This works fine as long as the connection is up, there are no internal code errors.
Now I don`t want to have to manually refresh the page once it cannot refresh the page correctly for whatever reason. (connection, internal error).
Is it possible to have a webpage that keeps refreshing every fixed period of time regardless on whether the last refresh was succesfull.
Currently the html page contains no Javascript or the like, just plain html which is generated by Flask built-in template engine Jinja2.
Is it maybe possible to load the webpage completely first than check if it was successful and then refresh?
If you get the a javascript library such as jQuery, you can do this with the asynchronous Ajax functions. Here is an example of how you can replace your <body> content every 15 minutes if it is successfully loaded:
function update_site() {
$.ajax({
url: "/my/page/url/",
dataType: "html",
cache: false,
success: function(data) {
// Replace body with loaded site. You can do more checks here to check
// if the fetched content is all there.
var body_html = /^.*<body>(.*)<\/body>.*$/g.exec(data)[1];
$('body').html(body_html);
},
error: function(data) {
// Couldn't load site.
}
});
}
// Run every 15 minutes.
window.setInterval(function() {
update_site();
}, 15*60*1000);
You could implement some javascript to check the connection when a button is pressed. You could use the navigator.onLine property which should work with all major browsers.
Read more here:
http://www.w3schools.com/jsref/prop_nav_online.asp
should try this
function update_site() {
$.ajax(
{
url: "/my/page/url/",
dataType: "html",
cache: false,
success: function(event)
{
var update_html = /^.*<body>(.*)<\/body>.*$/g.exec(event)[1];
$('body').html(update_html);
},
error: function(event) {
}
});
}
// Run every 10 minutes.
window.setInterval(function() {
update_site();
// To refresh site every 15 min
}, 15000000);

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

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

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

Categories