Javascript change div content - javascript

My site has a one <div> for the header, one for navigation-panel and one for the content.
For the navigation-links i use
<p class="blue"><label onclick="goFor('test')"> -> TEST! <- </label> </p>
and my JS:
function goFor(destination)
{
document.getElementById("content").load(destination+'.php');
}
in this case, the content-div should change to the file "test.php".
but Firebug says: document.getElementById(...).load is not a function
what am i doing wrong?

Use $("#content").load(something) instead of document.getElementById.
Or... make an ajax request and load answer in that div.
For an ajax request with no lib, you can check my script here (first answer): Insert external page html into a page html. Note the success handle as you want it... with document.getElementById.

Related

Can jQuery replace text with JavaScript that is then executed

I have a page with headers, images, etc. I'd like to replace a "page" div with another file of HTML, JavaScript, etc using Ajax and execute JavaScript on that page after it is loaded. How do I do this and also handle < , ", and other tags in the file and pass the page some parameters?
Is the other "page" content owned by you? If so, you can have javascript methods on your main "container" page, then once you fire the method to pull the contents of the new "page" div, fire the corresponding javascript method you need, since any necessary DOM elements will have been added to the page at this time.
To do it the way you mentioned, you can follow the steps seen here to use the dynamic script pattern: Executing <script> inside <div> retrieved by AJAX
Basically, you host your javascript externally, then once the page has loaded, add the "src" tag to a script element and it will execute.
As for handling special characters, you can follow steps with jQuery's ajax call to inject HTML from the other page into your current one, such as here: How to get the html of a div on another page with jQuery ajax?
$.ajax({
url:'http://www.example.com/',
type:'GET',
success: function(data){
$('#ajaxcontent').html($(data).find('body').html());
}
});
(Instead of targeting a specific div on the external page, you would target the body or parent container div)
given an html page
<html>
...
<body>
<div class="page">
some html content...
</div>
</body>
</html>
you can replace the content of the div via the jQuery function load()
$("div.page").load("an-http-resource.html");
Use an AJAX request to get the HTML file as a response.
Replace the "page" div innerHTML with the response.
If the HTML page has a bunch of headers and such and you only want a certain portion of that HTML file, you may want to use getElementById or some other method of selecting the portion of the HTML file.
The HTML entities will appear as they normally would in a browser, if that is what you mean by handling < and " and other tags.
You can send parameters by editing the endpoint:
index.html?date=today&car=yours

Clear innerHTML of dynamically loaded elements with jQuery

Everything i have read, leads more to event handlers being added using .live(), .on(), .bind(), .delegate(), etc..
I asked a question earlier that may not be coming across correctly, so i voted to delete that one and re-ask a much simpler one, from which i can do the rest i believe.
Is there a way to clear the innerhtml of an HTML element with a predefined class, including those loaded dynamically via AJAX, etc.
So every time an ajax call puts
<div class="triggerElement">something here...</div>
or similar on the page, i need it to be emptied. I think i have explained that correctly. Just let me know if not.
EDIT
Seems to be a lot of confusion. .empty & others like it will not work. If you call
$(".omButton").empty();
from the index, then some other module loads something later via AJAX with that same class, it WILL NOT empty that. If i have the element on the page first, then call it, yes it will work....
I need something along the lines of .live or .delegate that will work for any content loaded after the fact, as i have tried .empty and .html and neither work for the content that is loaded with AJAX.
Not sure how else to explain this. Thought it was pretty simple. Sorry!
EDIT 2...
index contains empty function
$(function(){
$('.omButton').empty();
$ajax... to load "loadedContent"
});
<div class="omButton"></div>
<div id="loadedContent"></div>
ajax returns
json_encode(array('test' => '<div class="omButton">Button Text</div>'));
So now the HTML on the index is
<div id="loadedContent"><div class="omButton">Button Text</div></div>
However since the inner div was not there when the page loaded, the .empty does not effect it. I need something that i can put on the page load that "monitors" for any occurance (static or dynamic) of it and empties it.
Hopefully that helps?
Try using $.ajaxComplete() - as this is triggered after every ajax request completes
$('body').ajaxComplete(function() {
$('.triggerElement').empty();
});
Try this. .empty
$.ajax({
...
complete: function(){
$(elementSelectorForWhatYouWantEmptied).empty();
}
})
or if the element that is loaded is dynamically placed in the DOM, then you can use .live().
$(elementThatIsInDOM).on(event, elementSelectorThatIsDynamicallyAdded, function(){
$(elementSelectorForWhatYouWantEmptied).empty();
})
If you're loading content using ajax, and that content is a full on tag with content
<div class="triggerElement">something here...</div>
And you want to empty that element after it is loaded, you need to do that within the callback which gets executed when the data is loaded.
$.ajax(
....
success: function(data){
$(".omButton").empty();
});

