get full html source code of page through ajax request through javascript - javascript

The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();

data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script

Related

Send PHP Variable with Ajax Call

I wrote a PHP application that makes an AJAX call (XMLHttpRequest) and is called every 5 seconds. The page called makes a database query. However, I need a variable from the main page and am unable to find a solution to attach it to the Ajax call.
Using $_GET seems a bit too insecure to me. Is there another way here?
This is my first expierence with ajax so please dont be to hard with me :)
Here is my Ajax Call
const interval = setInterval(function() {
loadText() }, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.'&name='.$_SESSION['name'].'&org='.$_SESSION['org'];?>', true);
xhr.onload = function() {
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText; }
})
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
// console.log(xhr);
}
Ill hope i provided enough Information
WIsh u all a great weekend
You do not need sending session variables at all: those are already known to the called page, because it can share the session information of the calling page.
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?= $role ?>'
is enough, provided that "table_view.php" issues a session_start() command.
I have fixed your code; It's here:
(Note: \' means that the character ' doesn't closing the string.)
const myInterval = setInterval(function(){loadText();}, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.\'&name=\'.$_SESSION[\'name\'].\'&org=\'.$_SESSION[\'org\']; ?>', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText;
}
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
}

Ajax blob type recognition javascript

I'm using javascript to download multiple files from a webpage.
I'm using FileSaver.js to save the file and this method to download :
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}
};
xhr.send(null);
}
together I'm using it like that :
downloadFile(imgurl, function(blob) {
saveAs(blob, "image" + item + ".jpeg");
});
but the problem is im not sure what is the image/video type and the links arent specifying them. (cant take extention from url there's none)
My main issue is recognition between videos and images, probably mp4/png but I prefer being able to determine each file type so I can save it with its extention.
thanks in advance

How to add custom header in ajax request using plain javascript (NOT JQUERY)?

Please could someone advise on how to add a header to an AJAX request using plain javascript? I am trying to upload a video file to a server and want to let it know the file size and type of the file I am sending.
I found someone solutions but this involved jQUERY which is not what I am after.
For example:
Content-Length: 339108
Content-Type: video/mp4
My AJAX request:
var startUpload = function(){
var formdata = new FormData();
formdata.append('requestUpload', 'uploadTicket');
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = xmlhttp.responseText;
if(response == '1'){
document.getElementById('UploadBox').innerHTML = '<div id="upWrap"><input type="file" id="vidInput"><button id="submitFile" onclick="">Upload Video<button></div>';
}
}
}
xmlhttp.open('POST', 'myFile.php');
xmlhttp.send(formdata);
}
You can use setRequestHeader method of XMLHttpRequest:
var xmlhttp = new XMLHttpRequest();
xmlhttp.setRequestHeader('Content-Type', 'video/mp4');
xmlhttp.setRequestHeader('Content-Length', '339108')
You must call it after calling open(), but before calling send()
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', url, true);
xhr.setRequestHeader('accept', 'application/json, text/plain, */*');
And not all headers canbe set, refer this
Forbidden_header_name
Tip:
Server side should Also support Cross-Origin Resource Sharing (CORS), like Access-Control-Allow-Origin

Pinterest pins through HTML/JavaScript

I Have been using pins to get the information of a pin from pinterest.
The following is the script being used:
<script type="text/javascript">
function getresponse1()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids="+{Pin ID});
alert(xmlHttp.status);
var data=xmlHttp.responseText;
var jsonResponse = JSON.parse(data);
var pin_url="www.pinterest.com/pin/"+pin_id+"/";
var page_name=(jsonResponse["data"][0].pinner.full_name);
alert(page_name);
}
</script>
Whenever XMLHttpRequest() method is being invoked the status returned is always 0 and the xmlHttp.responseText is empty.
But when the link is opened in a browser the response is correct and has all the information of the pin.
EDIT:
Tried implementing cross domain too. But yet the status returns 0.
New Script:
<script type="text/javascript">
function getresponse1()
{
var xhr = new XMLHttpRequest();
var url="https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=308074430730714588";
if ("withCredentials" in xhr) {
xhr.open("GET", url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
alert(xhr.status);
var data=xhr.responseText;
}
</script>
Please let me know where i'm making mistake. Thanks in advance
Note: I'm using Chrome browser
This is an general issue, as you try to do an ajax request to a different site (cross domain).
This isn't an new issue at all, I think here it is well explained and this posts provide also some thoughts about possible solutions.
AJAX is asynchronous, so your data will only be available from some kind of callback.
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(request.responseText);
}
};

XMLHttpRequest does not send file

I want to upload a file trough a XMLHttpRequest. i have looked everywhere for examples and found quite a few. But i cant figer out what it is i am doing wrong. This is my code. The function is triggerd when a button is pressed. It not wrapped in from tags
function upl_kost() {
var url = "proces_data.php?ref=upload_kost";
var hr;
var file = document.getElementById("file_kost");
var formData = new FormData();
formData.append("upload", file.files[0]);
if (window.XMLHttpRequest) {
hr=new XMLHttpRequest();
} else {
hr=new ActiveXObject("Microsoft.XMLHTTP");
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "multipart/form-data");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(formData);
}
and this function catches it.
if($_GET['ref'] == 'upload_kost') {
var_dump($_FILES);
}
My problem is that the $_FILES stays empty. When i look at the file.files variable in the js its loaded with the data from the file that i am trying to upload.
Thanks!
Reduce your JavaScript down to minimum required for this, then add in some helpful messages you can look in your console for
function upl_kost() {
var xhr = new XMLHttpRequest(),
url = 'proces_data.php?ref=upload_kost',
fd = new FormData(),
elm = document.getElementById('file_kost');
// debug <input>
if (!elm)
console.warn('Element not found');
else if (!(elm instanceof HTMLInputElement))
console.warn('Element not an <input>');
else if (!elm.files || elm.files.length === 0)
console.warn('<input> has no files');
else
console.info('<input> looks okay');
// end debug <input>
fd.append('upload', elm.files[0]);
xhr.addEventListener('load', function () {
console.log('Response:', this.responseText);
});
xhr.open('POST', url);
xhr.send(fd);
}
If you're still having a problem, it may be server-side, e.g. are you performing a redirect before trying to access $_FILES?
Your problem is that you're setting the content type of the request
hr.setRequestHeader("Content-type", "multipart/form-data");
If you ever saw a multipart/formdata post you'll notice the content type header has a boundary
Content-Type: multipart/form-data; boundary=----webko2354645675756
which is missing from your code.
If you do not set the content type header the browser will correctly set it and the required boundary. This will allow the server to properly parse the request body.

Categories