a .get() request on page load - javascript

I will be redirecting the user to a page. This page gets all of its content from a REST api in JSON format. So on page load I would like to execute the $.get() request and load the contents of my divs in the page.
I know how to execute the get request, however, I don't know how to do it on page load. I have a application.js file for my entire application. So I can't put it in document.ready because that it would load on each page in my application.
I will be executing the get request like this:
$.get(
$(this).data('myurl'),
function (data) {
var item = data.response.item[0];
$('mydiv').html(item.text);
}
);

With jQuery this is very easy, but you have to put this block in your 'start'-page:
$(function() {
// this code will be executed on page load
app.start();
});

From what I understand, you only want to get data from rest api on a specific page..
for that you can do:
$(function(){
if (window.location.href.indexOf('/your/page/url') > -1){
// your $.get here
$.get('/torestapi', function(){ //update divs });
}
});

Add it as an inline script block with a separate document.ready, or just before </body>.
Or add it to a separate js file, and link it only from the specific page where you want to use it.

Related

Javascript From Console - Load a Few Pages, Then Run Function Per Page Load [duplicate]

I'd like to be able to call a jquery function once window.location has completed loading a URL. Is this possible? I can't seem to find anything online about this.
for instance:
if(parseInt(msg.status)==1) {
window.location=msg.txt;
alert("This URL has finished loading")
}
Thanks,
-Paul
You can either use window.onload of the destination page (if you have access to modify the code of that page), or you can use window.onunload to have the alert be launched when unloading the current page. You cannot execute code on the current page after the new page has been loaded.
Yes.
This page demonstrates onload/onunload behavior.
<html>
<head>
<script>
window.doUnload = function(){
alert("Here!");
}
window.doLoad = function(){
window.location="http://www.google.com";
}
</script>
</head>
<body onload="doLoad();" onunload="doUnload();"></body>
</html>
After a user logs in for the first time I need to load my index page to initialize everything but then need to forward them to another page for profile completion.
use window.location to redirect the user to your index, adding a query parameter (something like window.location=index.php?firstLogin=true ) and on your index redirect (using javascipt http 300, header() or whatever you are using) to the profile page after it ends loading if the parameter is set
Iframe
One (ugly) method you could use is to instead of using window.location, clearing the body, adding an iframe with the relevant path and listening to its onload function.
After that you can run code inside the iframe as long as it's not cross-site scripting.
I use this method to perform small automated scripts, that can't really on third-party plugins.
Ajax
Another method might be using ajax to load the page/body content. Then replacing your body with the newly loaded body and start executing the next functions.

jQuery/AJAX load event on individual HTML pages

Please I have multiple HTML pages with each having a separate .js file. I want to recognize each page by URL and load each implementation on page load. I understand I can check load event on HTML element using jQuery like
$( "#result" ).load( "ajax/test.html" );
As specified here. How do I extend that to the pages? I want to execute a jQuery/AJAX load event on each of my HTML pages to check few things like user status or authorization. Example to check if user is logged in, then proceed and execute other jQuery codes, otherwise redirect user to login page.
In page header do a authentication check and redirect user to login page.
$(function() {
$('#result').load('auth/test', function( response, status, xhr ) {
if (response == 'guest') {
window.location = 'auth/login';
}
});
You can either put this code in separate file and include the file in every page or use some template hierarchy to achieve this.

How to execute JS code after redirect to page with href link?

I have a page with a function like this:
$.ajax({
type: "POST",
url: "checkLogin.php"
})
.done(function( msg ) {
alert(msg );
if (msg != "true"){
window.location.replace("index.html");
}
});
This function checks if a Session is alive on Server. If not it will redirect to index.html.
On first call of this .html it works. But if I go to this page with a href link when the page was loaded before the page isn't executing any JS.
How can I call that JS again?
When I am open up an other page without loading that page with javascript before and click the href link it works.
Something with Cache?
Try using window.location.replace("index.html"); replace() removes the URL of the current document from the document history, meaning that it is not possible to go back.
What you could do is append the index.html string with index.htlm#something and then detect that (something) onload/on document-ready for the index page, and execute the code you want
edit: ie window.location.replace("index.html#session_check");
and on the index page, use
if(window.location.href.indexOf("#session_check") != -1) {
// code here
}
According to my limited knowledge JS scripts from a different HTML file are not executed due to security reasons. If you want to execute the JS scripts you need to use the eval(str) function call. Where str is the JS scripts serialized to a string.
A second approach would be to create a "script" tag dynamically and supply the src attribute pointing to the desired JS file. When the script tag is placed in the DOM the script should hopefully be executed.

Json request data and jquery prettyphoto binding issue

There is a situation I am having with jQuery. In particular its prettyPhoto library and getJSON function.
I have a page which loads HTML, it calls jQuery and prettyPhoto. There is some inline JS which makes a JSON request further down the page:
It should work like the below:
1) Page loads,
2) Javascript code run,
3) Script runs a jQuery JSON request which returns and has HTML (a-tags and images inside each a-tag) inside,
4) Script then prints the HTML from inside the JSON to the screen,
5) User clicks a-tag/image and it opens in prettyPhoto's iframe popup.
NOTE -> Each a-tag has a prettyPhoto id attached (to load the image in prettyPhoto using iframe popup).
The problem is the images (a-links) do not open with prettyPhoto and I am not sure why. There is no JS Error.
However, it does work if i manually have the HTML (a-links/image) already there (so just loading their HTML from the JSON request seems to make the difference).
Seems by time the JSON request returns (with HTML) prettyphoto already binds to a-tags (or lack off).
Tested so far:
Tried putting JSON request in 'document.ready' and prettyPhoto in 'window.load'. So does JSON requests early and prettyPhoto binds when everything else loads - failed
Tried using jQuery AJAX instead of JSON - failed
Dont need the code especially but having trouble with the logic.
It sounds like the HTML from the JSON (a-links/images) doesnt come back quick enough (before 'window.load' runs).
Try putting the prettyPhoto JS into the success callback (i.e. where returns data).
Below load_images.json is the JSON request you do which returns the HTML (a-links and their images):
$.getJSON("load_html.json", function() {
//grab HTML data (images/a-links) from json file and print into page
})
.success(function() {
//JS code running prettyPhoto inside here. Now will bind to a-links.
});
PrettyPhoto now binds to A-links AFTER the JSON has loaded them.
Hopefully will help having the prettyPhoto stuff AFTER the a-links.
If that fails try putting the prettyPhoto code inside the complete callback which occurs after success callback. Like the below:
$.getJSON("load_html.json", function() {
//grab HTML data (images/a-links) from json file and print into page
})
.success(function() {
//nothing
})
.complete(function() {
//JS code running prettyPhoto inside here. Now will bind to a-links.
});
This way you are giving prettyPhoto plenty of time to bind to the correct a-links which are marked for it.
Try that.

Trying to perform an action after loading a javascript resource

Clicking a button on a page causes to a javascript file to be loaded. How do I call a function on the completion of the loaded file?
Description
You can load the file using jQuery's getScript() function and then call a function from this script.
Sample
$.getScript('YourJavascriptFile.js', function() {
// file is loaded
});
More Information
jQuery.getScript()
Take a look at:
http://api.jquery.com/jQuery.getScript/
I believe you can put a $(document).ready in the script file you are dynamically loading, which will execute as soon as the loading is complete (assuming the DOM it's being loaded into is already "ready")
$(document).ready(function () {
// save the world
});

Categories

Resources