Javascript doesn't recognise items entered into DIV Using XMLHttpRequest

Having searched the site, I think the issue I'm having may relate to using innerHTML to populate a <div> but I can't quite find a solution that I can map onto my specific issue. Hope someone can help. Basically, I have an HTML page that contains a form with a text field. The page also contains an empty <div> which will be populated with a table-of-contents in a moment. The <div> is defined as:
<div id="toc_menu" class="menu_list">
I've set the onkeyup attribute of the form text field to run a Javascript function (defined in the HTML <head>) which defines a XMLHttpRequest and sends the value entered in the text input field (str) to a PHP page using xmlhttp.open("GET","toc_items.php?filter="+str,true). The PHP page GETS the value of 'filter' and runs a MySQL query. It then produces some results which are echoed back to the empty as a table-of-contents with main headings and subheadings using:
document.getElementById("toc_menu").innerHTML=xmlhttp.responseText;
This works more-or-less as expected. The length of the returned table-of-contents changes as text is entered into the text field. There is, however, a problem. This table-of-contents is supposed to have an accordion effect created using a script which is defined in the HTML <head>. The script was developed by Roshan Bhattarai and works beautifully when the table-of-contents list is hard-coded into the HTML page. The script is as follows:
<script type="text/javascript">
<!--
//---------------------------------+
// Developed by Roshan Bhattarai
// Visit http://roshanbh.com.np for this script and more.
// This notice MUST stay intact for legal use
// --------------------------------->
$(document).ready(function()
{
//slides the element with class "menu_body" when paragraph with class "menu_head" is clicked
$("#toc_menu p.menu_head").click(function()
{
$(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({backgroundImage:"url(left.png)"});
});
});
</script>
The table-of-contents items that are formatted as follows:
<p class="menu_head">HEADING</p>;
<div class="menu_body">;
SubHeading';
</div>;
It appears that the table-of-contents items that are inserted into the <div> don't trigger the Javascript in the HTML page <head> (although the text is formatted correctly using CSS files also defined in <head>). I can manually copy the output from the PHP page and paste it into the <div> and the accordion effect works perfectly.
Any suggestions would be greatly appreciated.
It appears that the code block:
<p class="menu_head">HEADING</p>;
<div class="menu_body">;
SubHeading';
</div>;
is echoed back by PHP from the ajax call. Correct me if I'm wrong on that. If the ajax call builds this html and echos it to the screen, the above script will not work. The ajax call is made via the keyup event on the form as you stated above. However, the script above is run on
$(document).ready. If what I'm understanding is true, the content is placed in the innerhtml of the div when the ajax call is made not when the page loads. Because there are no "p" elements with the class "menu_head" when the page loads on $(document).ready, jquery cannot bind the .click event properly. The script needs to be executed after the ajax call returns and the DOM has been updated with the new elements.
In other words on successful return from the ajax call, run the above script, not on $(document).ready. Once the elements are in the DOM, jquery can find them and bind to them the .click event. The script execution should then complete successfully.
Hope this helps.
I haven't studied your code in detail, but did notice your empty div element has no close tag (unless you've omitted this detail). You should always have a close tag (for div elements) to ensure the DOM doesn't make an invalid assumption as to where this should be inserted, use:
<div id="toc_menu" class="menu_list"></div>

