Repair/fix invalid HTML using Javascript/jquery - javascript

I want to use content(some div) on the page.
So I request the the page using AJAX. Since I want to use some div (by ID), I have written the following code but the problem is the HTML that gets returned from the delete1.aspx is faulty so I can not convert it to XML
$('#one').click(function () {
$.ajax({
url: 'http://localhost:51967/delete1.aspx',
success: function (data, status, xhr) {
var temp = $.parseXML(data);
$('#arjunvachhani').html($(temp).find('#id1').html());
}
});
});
I have tried to put it on some hidden div so that browser will correct it and then retrieve that div, but in that case, the browser will request css and js and some other images which is changing appearance of my page(where I put the retrieved HTML). It is also very slow
One more problem "I can't change the delete1.aspx file"

If it's valid HTML, but not valid XML, try:
var temp = $('<div/>', { html: data });
$('#arjunvachhani').html(temp.find('#id1').html());

Related

AJAX Post HTML Code

I'm having an issue with sending some HTML code using AJAX please see my code below
<iframe src="http://www.w3schools.com" width="10" height="10" id="awc_frame"></iframe>
<script>var iframe = document.getElementById("awc_frame");</script>
Here is the AJAX code below
<script>
$.ajax({
type: "POST",
url: "mobileView.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
})
</script>
The code isn't sending the variable to the PHP file. Looking into the Network side of things it sends text ie if I put "" around iframe it sends this code
"val = iframe" but not the actual code within the iframe. The "var iframe"does work and pulls back the HTML code of the iframe
Please tell me what I'm doing wrongly.
Thanks in advance.
EDIT: I'm sorry. It's not the HTML code within the iFrame I need to send, It's the entire iFrame code I need to send.
Another Edit: What I'm trying to accomplish when a visitor from my company goes to my website I would like Javascript or Jquery to load an internal website from the visitors computer and then have all of the code from that website that's on the client's end to be sent to a Server which will store the entire iFrame code in a database.
This would send the entire html inside the iframe.
var iframe = $('#awc_frame').html();
First of all, var iframe does not contain HTML of the iframe element - it contains a DOM Node, which is kind of a wrapper around the iframe element (it contains various properties of that element, including the HTML).
Next thing, you probably want to wait for the iframe to completely load all the contents, so you'll have to bind to the load event of it.
Something like this should work:
var $iframe = $("#awc_frame");
$iframe.on("load", function () {
var iframeHTML = $iframe[0].contentWindow.document.body.innerHTML;
// jQuery alternative
var iframeHTML = $iframe.contents().find("body").html();
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: iframeHTML
},
success: function(data){
console.log(data);
}
});
});
Super important thing in this example
Just one more thing - please note that for websites outside of your own domain, this code won't work (due to Same Origin Policy). Any other code won't work too.
Since javascript has problems with getting the HTML from a cross-domain iframe, you can't do this across domains. However, why not just send the iframe's src attribute to the PHP page, and then just use file_get_contents to get the HTML, and then store that? Problem solved:
Javascript:
var iframe = $('#awc_frame').prop('src');
$.ajax({
type: "POST",
url: "posttest.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
});
PHP:
$html = file_get_contents($_POST['val']);
what are you trying to do?
var iframe = document.getElementById("awc_frame");
above code is an javascript object of your iframe which contains a lot of properties.. since you are using jQuery, you could get that with:
var iframe = $('#awc_frame');
keep in mind that above code is the element it self in jquery object format you could get element object like this:
var iframe = $('#awc_frame')[0];
** you're doing something wrong.
if you're trying to get iframe HTML content:
var iframe_contents = $("#awc_frame").contents();
if you explain more about what you are trying to do, i can update my answer to suit you.
* UPDATE *
considering what you are trying to do..
Method #1: (Easy Way)
you could use php to fetch content of the website you need:
<?php
$contents = file_get_contents('http://www.w3schools.com');
// Saving $contents to database...
?>
Method #2: (Hard Way)
as #mdziekon said, you first should wait until your iframe gets loaded then:
var iframe = $("#awc_frame");
iframe.on("load", function () {
var contents = $(this)[0].innerHTML;
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: contents
},
success: function(data){
console.log(data);
}
});
});
hope it solves your problem

jquery .load() does not load external JS

I am loading external content into a div element using jquery.load() without a selector. If the content loaded has embedded JS, the JS works as expected. HOWEVER, if the content includes a script tag with src=path-to-js-code the js-code is not loaded.
Am I correct in this observation and if so is there a good solution other than embedding the JS in the loaded content?
EDIT :
A few clarifications and observations:
To load the content I am using
$("#DivId").load("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking and post processing code
});
Changing the load code to:
$.get("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking
$("#DivId").html(response);
post processing
});
Does not seem to change the behavior (more on the behavior below)
I have not tried parsing the response to retreive the script src and then using getScript().
Now more on the behavior...
Using Firefox, it seems that the external JS is loaded but only if it has been about 2 min from the last load. I do not see an attempt in Firebug unless the refresh is about 2m after the last load of the external JS. (weird). When I was making JS code changes and hitting refresh, it was not loading my new code and thus the original question.
So i will withdraw my question in light of this clarified behavior (2m caching?).
Thanks.
Both the .load() and .html() jQuery methods utilise the .innerHTML property. This won't execute scripts added with <script> tag. Use a regular AJAX call e.g. .get() then in the callback use .append() to add your HTML string and the scripts will run once it's parsed e.g.
$.get("path/to/content.php", function(response, status, xhr) {
// error checking
$("#DivId").append(response); // Any <script> tags in the response string will execute
// post processing
});
Thing is you need to make sure you're running trusted code if it's added by .append()
I was wondering you can get the script src in the response text of $.load method with regular expressions, then use $.getScript() method to load the script, maybe something like this:
$("#DivId").load("path/to/content.php", function(response, status, xhr) {
var regexp = new RegExp('script.*?src="(.*?)"'),
execresults = regexp.exec(response);
if(execresults.length > 1)
{
// the first result is the entire match including
// the 'script..src=', so abandon it
var matches = execresults.slice(1);
$.each(matches, function(){
$.getScript(this, function(){
// do something after load script
});
});
}
});
Hope this can help
This is the easy way to load an external JS to your jQuery
$.ajax({
type: "GET",
url: "path/to/content.php",
dataType: "script"
success:CallbackFunction(response, status, xhr)
});

