I have HTML and I need to get page source of this html.
document.documentElement.outerHTML
or
$.ajax({
async: true,
type: 'GET',
cache: false,
url: window.location.href,
success: function(data) {
alert(data);
}
});
is working, but they display originally source. If I change html (by jQuery, for example), they don't read my changes.
Is it possible read CURRENT source of page?
Tried it on chrome and it works. Use
document.documentElement.innerHTML
Funnily enough your code also worked
document.documentElement.outerHTML
Check out the html printed to the console in this fiddle. It actually contains the changes made by jQuery.
Using jQuery you can do this by:
$( 'body' ).html();
For example.
Or convert to String:
$( 'body' ).html().toString();
You just need to grab the element and use the html method:
$('.selector').html();
Simple solution, source of a document usually embedded in html tag
so use $('html').html(), you will get everything between html tags.
Related
I'm trying to load a PHP file into another PHP file on a click event through Ajax. I'm trying to do this to eliminate loading several modals I have on the page. It seems the PHP file is loading (in the console), but nothing is showing up.
Here's my javascript:
$("a#lightbox-open").click(function(e){
e.preventDefault();
$("body").addClass("noscroll");
$('section#lightbox').addClass("open");
$.ajax({
context: '#lightbox-holder',
url: '/template/lightbox.inc.php',
type: 'POST',
dataType: "json",
success: function(html){
alert("works");
}
});
});
In my main PHP file, I have a div #lightbox-holder that lightbox.inc.php is supposed to load into it.
context expects a (Plain)Object (as you can read in the api doc). Replacing '#lightbox-holder' by $('#lightbox-holder') will do the trick.
Working fiddle with the $() added versus non working fiddle representing your current code.
In Javascript, to add text to an already existing div I would use
document.getElementById("container").innerHTML = document.getElementById("container").innerHTML + "Text";
So that the text that is already present in the div wouldn't be deleted and to be able to reset what is written in the div by just using:
document.getElementById("container").innerHTML = "Text";
But, since I'm using jquery to load the text from a txt file with
$( "#container" ).load( "text.txt" );
That doesn't seem possible.
I'm not a big expert on neither JS or Jquery, but is there a way to mix the two to still be able to reset the text in a div or add text to it, while still fetching that text from an external file?
Hope I've been clear enough in explaining what I'm trying to do
Try using AJAX to fetch your data but not populate it:
$.ajax({
url: 'text.txt',
success: function(text){
document.getElementById("container").innerHTML += text;
}
});
Ajax is a lot more full featured - it's the 'harder' cousin of load(), so you can also add an error catcher (as well as a raft of other things):
$.ajax({
url: 'text.txt',
success: function(text){
document.getElementById("container").innerHTML += text;
},
error: function(e){
document.getElementById("container").innerHTML += 'Data could not be loaded! (' + e.statusText + ')';
}
});
You can learn more about AJAX at jQuery docs: http://api.jquery.com/jquery.ajax/
First of all:
You run the risk of loading a file, which may or may not be available. Meaning you could get a file load error. In order to stick with jQuery I would leverage AJAX to load the file like so:
JQuery code:
$(document).ready(function() {
$.ajax({
url : "text.txt",
dataType: "text",
success: function (data) {
data.appendTo("#container")
},
error: function(e){
// Show some error, for example:
alert("Data failed to load from text.txt file")
}
});
});
I believe that appendTo will be a much simpler version of what you've tried to accomplish via document.getElementById("container").innerHTML in order to replace the text. Give it a try and modify this to work exactly as you like. Let me know if you have any questions about it.
To make it clear to you, JQuery is an extension of the existing JavaScript language. Meaning, you can always use your JavaScript within your perceived JQuery code. You can learn how to use the strengths of JQuery to support your JavaScript code with added functionality, a great example of one is the AJAX implementation of file loading you see here. To learn more visit: Learn JQuery.
I'm loading an svg through ajax with jquery like so:
$("body").load("https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg");
Which loads just fine, but replaces all the content in the body. What I want it to do is prepend the loaded svg, so the svg does not replace everything but is inserted as the first element after <body>.
Use $.get() then do prepend in the callback:
$.get( "https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" )
.done(function( data ) {
$("body").prepend($(data).find("svg"));
});
Well, you cannot just place an image retrieved into body like so.
If you want to display image, just show it via img tag.
If you retrieve data, you can use something like this:
$.get("https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" )
.success(function(data) {
$("body").prepend(data.activeElement.innerHTML);
});
The reason why your initial variant "worked" by showing an entire picture is that browsers can display image files, and your code just did that - the same would be if you just drag-n-drop an image into browser window.
Try this:
$.ajax({
url:"https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg",
method: "GET",
dataType: "html",
success: function(data) {
$("body").prepend(data);
}
})
You have to adjust the datatype in case you want to get different content (e.g. xml/json elements).
Works with your example - svg is right below the body and before your #svg div.
Try following code I checked it and working fine.
$("#svg").load("https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg");
What I'm trying to do seems simple: get an HTML page through $.ajax() and pull out a value from it.
$(function () {
$.ajax({
url: "/echo/html",
dataType: "html",
success: function (data) {
$('#data').text(data);
$('#wtf').html($(data).find('#link').text());
},
data: {
html: '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a id="link">content<\/a><\/li><\/ul><\/body><\/html>'
}
});
});
The problem is that jQuery refuses to parse the returned HTML.
The fiddle I'm play with this in isn't working in the mean time, so there's little else I can do to provide a working example.
UPDATE: My new fiddle is working fine, but it seems the problem is that in my actual project I'm trying to parse a large, complex bit of HTML. Is this a known problem?
Your code works fine. You just aren't using jsFiddle's API correctly. Check the docs for /echo/html/ (http://doc.jsfiddle.net/use/echo.html#html):
URL: /echo/html/
Data has to be provided via POST
So, you need to update your AJAX call to use POST. Also the trailing slash is needed.
$(function () {
$.ajax({
url: "/echo/html/",
type: "post",
dataType: "html",
success: function (data) {
$('#data').text(data);
$('#wtf').html($(data).find('#link').text());
},
data: {
html: '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a id="link">content<\/a><\/li><\/ul><\/body><\/html>'
}
});
});
DEMO: http://jsfiddle.net/hcrM8/6/
If you would like to parse it, jquery has a nifty trick :)
ParsedElements = $(htmlToParse);
Console.log(ParsedElements);
You now have DOM elements you can traverse without placing them in the body of the document.
jQuery.parseHTML()
http://api.jquery.com/jQuery.parseHTML/
str = "hello, <b>my name is</b> jQuery.",
html = $.parseHTML( str ),
nodeNames = [];
// Gather the parsed HTML's node names
$.each( html, function( i, el ) {
nodeNames[ i ] = "<li>" + el.nodeName + "</li>";
});
Some thing is wrong with your ajax on fiddle
http://jsfiddle.net/hcrM8/5/
var html= '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a class="disabled" id="link">content<\/a><\/li><\/ul><\/body><\/html>';
h = $.parseHTML(html);
$('#data').text(h);
$('#wtf').html($(h).find('#link').text());
Why don't you just use the load method?
$( "#wtf" ).load( "/echo/html #link" );
Or, here's your fiddle fixed and working:
http://jsfiddle.net/hcrM8/4/
I had the same problem and i fixed encapsulating requested html code into just one container element.
Bad Example:
Linkname
<p>Hello world</p>
Jquery couldnt convert this to element, because it wishes to convert a single element tree. But those are not having a container. Following example should work:
Right Example:
<div>
Linkname
<p>Hello world</p>
</div>
All answers do not point to the real problem, jQuery seems to ignore the head and body tag and creates an array of nodes. What you normally want is, extract the body and parse it.
Take a look at this helpful answer, I do not want to copy his work: https://stackoverflow.com/a/12848798/2590616.
I am facing the same problem, and it is not because you are doing something wrong.
it's because the "link" tag is not supposed to have any innerHTML returned, it's explicitly excluded in jquery, you will find some where this line:
rnoInnerhtml = /<(?:script|style|link)/i,
This tag in HTML is supposed to link to external style sheet.
I want to make a few divs on the same page work similar to iframes. Each will load a URL which contains links. When you click on those links I want an AJAX request to go out and replace the div's html with new html from the page of the clicked link. It will be very similar to surfing a page inside an iframe.
Here is my code to initially load the divs (this code works):
onload:
$.ajax({
url: "http://www.foo.com/videos.php",
cache: false,
success: function(html){
$("#HowToVideos").replaceWith(html);
}
});
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$("#HowToProjects").replaceWith(html);
}
});
This is a sample of code that I'm not quite sure how to implement but explains the concept. Could I get some help with some selectors(surround in ?'s) and or let me know what is the correct way of doing this? I also want to display a loading icon, which I need to know where the right place to place the function is.
$(".ajaxarea a").click(function(){
var linksURL = this.href; //
var ParentingAjaxArea = $(this).closest(".ajaxarea");;
$.ajax({
url: linksURL,
cache: false,
success: function(html){
$(ParentingAjaxArea).replaceWith(html);
}
});
return false;
});
$(".ajaxarea").ajaxStart(function(){
// show loading icon
});
Assuming you want to listen to click events for all anchor tags inside all elements with class ajaxarea, then your selector works fine:
$(".ajaxarea a").click(function(){ .. });
And this line of code, while not a selector (you're just accessing a property on the DOM element that was clicked), should work fine as well:
var linksUrl = this.href;
As for ParentingAjaxArea, you'll need to use $(this).closest() with a selector to determine which parent you want, but it's hard to give a specific example without knowing your HTML structure. It looks like you want ParentingAjaxArea to be either the element with id #HowToProjects or #HowToVideos, so you could write:
var ParentingAjaxArea = $(this).closest("#HowToProjects, #HowToVideos");
As for the loading dialog, I think this answer explains a good method (using ajaxStart and ajaxStop).
Edit: I also noticed you're using the click event--If you plan on being able to attach event handlers to links that will be inserted into the DOM via AJAX later, look at delegate or live.
$(".ajaxarea a").live('click',function(e){
e.preventDefault(); //*
var URL = $(this).attr('href');
var parentFrame = $(this).parent(".ajaxarea"); //**
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.replaceWith(html); //***
}
});
});
* - added preventDefault to prevent click action (see e in function's arguments)
** - instead of closest, i used parent – like it more for it's descriptive qualities
*** - the var containing parent AJAX frame should be jQuery object, no need to wrap it in $(..)
This should work fine, but beware, it's untested.
edit:
You probably need a live (okay, I'm sure you need it). what click() does it's that it adds to all elements at the time in DOM an onClick event. What live() does, it's that it waits for any change in DOM and runs used selector (.ajaxarea a) again and if it fits for any of new elements, it adds the action. In pseudocode, it does basically this:
DOM.hasChanged{
$('selector').click(..)
}
I used this example for my own web page:
http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp
It works quite well and uses hash tags and jQuery.history.js for the history of your browser. It works very nice, because you can let something like a media player just continue playing. Take a look at my own site elsewise, where you can find the javascript file: ajaxpages.js. I haven't used live(), but maybe I should.
Figured it out! The problem was I was using the function ".replacewith()" which was removing my AJAXed div(class="ajaxarea") entirely instead of replacing the content. The proper function to use here was ".html()".
Here is my working code to make an AJAXed div work like an iframe:
//onload to initialize the div
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$('#HowToProjects').html(html);
}
});
$(".ajaxarea a").live('click',function(e){ // must use live instead of .click()
e.preventDefault();
var URL = $(this).attr('href');
var parentFrame = $(this).closest(".ajaxarea");
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.html(html);
}
});
});