Loading content into a div using jQuery's load method - javascript

I am trying to load the contents into a div named rightcontent into my page from external html files using the jQuery's load method. Initially, there is no content in my div rightcontent, and as the user clicks some links, the texts are automatically loaded into that div.
Take a look at these snippets :
In my web page:
<div id="rightcontent">
</div>
The same web page also contains links like these:
<a class="myajaxreq" href="pages/abc.html">Link I</a><br>
<a class="myajaxreq" href="pages/pqr.html">Link II</a>
The external javascript file contains these code:
$('.myajaxreq').click(function() {
var myhref=$(this).attr('href');
$('#rightcontent').load(myhref);
return false;
});
When I check whether my javascript calls are made correctly using alert(myhref), it works correctly. However, no content is loaded into the div. Help me out here !!

Are you testing the code locally or on a server? AJAX requests won't work locally.
Upload it to a server (and put everything in the right subdirectories) and it should work fine.

use
$('#rightcontent').text(myhref);
instaed of
$('#rightcontent').load(myhref);

Try using
$(".myajaxreq").click(function(){
$.get( $(this).attr("href"), function(page){
$("#rightcontent").html(page);
})
return false;
})

Related

Waiting for Web Request Results in HTML <script> Tag

An application I'm writing has the following requirement:
I need to implement a fetch request within a tag, but I need to wait for the results of the request before the rest of the page is loaded? The goal is to run window.stop() if the results match a certain value, but allow the page to fully load if the results don't match the specified value.
Is there any way to implement this?
I know this is not an efficient way to load the page, and it will make the page load slower, but that is not a concern for the current application.
I don't think http requests can be controlled directly through DOMJS, but you can use the following method to do what you want:
The method simply saves the content of the page to a local variable inside the function, and then displays it when you are done with your verification.
This Function Was Be called When Your Browser displayed the basic html content :
function CheckPageContent(){
var appData = document.querySelector("#AppData");
var htmlContent = appData.innerHTML
appData.innerHTML = "";
setTimeout(function(){
appData.innerHTML = htmlContent;
appData.style.display = 'block';
document.querySelector("#Loader").style.display = 'none';
},3000);
}
Your page must be have this structure :
<body>
<div id="AppData" style="display:none">
<img src="https://www.w3schools.com/tags/img_girl.jpg">
<br>
Hello 1Worled!
</div>
<div id="Loader">Loading......</div>
</body>
<script>
CheckPageContent();
</script>
If you want how the method works, then you must first understand how the browser works when you request a page
Until everything is clear, the browser when you request a page, the browser downloads only the hypertext (html) for this page, and then displays it on the page.
In the event that the hypertext contains external files, the browser downloads them separately from the main page.
For example, if the requested page contains this crown
After viewing the basic hypertext, the browser will download the bootstarp file and then normalize it to the already displayed html text .... and so on with the images and other files ....

Add HTML/JS code to external web page after it has loaded

Is it possible to load an external web page like 'http://www.google.com' and then append my own HTML/JS code to the end of it (e.g. to run a function)?? Surely there is a way to load an external page then add a little bit of my own code after it? Something like this:
<html>
<script>
document.location.href="http://www.google.com/"; //Load external page
function myscript() {
...blahblah
}
</script>
<button onclick="myscript();">Click me</button>
</html>
I'd like that button to be at the bottom of the external page. Please do not suggest parsing methods in php. I've tried doing this by parsing the page first in php then appending my own script to it and echoing as I described here:
Append HTML to page after redirect
This works for simple pages where there are no re-directs or when the final external page can be parsed properly. The problem is that I can't properly parse the external page. The code that is parsed doesn't seem to function without the code from previous pages (before the re-directs). I need to do this without parsing/scraping/crawling.
Thanks!
EDIT: I've tried displaying the external page in an iframe as suggested by Amadan:
<script>
function myscript() {
...blahblah
}
</script>
<iframe src="http://www.google.com/"></iframe>
<button onclick="myscript();">Click me</button>
</html>
However, in firefox it just displays a blank box but in IE it says "This content cannot be displayed in a frame: To help protect the security of information you enter into this website, the publisher of this content does not allow it to be displayed in a frame."
Any way I can get around this?
EDIT 2:
I've included jquery and the cross domain script here (https://github.com/padolsey/jquery.fn/blob/master/cross-domain-ajax/jquery.xdomainajax.js). This is the code I'm using now to get the contents using ajax. How would I go from that to actually displaying the content in the webpage? Sorry I'm really bad with ajax/jquery!
function test () {
$.ajax({
url: 'http://www.google.com/',
type: 'GET',
success: function(res) {
var content = $(res.responseText).text();
alert(content);
}
});
}
You can't append anything to a page you don't control except by installing a browser extension (which then works only for the clients where your extension installed).
You can include the contents of a page you don't control inside your own page (in two main ways: client-side iframe and server-side pull), but you seem to be saying this is not what you want.
Try something like this:
var html = '';
$.ajax({
uri: 'http://ya.ru',
method: 'POST',
success: function(data){
htmlx = data;
}
});
About manipulating html inside an variable
var test = $("<div/>");
test.append(html);
test.find(".innertest");
// When I'm ready to append it..
$('#container').append(test);
If it doesn't work, you can use another page on your server for getting a remote page and use ajax to request it.

Load scripts in bootstrap modal when getting fragment of page

