how to get specific information from url html source code - javascript

I am trying to get the information from a url links html source code onto another webpage which is in the same domain and get specific information from the html code, like getting the span id, and information from a <td>
and change the internal html code <span id="myspan"> here is my text </span>
to that of what I get.
the code I have below is not working, not sure why
function loadHTML(spanId, url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 /* complete */) {
handler(xmlhttp.responseText, spanId);
}
}
}
function handler(responseText, spanId) {
var parser =new DOMParser();
var doc = parser.parseFromString(responseText, "text/html");
//get class name from parser
var status = doc.getElementsByTagName("tr");
var className = status[1].className;
//get the date/time from parser
var tds = doc.getElementsByTagName("td");
var dateTime = tds[0].innerText;
var span = document.getElementById(spanId);
span.id= className;
span.innerHTML = dateTime;
}
loadHTML('myspan',"any given url");
<span id="myspan"> here is my text </span>

after xmlhttp.onreadystatechange you need to call xmlhttp.send() to start the http request
correct code is here
function loadHTML(spanId, url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 /* complete */) {
handler(xmlhttp.responseText, spanId);
}
}
}
// send() method actually initiates the ajax request
xmlhttp.send();
function handler(responseText, spanId) {
var parser =new DOMParser();
var doc = parser.parseFromString(responseText, "text/html");
//get class name from parser
var status = doc.getElementsByTagName("tr");
var className = status[1].className;
//get the date/time from parser
var tds = doc.getElementsByTagName("td");
var dateTime = tds[0].innerText;
var span = document.getElementById(spanId);
span.id= className;
span.innerHTML = dateTime;
}
loadHTML('myspan',"any given url");
<span id="myspan"> here is my text </span>

Related

What causes the "419 unknown status" error in this Laravel 8 application?

I am making a blogging application with Laravel 8 and Bootstrap 5. It has a user profile management system.
I want to enable every user to add and delete her/his avatar. For this purpose, I have a deleteavatar() method in my UserController controller:
public function deleteavatar($id, $fileName)
{
$current_user = Auth::user();
$current_user->avatar = "default.png";
$current_user->save();
if (File::exists(public_path('images/avatars/' . $fileName))) {
File::delete(public_path('images/avatars/' . $fileName));
}
}
In the routes file:
Route::group(['prefix' => 'user'], function() {
Route::get('/', [UserController::class, 'index'])->name('user');
Route::match(['get', 'post'],'/update', [UserController::class, 'update'])->name('user.update');
Route::post('/deleteavatar/{id}/{fileName}', [UserController::class, 'deleteavatar'])->name('user.deleteavatar');
});
I use this piece of JavaScript to call the above method:
function deleteAvatar(e) {
e.preventDefault();
var avatar = document.querySelector('#avatar-container img');
var topAvatar = document.querySelector('#top_avatar');
var trashIcon = e.currentTarget;
var defaultAvatar = APP_URL + '/images/avatars/default.png';
//Get user's ID
var id = trashIcon.dataset.uid;
var fileName = avatar.getAttribute('src').split('/').reverse()[0];
var url = APP_URL + `/dashboard/user/deleteavatar/${id}/${fileName}`;
if (confirm('Delete the avatar?')) {
var CSRF_TOKEN = document.querySelectorAll('meta[name="csrf-token"]')[0].getAttribute('content');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
avatar.setAttribute('src', defaultAvatar);
topAvatar.setAttribute('src', defaultAvatar);
trashIcon.remove();
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.send();
}
}
document.querySelector('#delete-avatar').addEventListener('click', deleteAvatar);
The problem
For a reason I have been unable to find out, the Chrome console throws this 419 (unknown status).
What is my mistake?
set xmlhttp header for csrf token
function deleteAvatar(e) {
e.preventDefault();
var avatar = document.querySelector('#avatar-container img');
var topAvatar = document.querySelector('#top_avatar');
var trashIcon = e.currentTarget;
var defaultAvatar = APP_URL + '/images/avatars/default.png';
//Get user's ID
var id = trashIcon.dataset.uid;
var fileName = avatar.getAttribute('src').split('/').reverse()[0];
var url = APP_URL + `/dashboard/user/deleteavatar/${id}/${fileName}`;
if (confirm('Delete the avatar?')) {
var CSRF_TOKEN = document.querySelectorAll('meta[name="csrf-token"]')[0].getAttribute('content');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
avatar.setAttribute('src', defaultAvatar);
topAvatar.setAttribute('src', defaultAvatar);
trashIcon.remove();
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.setRequestHeader("X-CSRF-TOKEN", CSRF_TOKEN);
xmlhttp.send();
}
}
document.querySelector('#delete-avatar').addEventListener('click', deleteAvatar);
Ref:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
Ref: https://laravel.com/docs/9.x/csrf
Laravel is returning http status 419 because of missing csrf token. Add the csrf token in a HTML meta tag and add to your ajax request header as well.
For reference: https://laravel.com/docs/8.x/csrf#csrf-x-csrf-token

JavaScript Handlebars give no error but does not work