Get HTML source code as a string

I want the source code of an HTML page (1.html) to be used in another page (2.html). Furthermore, I want to perform operations on it in 2.html.
Is there a way to do this?
EDIT: 1.html is a separate public webpage and I do not have access to make changes to its source code. I have to do whatever I need only by using 2.html.
To get the DOM converted to a string:
document.getElementsByTagName('html')[0].innerHTML
Question: what do you mean by "use it"? Do you need to include 1.html inside 2.html? Or do you just need to process it?
Its very simple
On 2.html use this jQuery snippet
$.get("1.html", function(response) {
alert(response)
//do you operations
});
jQuery:
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
I don't understand whatyou mean that you must make modifications, but you could simply load the second page through AJAX
var url ="1.html";
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
}
});
Use can use .html method alternatively to get the entire html data of the page.
$(function(){
var a = ($('html').html())
})​
A realy simple and modern way is the follow:
fetch('1.html').then(function(response) {
/* when the page is loaded convert it to plain text */
return response.text()
}).then(function(html) {
/* initialize the DOM parser */
var initParser = new DOMParser();
/* parse the text */
var parse = initParser.parseFromString(html, 'text/html');
/* you can now even select part of that html as you would in the regular DOM */
/* example */
var docOutput = parse.querySelector('html').outerHTML;
console.log(docOutput);
}).catch(function(error) {
console.log('Error fetch page: ', error);
});

Why .html() method does not load data in the element?

$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").html("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").html(data_aj);
}
});
I really have tried everything but can't figure out whats wrong. If I use alert(data_aj); it gives the desired output and just works fine but HTML(data_aj) just doesnt loads into a <ul> element #list using .html(). Can anyone tell me why?
Have you tried putting your code in a document ready, as your alert will fire fine but if your dom is not loaded then you cannot append to it. Also use .append() for lists not html
$(document).ready(function() {
$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").append("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").append(data_aj);
}
});
});
Listen up...
$.get() is a shorthand for $.ajax().
So when you do this
$.get(uri, function(data){
//Your functionality
});
You're really doing this
$.ajax({
url: uri,
type: "GET",
success: function(data) {
//Your functionality
}
});
By default this returns the page as HTML. Or rather, by default, it first checks the MIME-type on the page, and if none is found, it returns HTML. As you are requesting a .txt file it will interpret it as a simple textfile. If you want to tell it what you would like to return (HTML), you can either do it in the MIME-type on the server page, or you could use $.getJSON().
An easy way to solve this is thus doing:
$.get(uri, function(data) {
//Your functionality
},
"html");
Which is the same as doing:
$.ajax({
url: uri,
type: "GET",
dataType: "HTML",
success: function(data) {
//Your functionality
}
});
Also it is not a good idea to use html() because you are replacing the existing html inside of your ul element every time you want to add an additional new node.
Try making use of:
$('#list').append('<li>' + data_aj + '</li>');
Basically you can just append the <li> to the <ul> itself.
Lastly make sure your dom has already been loaded by placing all your JQuery code into the
$(document).ready(function() {
//Your code...
});
Otherwise if your HTML is not fully loaded yet, your list might not exist yet so there is no way for JQuery to put some values into unexisting HTML.

jQuery selectors on an ajax response string that is a full html page

I'm trying to get some page details (page title, images on the page, etc.) of an arbitrarily entered URL/page. I have a back-end proxy script that I use via an ajax GET in order to return the full HTML of the remote page. Once I get the ajax response back, I'm trying to run several jQuery selectors on it to extract the page details. Here's the general idea:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function (data) {
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", data);
//doesn't seem to work even if there is a title in the HTML string
var name = $(data).filter("title").first().text();
var description = $(data).filter("meta[name='description']").attr("content");
}
});
Sometimes using $("selector", data) seems to work while other times $(data).filter("selector") seems to work. Sometimes, neither works. When I just inspect the contents of $(data), it seems that some nodes make it through, but some just disappear. Does anyone know a consistent way to run selectors on a full HTML string?
Your question is kind of vague, especially w/r/t what input causes what code to fail, and how. It could be malformed HTML that's mucking things up - but I can only guess.
That said, your best bet is to work with $(data) rather than data:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function(data) {
var $data = $(data);
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", $data);
//doesn't seem to work even if there is a title in the HTML string
var name = $data.filter("title").first().text();
var description = $data.filter("meta[name='description']").attr("content");
}
});

Categories