How to update URL from request response using javascript? - javascript

I have a JavaScript function that is attempting to closely emulate a form submit.
function fopen() {
var xhr = new XMLHttpRequest();
xhr.open("POST", open_url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
create: 0,
jobtype: jobtype,
name: document.getElementById("file-selector").value
}));
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.write(xhr.responseText);
}
else {
console.log('ErR0r')
}
}
}
The behavior is close to identical, but the URL is not being updated after the response. I see there is an xhr.responseURL attribute but how can I actually get this to show in the address bar? And is there an exact full JavaScript implementation of form submit I can refer to in order to keep things as similar as possible?

To change the page's URL, set window.location.href.

Related

PHP functionality ($_[value]) in Javascript

I have been trying to get a php code to work through an ajax call but it doesnt seem to work (even though its posting and etc) when im simply assigning a value. I know the php code works when I just put it directly on the page but I want this to load after a button is pressed. My question is what would be the javascript equalivant to doing:
$_['dog'] = 'red';
Update:
the value 'dog' is already a value , the php code is simply changing it to 'red' for clarification. And the ajax call since I just wanted the code to be run this was my call :
function ajaxPost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("success");
}
};
xhttp.open("POST", "https://linkto.com/lan.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
ajaxPost();

400 error while making http request in javascript

I ctrl+c the part of Max Payne Wiki article(it's just an exmaple of any text):
just a screenshot of how I copy part of the article
Then I ctrl+v this stuff into <textarea> in my site(not in the code, but literally in the site-rendered <textarea>)
The the runs the next javascript code:
SomeParagraphElement.innerText=document.getElementById('my_txtarea').value;
requestp("aga.php?data="+SomeParagraphElement.innerText, callback_function);
where requestp is
function requestp(path, run)
{
var request = new XMLHttpRequest();
request.open('GET', path, true);
request.addEventListener('readystatechange' ,function()
{
if ((request.readyState==4) && (request.status==200))
run( request.responseText);
}
);
request.send(null);
}
After this there should be a data uploaded to sever, but it doesn't happen and if I just write stuff from keyboard by my fingers and even insert emojis - all works fine.
Google Chrome debug window says, that I make a 400 HTTP error. I tried
var str= SomeParagraphElement.innerHTML.replace(/(?:\r\n|\r|\n)/g, '%0A'); and another %blahblah symbol, but it doesn't change anything.
If I make a new line by myself by pressing 'enter', via keyboard it works fine.
What should I do?
Yeah, if I pass data more the 2048 bytes, I have to use POST request. Here is a function, maybe it will be helpfull for someone
function requestp(path, data, callback)
{
var request = new XMLHttpRequest();
request.open('POST', path, true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');//specify this!
request.addEventListener('readystatechange' ,function()
{
if ((request.readyState==4) && (request.status==200))
callback( request.responseText);
}
);
request.send(data);
}

JavaScript: How to "refresh" data from same URL?

Having this API:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
How can I write using pure JS request that downloads me different data after button click event?
All I get from this code is the same quote all the time:
function getQuote (cb) {
var xmlhttp = new XMLHttpRequest();
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && this.readyState==4) {
cb(this.responseText);
}
};
xmlhttp.open("GET", quoteURL, true);
xmlhttp.send();
}
document.querySelector('button').addEventListener("click", function() {
getQuote(function(quote) {
console.log(quote);
});
})
I tried xmlhttp.abort() and stuff but it didnt want to cooperate.
Thanks in advance!
Your response is being cached by the browser. A common trick to avoid this is to perform a request to
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
Notice how the r={random_number} will make the URL different each time.
This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.

When changing html via element.innerHTML='text' it doesn't work

For the last hour or so, I've been trying to solve a problem, which came up when I tried to change html of an element from XMLHttpRequest.
xhr.open('GET', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(document.getElementById('notifications-navbar').innerHTML);
document.getElementById('notifications-navbar').innerHTML = xhr.responseText;
console.log(xhr.responseText);
console.log(document.getElementById('notifications-navbar').innerHTML);
} else {
console.log('error');
}
};
xhr.send();
The output of the console logs were:
pastebin
So in the console.log we can see the change to the innerHTML was made, however there is no change whatsoever when I have a look on the elements via Chrome inspect and also there is no change in the browser. I even tried to remove every other JS scripts that were being loaded and just make a simple change of the innerHTML outside of XHLHttpRequest, but that didn't help too. Please if you could help I would be really happy.
Not sure what your EndPoint URL is , but I wrote this for you and it works just fine. Hope this can help you!
HTML
<div id = "notifications-navbar"></div>
Javascript
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "http://jsonplaceholder.typicode.com/posts";
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(document.getElementById('notifications-navbar').innerHTML);
document.getElementById('notifications-navbar').innerHTML = xhr.responseText;
console.log(xhr.responseText);
console.log(document.getElementById('notifications-navbar').innerHTML);
} else {
console.log('error');
}
};
xhr.send();
Okay, sorry guys, I found my mistake, I had in my HTML two elements with ID notifications-navbar and only the first one was being changed. Thanks for your help anyway.