How to append the HTML results of a URL call to the DOM?

I have a URL that resides on another domain, like this:
http://ads.adserver.com/ad?site=1233&zone=45435
When you type this URL in the browser, the result is HTML like this:
<img src="htt://ads.adserver.com/i/image.gif" border="0"/><br/>Test
The above renders as an image wrapped in a link with a second link below it.
I tried to capture this URL in a script tag and append it to the DOM, but it does not render the HTML above.
var ad_script = document.createElement('script');
ad_script.type = 'text/javascript';
ad_script.src = 'http://ads.adserver.com/ad?site=1233&zone=45435';
li.appendChild(ad_script);
Are there any other ways of invoking this URL and putting the result on the page? I can't use $.getScript() since I'm not invoking this in the global context. I need this HTML to appear exactly where I want it to appear.
EDIT: The only reason I am trying this route is that the third-party does not provide a JSON-P interface.
EDIT2: Unfortunately, I am not on an application server.
EDIT3: This is for iPhone.
You are limited to how you load this due to cross-domain issues .. an easy way would be to load the image in it's own iframe
<iframe src='http://ads.adserver.com/ad?site=1233&zone=45435' height='200px' width='200px' />
You'll want to use ajax for this. The easiest way might be jQuery's .load() method.
Assuming the element you want the content to go into has an id of holder, you would do
('#holder').load('http://ads.adserver.com/ad?site=1233&zone=45435')
It will put the contents of the webpage into your selected element. http://api.jquery.com/load/
edit: Sorry, forgot cross-site ajax limitations. You could instead set up a php page like:
if(isset($_GET['url'])){
echo file_get_contents($_GET['url'])
}
and then do
('#holder').load('http://yoursite.com/yourpage.php?url=http://ads.adserver.com/ad?site=1233&zone=45435')
Take the jsonp approach. use an actual script tag and put an executing javascript function as the response that adds that html markup to the dom. It will add it to the dom of the page where the script tag resides.
There are a number of jQuery ajax calls that can accomplish this, for example:
jQuery.get('http://ads.adserver.com/ad?site=1233&zone=45435', function(data){jQuery(updateElementQuery).html(data);});
Try to use jquery method 'load'
`$('#result').load(url, function(response) {
$('#my-li').append($('#result').html());
$('#result').html(null);
});`
... where #result is some hidden div

In jQuery, how to load ajax content after a specified element

I have the following HTML:
<div id="mydiv">
</div>
I would like to load content using jQuery so it appears after my DIV.
I've tried this:
$("#mydiv").load("/path/to/content.html");
However, this ends up with this result:
<div id="mydiv">
<p>content from file</p>
</div>
How do I get this result?
<div id="mydiv">
</div>
<p>content from file<p>
Anyone still looking for solution, I would suggest using jQuery.get() instead of .load() to load AJAX content. Then use .after() function to specify the preceding element.
Here's an example:
$.get('url.html', function(data){ // Loads content into the 'data' variable.
$('#mydiv').after(data); // Injects 'data' after the #mydiv element.
});
Use the after function.
I have one interesting but rather hard and difficult for understanding method, but using .load function. So, code:
$('#div_after').remove();
$('#mydiv').after($('<div>').load('/path/to/content.html #div_after', {
data: data, //variables to send. Useless in your case
}, function () {
$(this).children().unwrap();}
));
See, I put .remove() method to remove previously created div if you use this code more than once. You can delete first line if it will be used just once.
The idea is .after($'') creates noname div element on the page after #mydiv and .load() the html into it with callback-function
$(this).children().unwrap();
which is logically will unwrap into our noname div and "rename" it to our #div_after from loading html. It is also unnecessary if you wish using just noname div.
Cheers!
P.S. It took me a while in a project to combine all this stuff together :) I wish it would be useful.
with the after(content) function

Categories