I am trying to replace text in my page using handlebars. But its not working and i am not getting any errors either.
The following code kicks in when the user presses the submit button
<button type="submit" id="add_lunch" class="button button-contactForm boxed-btn" onclick="addToCart()">Submit</button>
this then
function addtoCart() {
var request = new XMLHttpRequest();
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = $("input[name='dessert_id']:checked").val();
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var template = Handlebars.compile(document.querySelector('#js_result').innerHTML);
var data_response = JSON.parse(request.responseText);
var content = template({'base_name': data_response.base.name});
console.log("****" + data_response.base.name)
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#add_lunch').onclick = () => {
document.querySelector('#media_js_body').innerHTML += content;
};
});
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
return false;
}
plus the template
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script id="js_result" type="text/x-handlebars-template">
{{ base_name }}
</script>
<script src="{{ url_for('static', filename='js/util.js') }}"></script>
What i have figured out so far is that it has something to do with DOM state? and onclick even.
Any suggestions and corrections?
i do not know if it was the coffee i drank, but after a few sips and few changes it seems to work partially now. i am getting the text being placed in the right place.
Now i only have to make sure that the values from data_response gets transferred in content as well
This is what i changed.
function addToCart() {
var request = new XMLHttpRequest();
var limit=2;
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = [];
$.each($("input[name='side_id']:checked"), function(){
side_id.push($(this).val());
});
if(side_id.length==limit) {
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var data_response = JSON.parse(request.responseText);
var templateInfo=document.querySelector('#js_result').innerHTML
console.log("TempInfo:" + templateInfo)
var template = Handlebars.compile(templateInfo);
var content = template({'base_name': data_response.base.name});
console.log("DataResponse:" + data_response.base.name);
console.log("Content:" + data_response.base.name);
document.querySelector('#media_js_body').innerHTML += content;
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
} else {
alert("Kindly select "+limit+" sides")
}
return false;
}

settimeout not getting called?

I have a javascript which call a server and get a JSON data which contains some config to enable/disable redirecting to another link. I need to delay the redirection by a few seconds, but it seems that setTimeout() is not getting called in my method. Even if I change redirect() as an anonymous function and pass it in setTimeout it is still not getting called.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {
function redirect(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);
// set global object for using it inside the settimeout function
var redirect;
and then inside the xhr.onreadystatechange = function() {
redirect = function(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
setTimeout('redirect()',3000);
Thanks for all the suggestions. I have improved it as per suggestion by talsibony, and I further found out also that document.write() removes all my content, which makes it unable to find the redirect global variable. So I have instead changed it to add a div element and set the innerHTML. Here is the fixed code in case if someone encountered similar issue.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;
xhr.onreadystatechange = function() {
redirect = function(){
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
var div = document.createElement("div");
document.body.insertBefore(div, document.body.firstChild);
div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

Vanilla javascript: Get a specific element of page in an ajax get request

I'm trying to get #test1 from another page and append it to #test3 of the main page. This is what I have done so far:
<div id="test3"></div>
var request = new XMLHttpRequest();
request.open('GET', '//jsbin.com/wemowe', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(resp,"text/xml");
var tds = xmlDoc.getElementById("test1");
console.log(xmlDoc);
document.getElementById('test3').innerHTML=tds.innerHTML;
} else {}
};
request.onerror = function() {};
request.send();
Here is JSBin
Any suggestion to make it work?
The doc type is causing the issue here.
var xmlDoc=parser.parseFromString(resp, "text/xml");
change it to:
var xmlDoc=parser.parseFromString(resp, "text/html");

Extract Title from web page, using just the url

I want to replicate some functionality from Digg.com whereby when you post a new address it automatically scans the url and finds the page title.
I am programming in classic ASP and VBScript and using javascript. Anyone know a script to make this happen..?
Many thanks in advance..
Paul
This is somewhat of a rudimentary example. You should probably include some data verification.
The ASP page should be called something like getPageTitle.asp
<%
Response.Buffer = True
Dim strURL, objXMLHTTP, objXML, strContents
Dim objRegExp, strHTML, strPattern, colMatches, strTitle
strURL = Request.Form("url")
Set objXMLHTTP = Server.CreateObject ("Microsoft.XMLHTTP")
'Or if this doesn't work then try :
'Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXMLHTTP.Open "GET", strURL, False
objXMLHTTP.Send
strContents = objXMLHTTP.ResponseText
Set objXMLHTTP = Nothing
Set objRegExp = New RegExp
strPattern = "<title>(.*?)<\/title>"
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
Set colMatches = objRegExp.Execute(strContents)
If colMatches.Count > 0 then
strTitle = objMatches(0).Value
Else
strTitle = ""
End If
Set objRegExp = Nothing
Response.write(strTitle)
%>
This is a basic JavaScript POST implementation. You could spruce this up a bit with any JS framework you like.
var script = "http://www.example.com/getPageTitle.asp"
var page2check = "http://www.example.com/somePageToCheck.html"
function getXMLHttpRequestObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = new getXMLHttpRequestObject();
var parameters = "url="+page2check;
http.open("POST", script, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters .length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
alert(http.responseText);
}
}
http.send(parameters);
var pageTitle = http.ResponseText
I hope this helps.
Send url from clientside to serverside using javascript(ajax).
Load html page by it's url using asp on serverside.
Parse html page, extract title.
Send title to clientside.

Categories