Is it possible to add Request Headers to an iframe src request?

I understand that you can set HTTP request headers very easily when making AJAX calls in JavaScript.
However is it also possible to set custom HTTP request headers when inserting an iframe into a page via script?
<iframe src="someURL"> <!-- is there any place to set headers in this? -->
You can make the request in javascript, setting any headers you'd like. Then you can URL.createObjectURL(), to get something suitable for the src of the iframe.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'page.html');
xhr.onreadystatechange = handler;
xhr.responseType = 'blob';
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
// this.response is a Blob, because we set responseType above
var data_url = URL.createObjectURL(this.response);
document.querySelector('#output-frame-id').src = data_url;
} else {
console.error('no pdf :(');
}
}
}
The MIME type of the response is preserved. So if you get an html response, the html will show in the iframe. If you requested a pdf, the browser pdf viewer will kick in for the iframe.
If this is part of a long-lived client-side app, you may want to use URL.revokeObjectURL() to avoid memory leaks.
The object URLs are also pretty interesting. They're of the form blob:https://your.domain/1e8def13-3817-4eab-ad8a-160923995170. You can actually open them in a new tab and see the response, and they're discarded when the context that created them is closed.
Here's a full example: https://github.com/courajs/pdf-poc
No, you can't. However you could set the iframe source to some kind of preload script, which uses AJAX to fetch the actual page with all the headers you want.
As #FellowMD answer is not working on modern browsers due to the depreciation of createObjectURL, I used the same approach but using iframe srcDoc attribute.
Retrieve the content to display in the iframe using XMLHttpRequest or any other method
Set the srcdoc parameter of the iframe
Please find below a React example (I know it is overkill):
import React, {useEffect, useState} from 'react';
function App() {
const [content, setContent] = useState('');
useEffect(() => {
// Fetch the content using the method of your choice
const fetchedContent = '<h1>Some HTML</h1>';
setContent(fetchedContent);
}, []);
return (
<div className="App">
<iframe sandbox id="inlineFrameExample"
title="Inline Frame Example"
width="300"
height="200"
srcDoc={content}>
</iframe>
</div>
);
}
export default App;
Srcdoc is now supported on most browsers. It seems that Edge was a bit late to implement it: https://caniuse.com/#feat=iframe-srcdoc
It turns out that URL.createObjectURL() is deprecated in Chrome 71
(see https://developers.google.com/web/updates/2018/10/chrome-71-deps-rems)
Building on #Niet the dark Absol and #FellowMD's excellent answers, here's how to load a file into an iframe, if you need to pass in authentication headers. (You can't just set the src attribute to the URL):
$scope.load() {
var iframe = #angular.element("#reportViewer");
var url = "http://your.url.com/path/etc";
var token = "your-long-auth-token";
var headers = [['Authorization', 'Bearer ' + token]];
$scope.populateIframe(iframe, url, headers);
}
$scope.populateIframe = function (iframe, url, headers) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'document';
headers.forEach(function (header) {
xhr.setRequestHeader(header[0], header[1]);
});
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
var content = iframe[0].contentWindow ||
iframe[0].contentDocument.document ||
iframe[0].contentDocument;
content.document.open();
content.document.write(this.response.documentElement.innerHTML);
content.document.close();
} else {
iframe.attr('srcdoc', '<html><head></head><body>Error loading page.</body></html>');
}
}
}
}
and shoutout to courajs: https://github.com/courajs/pdf-poc/blob/master/script.js

Categories

Resources