400 error while making http request in javascript - 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);
}

Related

How to update URL from request response using 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.

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();

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.

Is a get request possible with javascript?

I was wondering if it was possible to make a GET request with javascript, so it can update text without refreshing the page.
If this is possible, how can I make a get request with javascript & get the result/decode it from json?
I tried this from a past question:
function updateButton(){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", false);
xmlHttp.send(null);
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
}
And, it completely stops the main thread, making the website unresponsive. What is wrong?
Currently you set the async parameter to false, so the request is sent to the server and the browser waits for the response. To make an async request, just pass true as thrid param to open
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
in addition to that, you have to register an callback, which waits for the response (and maybe to handle errors..)
xmlHttp.onload = function (e) {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
console.log(xmlHttp.responseText);
} else {
console.error(xmlHttp.statusText);
}
}
};
xmlHttp.onerror = function (e) {
console.error(xmlHttp.statusText);
};
In addition to that a note from the mozilla docs
Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 /
SeaMonkey 2.27), synchronous requests on the main thread have been
deprecated due to the negative effects to the user experience.
var isAjax=false;
function updateButton(){
if(!isAjax) { //Stops the user making a million requests per minute
isAjax=true;
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
xmlHttp.send(null);
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
isAjax=false;
}
}
OR jQuery...
$("#btnUpdate").click(function(){
$.get("http://xxxx.com/getSpecialSale.php", function(data, status){
$("#dicebutton").html(data);
});
});
If you want to use async you will need some code modifications, ie the stuff that happens after the response completes needs to be in a callback function as follows:
function updateButton(){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
xmlHttp.onload = function () {
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
};
xmlHttp.send(null);
}

Ajax request but no content

I'm trying to create an Ajax request and then parse the response header to get the "Location" attribute. This is my code :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 301) {
alert('test');
var header = request.getResponseHeader('Location');
console.log(header);
}
}
request.open('GET', hrefAttr, true);
request.send(null);
The problem is that for some reason, the request is send and the response is received too (red "GET" request+response in Firebug), but I don't get any "test" alert nor any text in the firebug console.
EDIT: This is the modified code :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if(request.readyState <= 3 && request.status == 301) {
alert('test');
var header = request.getResponseHeader('Location');
console.log(header);
}
else if (request.readyState == 0 && request.status == 301) {
alert('state0');
}
}
request.open('GET', hrefAttr, true);
request.send();
console.log(request.readyState) gives this sequence of states : 1, 1, 2, 4.
In the Firebug console tab the Http Request+Response show fine but in red (if that means anything).
Not sure why I it isn't working...
Edit : I'm using Firefox.
Thanks in advance !
Unfortunately, the XHR will follow the 301 and return the content of the redirected page. You can see the behavior documented at the W3C here.
If the XMLHttpRequest origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.
So basically, your request is following the 301 transparently. The browser is automatically redirected and you are unable to do what you intend to do. If you have control over the web server, this can be changed (albeit, against most advice).
Hope this helps!

Categories

Resources