I'm currently getting a fragment of a page and loading in bootstrap modal.
This fragment of page includes the jQuery required to load Google Maps but when the modal loads the content, all scripts are getting stripped so subsequently, the maps don't load.
Even if I directly insert the scripts inside the modal-body class, they still get stripped.
Is there a workaround to this at all?
What we're currently using to trigger the modal is:-
Launch demo modal
I can provide further code in use if needed to answer accurately.
=== Edit: Providing more code in use on request...
So we're including a sitewide link that triggers bootstrap modal. The link that is triggering modal can be seen above and here is the rest of the code in relation the modal.
What we wish to load in the modal is just a fragment of the page at /stores, all the code that is loaded at this URL can be seen here. From this page though, we only really wish to load everything inside .modal-container on line 192 but as necessary scripts reside outside of this div in the same file, we aren't capturing this when we try to load in modal. So previously, our modal trigger looked like:-
Launch demo modal
This then led us to try and just wrap entire file content inside div and call it's contents as the fragment of page in modal so that we can pull the necessary scripts required to load #map_canvas but alas, all scripts are stripped out of modal...
Hope this gives greater explanation into what we're trying to achieve.
=== Edit 2: We've actually fixed this via a workaround but it was a mammoth job so will post answer as soon as I can...
I'm using the following code to load view on boostrap modal :
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$(url).modal('open');
} else {
$.get(url, function(data) {
$(data).modal();
}).success(function() { $('input:text:visible:first').focus(); });
}
});
With the following trigger :
<i class="icon-plus icon-white"></i>
By using this method you will ensure that all you script will be loaded when your modal will display. This is only this workaroung that I found to correctly showing my modal.
Everything that I have to show on my form (new.html) will be displayed perfectly.
Thus, I suggest that you put all you releavant code to Google Map on the page corresponding to /stores.
Edit
You trigger should be :
Launch demo modal
Instead of :
Launch demo modal`
Edit2
The problem that I see, is that you modal inclusion do not get the JS files because these are not within your inclusion section. I'm not a PHP expert, but here is to option that you might try :
Option1 (not very clean)
You can add <script>Google Map required JS File</script> tag inside the <div class="modal-container"></div> but you will get duplicate tag for the same JS file.
Option2 (Might be possible ?)
Create new file and add your section <div class="modal-container"></div> with your required JS files.
Replace the line 192 by including your new file and call your modal by passing your current store object in order to display your information in the modal.
Let me know if its help.
Has StackOverflow changed your code?
Launch demo modal
You have the classname within the href? This could be part of the problem.

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.

How to realize screens / views with JavaScript / Jquery easily?

I'm sure I'm missing something pretty basic, but I have just started to get myself up to speed on jQuery and Javascript programming. Previously I was doing server side programming with PHP.
I'm now in the middle of creating a prototype for HTML5 webapp, where I would like to have different screens. Now with PHP that was pretty easy, I could just used server side templates like Smarty and be done with it.
However to make my app more webapp like, I would like to dynamically change between screens without having to reload the window.
I have looked into several options that might be anwsers to my question, but I'm not sure whether I'm on the right track.
I have checked for example JsRender, JsViews or even the pure jquery load command.
But what I'm not sure is whether these things would allow me to have something like this:
HEADER_PART
MAIN_CONTENT
FOOTER_PART (also contains links to common JS files that I use)
I would like to dynamically update the MAIN_CONTENT part. Currently my application is only one page, and all my custom logic that belongs to that page is in one JS file. In this JS file, I use a simple $(function() { ... to load my page, so whenever it gets loaded, parts of my page get updated asyncronously. This is fine, since all my blocks in this certain page would have to be loaded when that one page gets loaded.
But what if I have a link, like main.html#otherscreen, and when I click that screen, I would like to change my MAIN_CONTENT and also run another page load specific JS that handles blocks on that other screen, not the first page?
I know I could still use probably server side templating and load my pages using AJAX requrests, but again, not sure whether that is the right approach.
Could you please enlighten me? :)
Thanks & best regards,
Bence
Check out jQuery.load(). Using this function you can dynamically load content into a div on the page, which is what I think you want to do. Just find the div on the page you want to load content into and call
$('#mydiv').load(url, data, function(response){
//do something once it's done.
});
Per your comments...
This is actually very easy. .load() should replace the content in the div (I think. If not, just call .empty() first). Of course you could get fancy and add effects, like
function changePages(url) {
$('#mydiv').fadeOut('fast', function() {
$(this).load(url, function(response){
$('#mydiv').fadeIn('fast');
});
});
}
To handle things like the hash in the URL, in your click event you have to make sure you first call e.preventDefault():
$('#mylink').click(function(e){
e.preventDefault(); //e is a jquery event object
var link = $(this);
var hash = link.attr('href'); // get the hashtag if the href is '#something'
changePages(someUrl + hash);
});
For dynamic loading of data into the page without changing your header and footer you should use jQuery's AJAX function. It allows you to post requests to the server and receive data back without reloading the page. A simple example would be something like:
<html>
<head>
<title>Example</title>
<!-- Assuming jQuery is already referenced -->
<script type="text/javascript">
$('span.buttonish').click(function(){
$.ajax({
// The URL can be a file or a PHP script of your choosing
// it can also be pure HTML without the <html> tags as they
// are already in your file
url: 'path/to/the/file/that/return/data',
success: function(receivedData) {
// The received data is the content of the file or the return
// data of the script and you can use it as you would with any data
$('#content').html(receivedData);
}
});
});
</script>
</head>
<body>
<div id="header">
<!-- Something -->
</div>
<div id="content">
<span class="buttonish">Click me to change the text... </span>
</div>
</div id="footer">
<!-- Something -->
</div>
</body>
<html>

Categories

Resources