Remove HTML Elements from JQuery AJAX load() Response - javascript

Is there a possibility to remove specific HTML Elements from a AJAX (load) Response before placing in to the container? In this case I want to remove the "#containerTop", including content, from the response.
Response (HTML):
<html>
<head></head>
<body>
<div id="containerMain">
<div>...</div>
<div id="containerTop">Content-to-remove-including-container-div...</div>
</div>
</body>
</html>
I've tried this, without success.
<div id="middle"></div>
<script>
$( "#middle" ).load( "http://<URL>",
function(response, status, xhr){
$response.remove('#containerTop');
});
</script>
Any ideas?

.load() inserts the content directly for you. It does not give you an opportunity to modify it before it is inserted. As such you have two options:
You can modify the content after it is inserted, but before it is painted in the .load() completion handler.
You can switch to .get() to get the content as data, then put it into a jQuery object, then modify it using jQuery methods, then insert the modified content into your page yourself.
Here's an example of the second option:
$.get("http://<URL>", function(data) {
var temp = $(data);
temp.find('#containerTop').remove();
$('#middle').empty().append(temp);
});

response.find(element).remove()
This works with me

Related

Using .load in JavaScript

I am using .load() function in JavaScript and I'm working with JSP java files. I am loading a page like this in JavaScript
$("#body").load("livestatus #status")
The problem is the div I'm trying to load doesn't load immediately on page load because it contains some data from APIs, so there's a one second delay but my code doesn't accommodate that delay.
Try to put your code in document.ready block or if you are making an ajax request then put your code in Ajax success function
If you use jQuery and it just not initialized for some element, you can use
$(function() {
$("#body"). // ... your code
});
If it calls through some time and you can't track when exactly, you can use live listeners on some event. Like, click on this element.
$("body").on("click", "#body", function() {
// your code
});
$("body") can contain any parent element which had loaded before jQuery.
Or you can load 1px image with you code which loads after main code and track when it will load.
<div id="body">
<!-- your markup -->
<img class="loading-status-img" src="../path_to_1px_small_image.png" style="display:none">
<img class="loading-status-img-2" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII=" style="display:none">
<!-- your markup -->
</div>
<script>
$("body").on("load", ".loading-status-img", function() {
// execute you code here after #body will load
});
</script>
The second image is encoded with base64.
[UPD] old version of jQuery have another syntax. More: http://api.jquery.com/live/

Can't access elements loaded via ajax using jQuery

I need to modify content loaded via ajax, but can't seem to access it. I don't have access to the js file that is doing the initial load so I need to write a separate function to change the content.
The content needs to be modified automatically WITHOUT the user clicking or interacting with anything on the page.
In the example below the 'news' div is hard coded and the 'article' divs are loaded via ajax.
HTML
<div id="news">
<div class="article"><img src="headline1_small.jpg">
<div class="article"><img src="headline2_small.jpg">
<div class="article"><img src="headline3_small.jpg">
</div>
jQuery
$(document).ready(function() {
console.log( $("#news").html() );
});
Console
<div id="news">
</div>
How can I access the articles? I want to remove '_small' from the img src.
Thanks!
This should work:
$(document).ajaxStop(function() {
$("#news").find('img').attr("src", function(_, src){
return src.replace('_small', '');
});
});
How can I access the articles? I want to remove '_small' from the img src.
For example like this:
$('#news .article img').attr('src', function() {
return this.src.replace('_small', '');
});
You can execute this code on AJAX successful completion
$(document).ajaxSuccess(function() {
// above code
});
You said the article divs are loaded through AJAX, seems that this script is running before they are loaded. Try putting this script after #news so all the content is already loaded when it is executed.
<div id="news">
<div class="article"><img src="headline1_small.jpg">
<div class="article"><img src="headline2_small.jpg">
<div class="article"><img src="headline3_small.jpg">
</div>
<script>
$(document).ready(function() {
console.log( $("#news").html() );
});
</script>
To remove "_small" from src of the img tag, there is another way for that. you dont need to get access to the html() -> innerHTML of the #news div.
all you could do is get hold of the all the ".article" div's and then alter the img tag.
$(".article img").each(function() {
$(this).attr('src', $(this).attr('src').replace("_small", ""));
});
Thanks

Load HTML within AJAX call

