I am fetching a remote page's HTML and returning the HTML to review meta tags and I notice unexpected failed requests for all the remote assets in the other page's HTML whenever I assign that to a variable.
$.get(url, function(data, status) {
var dt = $(data);
}
By the time I've assigned that variable, it triggers all these remote requests.
How can I avoid the the fact that assigning this data to a variable in the DOM seems to trip a request for every image or resource on that remote page!
When you do $(data), jQuery ends up parsing the hTML and causes the requests to be made for the resources.
To get around it, use DOM parser so the resources are not fetched.
const myHTMLSource = `
<html>
<head>
<meta name="title" content="Foo Bar">
<meta name="description" content="FOO FOO">
<meta name="keywords" content="bar, egg, bacon">
<meta name="robots" content="index, follow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="English">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"><\/script>
</head>
</body>
<h1>Test</h1>
<img src="http://placekitten.com/200/300" />
</body>
</html>`;
const parser = new DOMParser();
const testDoc = parser.parseFromString(myHTMLSource, "text/html")
const metaTags = testDoc.querySelectorAll("meta");
console.log(metaTags.length);
Since being asked how to use in in the jQuery Ajax request, it just uses data:
var request = $.ajax({
url: url,
method: "GET",
dataType: "text"
}).done(function( data ) {
const parser = new DOMParser();
const testDoc = parser.parseFromString(data, "text/html")
const metaTags = testDoc.querySelectorAll("meta");
console.log(metaTags.length);
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
So you claim: GETTING the html results in the requests inside the result are executed when doing $(data). So the issue is to NOT use $(data) but the raw HTML but that means some kind of split on </head> BEFORE creating a DOM fragment
Try this:
Uncomment the comments and remove the string I use for testing
//$.get(url, function(data, status) { // uncomment
// const dt = data.split("</head>")[0]
const fragment = document.createElement("div");
// fragment.innerHTML = dt;
// test
fragment.innerHTML = `<html>\n<head>\n<meta name="title" content="Foo Bar">\n<meta name="description" content="FOO FOO">\n<meta name="keywords" content="bar, egg, bacon">\n<meta name="robots" content="index, follow">\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<meta name="language" content="English">\n<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"><\/script>`;
[...fragment.querySelectorAll("meta")]
.forEach(meta => {
console.log([...meta.attributes]
.map(attr => `${attr.nodeName}: ${attr.nodeValue}`))
})
//}}
Related
I have to generate a popup in flutter that is coming from backend in the html, css and javascript form
In my case I'm using a korean based software named Band that is going to provide me google, fb and band login.
It's working is something like passport.js just in my case I've to use band but the issue is that when I try to render the response, the flutter is treating javascript as string.
Band developers guide link
Using band api I have got the response in html and javascript, something like given below
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="keywords" content="BAND" />
<meta name="description" content="밴드 방문을 환영합니다. 로그인하고 그룹 멤버들과 대화에 참여해 보세요." />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>로그인 | 밴드</title>
<script type="text/javascript">...</script>
</head>
<body>...</body>
</html>
Preview of response using postman software
Code snippet I'm using in flutter to render the response is given below
Future getJSONData() async
{
var redirectUri = Uri.encodeFull("apiredirection.php");
var response = await http.get(
Uri.encodeFull(
"https://auth.band.us/oauth2/authorize?redirect_uri={TEST_URL}" +
redirectUri),
headers: {"Accept": "application/text"});
this.setState(() {
data = response.body;
return data;
});
return data;
}
#override
Widget build(BuildContext context)
{
String html = data.toString();
return new MaterialApp(
home: new Scaffold(
body: new Container(
child: new HtmlView(
data: html),),),),
}
If the response that you need to display is in html String, you can use webview_flutter to render this on your app with a WebView.
// Let htmlData contain the html response
String htmlData = '''<!DOCTYPE html><html>...</html>''';
await webViewController.loadHtmlString(htmlData);
Then set webViewController as the WebViewController of your WebView.
I want to send a JavaScript variable with a image that a user will upload to my Flask file where processing will be done. So I am using Formdata and a AJAX call for the same. But after the data and image is received in flask and processing is done, I am unable to render a HTML page in flask which will display the processed image .
Java Script Code :
formdata = new FormData();
jQuery("#image_to_upload").on("change", function() { // On Change Of image upload
var file = this.files[0];
if (formdata) {
formdata.append("file", file);
formdata.append("array", filtersActive);
jQuery.ajax({
url: "/object-detect-uploader",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success:function(){}
});
}
});
Flask Code :
#app.route("/object-detect-uploader", methods = ['GET', 'POST'])
def upload_object_detection():
detect_objs = request.values['array'].split(",")
d_array= [0 for i in range(6) ]
for i in detect_objs:
d_array[int(i)] = 1
for upload in request.files.getlist("file"):
filename = upload.filename
# This is to verify files are supported
ext = os.path.splitext(filename)[1]
if (ext == ".jpg") or (ext == ".png"): #File extention check
print("File supported moving on...")
ans=(object_detection_module.object_detection(upload,d_array))
else:
render_template("Error.html", message="Files uploaded are not supported...")
print("Rendering")
return render_template("index.html", result = ans)
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<br>
<br>
<h1><center>Output</h1></center>
<br>
<img src="data:image/png;base64, {{result[0]}}" >
<br>
<br>
<h2> No of objects = {{ result[1] }}</h2>
</body>
</html>
An Ajax call is an asynchronous request initiated by the browser that does not reload the page when it receives the server response.
IMO, since you want to render the template, you should not use AJAX, just use a normal <form> element or create a form programmatically, fill the data, then submit with jQuery('selector').submit().
I want to open the response that I get from my PHP server in the In App Browser in a new window.
I am creating an app using Ionic and using PHP as a back end. I have full control of the php server.
I am making the ajax call like so:
$(document).ready( function() {
$("#paybutton").click(function() {
var params = "projectpaymentoption=1197&id=",
usernamepay = window.localStorage.getItem("username"),
paymenturl = params + usernamepay;
$.ajax({
type: 'POST',
url: 'http://www.blabla.com/encode.php',
data: $.param({"paymenturl": paymenturl}),
success: function(output) {
window.open('output','_blank','location=no','closebuttoncaption=Zurück');
console.log(result);
}
});
});
});
Now I want to open the output in a new inappbrowser windows.
The output i am throwing out is as follows
<?php
ob_start();
include_once('includes/headers.php');
require_once('includes/connection.php');
require_once('includes/functions.php');
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
</head>
<?php
include($filePath);
?>
It is a dynamically generated php page. An not an url.
How can I show this page in the inappbrowser
I have the following HTML code in a file called test.html. Both the HTML file and the JSON file below are stored on a server within the same directory.
<!DOCTYPE html>
<html>
<head>
<title>Shape Up</title>
<meta name="robots" content="noindex,follow">
<meta name="description" content="">
<meta name="keywords" content="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="JavaScript" type="text/javascript">
function ajax_get_json()
{
var hr = new XMLHttpRequest();
hr.open("GET", "game.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = "";
for(var obj in data)
{
results.innerHTML += data[obj].title;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script language="JavaScript" type="text/javascript">
ajax_get_json();
</script>
</body>
</html>
It pulls data from a file called game.json which is stored in the same directory.
{
"level_001":
{
"id":001,
"title":"Level 1",
"difficulty":0,
"comments":"this is how you complete level 1"
},
"level_002":
{
"id":002,
"title":"Level 2",
"difficulty":0,
"comments":"this is how you complete level 2"
}
}
The problem is that the results.innerHTML = ""; line is never reached. Why?
There are no errors in the browser, I've checked this on Firefox and on Safari.
According to jsonlint.com your JSON is invalid because of these properties:
"id":001
...
"id":002
You need to either remove the leading zeros:
"id":1
or make the numbers strings:
"id":"001"
For further details see the format rules spelled out at json.org
Presumably the line you mentioned is never reached because JSON.parse() gives an error about the above. (Do you not see an error in the browser's console?)
I have a script here, copied pretty much directly off this. Why doesn't the code, listed below, return anything?
ajax.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cross-Domain Ajax Demo</title>
</head>
<body>
<div id="container">
<form>
<p><label>Type a URL:</label><input type="text" name="sitename" id="sitename"/></p>
<p><input type="submit" name="submit" id="submit" value="Make Cross Domain Ajax request"</p>
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="cross-domain-requests.js"></script>
<script type="text/javascript">
$('form').submit(function() {
var path = "www.google.com";
requestCrossDomain(path, function(results) {
$('#container').html(results);
});
return false;
});
</script>
</body>
</html>
cross-domain-requests.js:
// Accepts a URL and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no URL was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided URL, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
(I'm relatively new to scripting and Ajax, so I apologise in advance if I do anything stupid.)
Try changing the callback in var yql to callback=? and the select statement to 'from xml' like this:
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';