jquery load page fragment loading double div ids - javascript

$('#cart').load('shop.php/ #cart');
So i want to reload the cart section of my page but it is loading it inside the original div id like so:
<div id="cart">
<div id="cart">
// everything loaded fine here
</div>
</div>
I just want it to display the one div, what am i doing wrong?

You do everything correct. However, loading of page fragments in jQuery works as follows:
$('#result').load('ajax/test.html #container');
When this method executes, it retrieves the content of ajax/test.html,
but then jQuery parses the returned document to find the element with
an ID of container. This element, along with its contents, is inserted
into the element with an ID of result, and the rest of the retrieved
document is discarded.
So it will include the container as well. To include the inner contents only use the following:
$("#cart").load("shop.php/ #cart > *");​​​​​​​​​​​

Related

Unable to getElementById() after inserting HTML from a file using innerHTML

I have a quiz app with a series of questions implemented as a slide-deck. The deck is played in a single-page application (SPA). I have the HTML for each slide in a folder and it is loaded into a div container in the index.html file that is the single entry-point.
I use the id of the placeholder div tag in index.html and the innerHTML property to load a slide. The slide is rendered correctly on the page and inspection of the page source shows that the HTML was correctly loaded (i.e. as HTML and not text). However, I am unable to find the HTML elements within the inserted HTML with getElementById() in the application's code. It is as if they don't exist.
Here is the code that loads the HTML to display a slide. It runs when DOMContentLoaded.
fetch('./Slides/Quiz001.html')
.then(data => data.text())
.then(html => document.getElementById("Question").innerHTML = html)
.then([].slice.call(document.getElementsByTagName("div"))
.forEach(div_element => console.log(div_element.id)));
The first line fetches the slide to insert from a local folder. The second line gets the HTML string. The third line inserts the HTML into the page at the DOM insertion point. The fourth line queries all the div elements and converts HTMLCollection to array and the fifth line logs the IDs to console.
The HTML in Quiz001.html is as follows:
<div id="Quiz">
<h3>Patanjali Yoga Sutra</h3>
<div id="Expected" data-answer="asmina"></div>
<p>The five kleshas, the root cause of suffering, are avidya,
<input type="text" id="response" data-binding="response">,
raga, dvesa and abhinivesa.
</p>
</div>
There are two div elements in here, with id's "Quiz" and "Expected". These do not appear in the list logged to console by the javascript. In fact, after the insertion, I am unable to get any element in the inserted HTML by querying with getElementById() or any other method. It is like they are not visible in the code although the HTML is properly inserted and the elements are correctly seen in page source.
I have added a screenshot of the page and console, and highlighted the HTML that is inserted by javascript. Any help is appreciated.
.then([].slice.call(document.getElementsByTagName("div"))
This line is evaluated immediately, not as part of the Promise chain. You forgot the ()=> to make it a callback.

Changing HTML content on menu item click

I am trying to change the content of the yellow area when the user clicks on 'Dashboard', 'customers' etc: Here is the template I used
First I tried to change index.js I gave an id to div area:
$('.icon-dashboard').on('click', function() {
$("#area").load("secondpage.html #area > *");
});
This didn't work for me. Any suggestions to change the content between main tags?
Your selector for the load command is wrong. Your HTML shows a <main> tag with <div class="helper"> so you would want to use $("main .helper").load(...) to load content into "helper". Or, if you want to replace the "helper" div with whatever comes back from .load, just do $("main").load(...).
Also, passing "secondpage.html" to .load() is only going to work in the local browser. I'm assuming you're only doing that because you're testing? Ultimately, you'll need some backend script at an URL to return your content.

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

Inject script inside ajax loaded div

I'm using Jquery in my site and I have a div with content loaded by ajax, like an iFrame. With my code I can access the content and even change the class and values, but I can't insert a script to be executed.
There is the code:
<script>
$("#loginsb").click(function () {
$('#curso')
.contents()
.find('#script').jQuery("<script>").prop("tagName")
.attr('src', load.js);
});
</script>
My ajax loaded div is curso and inside this div I have another div script where I placed the the script line - without the src. Is the only way I knew to use more than one script in my page and find just one of them.
Inside Curso div
<div id="script">
<script></script>
</div>
Any idea to attribute this src inside my div script? Thanks!
You miss some basics in understanding Javascript and jQuery.
First thing: you can only have one element with id="script" and in your example you have one script element inside it.
So you can target that script element inside the script id element using jQuery:
$('#script script')
Then adjust the source of the script:
$('#script script').attr('src', 'load.js');
(Note the quotation marks around load.js. this is a string literal not a variable or constant.)

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>

Categories