I'm having some difficulty with a Javascript function I am writing. The basic function of the script is that when a specific AJAX function is called and returns successful, it loads some HTML from a file and inserts that HTML into a on the main page and then (once loaded), fades in the parent div.
jQuery.ajax({
type: "POST",
url: "fns/authenticate.php",
data: dataString,
success: function (data) {
if (data=='1') {
jQuery("#authlogin").fadeOut(500, function(){
$(this).remove();
jQuery("#result").load("fns/logic.html", function() {
jQuery('#authtrue').fadeIn(1000);
});
});
} else {
jQuery('#details-error').fadeIn(200);
}
}
});
return false;
Now the AJAX seems to function properly, in that it will execute under the correct conditions and fade out and in the correct divs, the problem seems to be that the content isn't being loaded from logic.html or it is not being bound to the #result div correctly.
The main page's html looks like:
<div id="authlogin">
<!-- HTML form -->
</div>
<div id="authtrue" style="display: none;">
<div id="result"></div>
</div>
Any help would be much appreciated.
This is one of those things that you must troubleshoot yourself, because we do not have access to your fns/logic.html and therefore cannot test fully.
However, some thoughts:
(1) The basic logic of your .load() success function seems correct. Here is a jsFiddle that approximates the AJAX success function's logic. I substituted .html() for .load() because jsFiddle cannot do ajax. Anyway, assuming that .load() is doing what it should, that part should be working.
(2) You may already know this, but note that .load() is shorthand for $.ajax() -- as are .post() and .get(). You might find $.ajax() easier to troubleshoot as the code block is more structured. As a general rule, troubleshooting the shorthand constructions is slightly more abstract/difficult than troubleshooting $.ajax()
(3) Use developer tools in Chrome (press F12 key) to verify that the contents of logic.html have been inserted into the #result div. You might find, as I did in playing with my jsFiddle, that the contents were injected but the #authtrue div remained hidden. At least you will know that the logic.html document has been found and contents inserted. Knowing exactly where the problem is, finding/fixing the rest might now be trivial.
(4) Does your logic.html file include unnecessary header information? If so, you can strip it out by only inserting the BODY of the document, or a top-level containing div. See this section of the jQuery docs:
jQuery("#result").load("fns/logic.html #container", function() {//CALLBACK IN HERE});
(5) It would be a smart idea to create a test document that just and only loads the logic.html document, using various methods:
Method A: Using PHP (or whatever server-side language you use)
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"><?php include 'logic.html'; ?></div>
</div>
Method B: Using load()
HTML:
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"></div>
</div>
jQuery:
jQuery('#authtrue').show();
jQuery("#result").load("fns/logic.html");
(6) Ensure you do not have a typo in the destination element jquery selector: If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent. (from the docs)
I managed to fix this myself, thanks to the help of everyone here. It ended up being a browser caching problem. As soon as I cleared the cache everything magically worked.

jQuery $.post and searching in the resulting HTML

I have the following code:
$.post(
url,
send_to,
function(data) {
console.log($(data).find("img");
}
);
I'm getting some result from server and want to find the src value of img tag in that result HTML code, but it's not working.
How I can search for the img tag in the received data?
Your code should work fine. The jQuery function ($(data)) will turn a valid HTML string into a (decoupled) Node tree.
Be aware, though, that find() searches through the descendants of the element or collection of elements on which it is called. If your <img> is in the top level of the HTML, use filter() instead. For example:
<!-- Returned HTML: -->
<p>Here's a nice image of a kitten:</p>
<img src="demonic_kitten.png" />
<p>Muhahahaha!</p>
/* JavaScript (callback function): */
var success = function(data) {
console.log($(data).filter("img");
};
If the <img> is not in the top level, make sure the data that is returned is valid HTML and contains an <img> in the first place.
It's difficult to see where you might be going wrong without some idea of what the data variable contains in terms of HTML. If you're sure it's just an IMG tag that's being returned from the AJAX request, using find will attempt to search through your IMG tag for another IMG altogether, and should be adjusted to this:
console.log($(data).attr("src"));
If it's not just an IMG tag being returned in your HTML, and is a bunch of different tags, I would suggest wrapping your HTML in something like a DIV tag before it's sent back to the Javascript, for example if you're returning something like:
<p>Something</p>
<p>Something else</p>
<img src="something" />
<p>Something</p>
...rather return something like this:
<div>
<p>Something</p>
<p>Something else</p>
<img src="something" />
<p>Something</p>
</div>
...which would also make your original code work. I would also think about adding the dataType option to your jQuery AJAX request:
$.post(
url,
send_to,
function(data) {
console.log($(data).find("img");
},
"html"
);
Hope this helps! :)

Make a specific div load last

I'm trying to make a page where a certain div (with lots of php, html and javascript content) loads after the rest of the page. Is this possible if so how?
You could apply this div a hidden style and then use javascript to show it:
$(function() {
$('#someDiv').show();
});
But if you want to avoid loading it initially you could use AJAX:
$(function() {
// <div id="container"></div> will be an empty div
$('#container').load('/script');
});
Also note that if you want this loading to happen once all other content is loaded including graphics you could use the $(window).load instead of $(document).ready:
$(window).load(function () {
...
});
I had a similar Issue, needed the data to be filled in after a certain div was created.
I use .ejs files for this stack.
What I did was Pull all the code to the .ejs page Ordering it in the way I needed.
For Ex.
<script type="text/javascript">
jQuery making the divs
</script>
<% Pull Data and put it in the divs above %>
look in to jQuery's $.ajax, and related functions. I think you'll find they're exactly what you're looking for. a simple example:
<script type="text/javascript">
$(function() { // called when page is done loading; you can have lots of these
$.ajax({
url: 'other-content.php',
success: function(data) { $('#load-me-later').html(data); }
});
});
</script>
<div id="load-me-later"></div>
The certain
<div id="the_div">some text or whatever</div>
must have
#the_div { display:none; }
in css.
An then
$(document).ready(function() {
$("#the_div").show();
});
There are several ways to do this. For one, you could put that div at the end of the page and flush() just before it; but this isn't very reliable, and it's pretty darned hard to get position and the likes right. A better way would be ajax:
$.ajax({
url: 'myurl.php',
data: someDataMaybe,
success: function(html) {
$('#mydiv').html(html); // document.getElementById('mydiv').innerHTML = html would be a thousand times faster, but I've been told jquery people like this more
}
});
this will only execute after page load and then load the contents into the div. It of course assumes myurl.php outputs only content that should be in said div.
So say you have this page:
<div id="page">
<div id="content">
<!-- lotsa stuff in here -->
</div>
<div id="mydiv"></div>
</div>
<script type="text/javascript">
// the stuff above ^
</script>
And myurl.php outputs this:
Some PHP-generated stuff
which would result in:
<div id="mydiv">Some PHP-generated stuff</div>

Categories