Confusion about ajax - javascript

There is a way to send or get request using ajax which allows to send data without page reload like everything happens behind the scene i found a script for doing that but some of the functions within aer confusing can anyone explain me what are they and why we are using those
data.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
data.onreadystatechange = function () {
if(data.readystate == 4 && data.status == 200) {
data.return_data = data.responseText;
document.getElementById("response").innerHTML = return_data;
}
}
data.setRequestHeader What is the use of this function and why we are using this
onreadystatechange same for this and not understanding why if condition is used
Help would be highly appreciated

You are using XMLHttpRequest to send/get the data.
The function setRequestHeader is used to set value of header params before sending request to server.
The condition if(data.readystate == 4 && data.status == 200) is used to check what is the status and state of request. By using if condition you can verify the success of your request and take needful action after success. Below is the list of possible status and state.
Possible states with description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
to see list of all possible status codes please refer to developer.mozilla.org

Related

How to use XMLHttpRequest while telling site to do something?

First of all I have to say that I have NO EXPERIENCE in Ajax and I just need this one explanation in order for me to create a simple chrome extension.
There is not much I could find on internet even tho I believe this is very simple.
I need a part of code where I would "call" url from website and I need to adjust certain arguments in that url.
Request URL:http://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE
Request Method:POST
Request Payload :
{amount: 1, user_id: 12345678}
amount: 1
user_id: 12345678
(this is something I get from Network panel- with url and token changed to real things - while calling url automatically from website, but I need to be able to call it manually too.)
So I have an idea of mixing AJAX(which I don't know) and JS in order for me to call this url.
I would use variables for both TOKEN_VALUE and amount&user_id, but I don't know how to even call that url and how to set "request payload" in order for site to do the thing I want it to do.
I would really appreciate if someone would be kind enough to help :)
Work I have done, but doesn't work:
var request=new XMLHttpRequest;
request.open("POST","https://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE"),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"),request.Payload("user_id=12345678&amount=5");
I basically tried to remake an example I found online, but it didn't work out, therefore I need someone to actually explain to me how this works and how can I adjust arguments that I need.
function callAjax() {
// the XMLHttpRequest returns the ajax object that has several cool methods, so you store it in the request variable
// #data contains the $_POST[amount],$_POST[user_id],$_POST[whatever] since we are using POST method, if you're using PHP as a server side language
var request = new XMLHttpRequest(),
url = 'place_here_the_url_only',
data = 'amount=1&user_id=12345678&whatever=dataYouWantToSendToServerFromBrowser',
token = document.querySelector('meta[name="csrf-token"]').content;
// when the server is done and it came back with the data you can handle it here
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// do whatever you want!
console.log("The request and response was successful!");
}
};
// method post, your giving it the URL, true means asynchronous
request.open('POST', url, true);
// set the headers so that the server knows who is he talking to, I'm using laravel 5.5
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
// Token needed
request.setRequestHeader('X-CSRF-TOKEN', token);
// then you send the data and wait for the server to return the response
request.send(data);
}
Ajax: Asynchronous JavaScript And XML
It is a mean of communication between the browser and the server hosting the website, it cannot call any other server.
Asynchronous means the website continues to function normally, until the request is returned from the server and the:
if (this.readyState == 4 && this.status == 200) { }
gets triggered

Chrome Extension webRequest.onBeforeRequest Cancel Page

I am attempting to create a chrome extension that queries an external source as a reference to block or allow through a particular page. The following is part of my code. I am new to javascript, and scope always seems to be something that screws me up.
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
var http = new XMLHttpRequest();
var url = "http://xxx.xx.xxxx";
var params = "urlCheck="+encodeString_(details.url);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
guilt = 0;
console.log(guilt);
}else if(http.readyState == 4 && http.status == 404){
guilt = 1;
console.log(guilt);
}
}
http.send(params);
if(guilt == 1){
return {cancel: true};
}else{
return {cancel: false};
}
},
{urls: ["<all_urls>"],
types:["main_frame"]
},
["blocking"]
);
Any help would be greatly appreciated! Thanks.
You can't do that.
Your code does not work as expected because XHR is asynchronous; your onreadystatechange is executed after the whole outer function finishes. So guilt will be undefined or, worse, stale (from the last request).
For more information, see this canonical question: Why is my variable unaltered after I modify it inside of a function?
However, if you try to fix this, you'll notice that you can't return a response from within the async handler.
This is intentional: there is no function to pass and then call later (like sendResponse in Messaging API), because Chrome will not wait for you. You are expected to respond to a blocking call in a deterministic and fast way.
If the optional opt_extraInfoSpec array contains the string 'blocking' (only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns.
You could try to bypass it by using synchronous XHR calls. That is not a very good idea in general, since loading a remote response takes a long time, and synchronous XHR is considered deprecated. Even though you limited your queries to "main_frame" requests, this still adds an uncertain delay to each load.
A proper way to do that would be to load a set of rules from a server and update it periodically, and when a request occurs validate it against this local copy of rules. This is the approach extensions like AdBlock use.

Possible HTTP Request states after form submit

I'm trying to submit a form and get the results inpage using AJAX. I call a JS function onsubmit which makes the AJAX call, and includes this code:
request=new XMLHttpRequest();
/* set up request here */
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
/* do what I need */
alert('Success');
} else {
/* do what I need */
alert('Failed');
}
}
However, the Failed alert shows up multiple times (3 at least) before the Success one, so I guess I'm getting many different statuses before the successful one? How can I check which ones I get, and what to expect when the submission is failed? Thanks.
The request goes through four phases. The readyStates. Every time the readystate updates it fires the event. 0 indicates a failure and 4 indicates that the request has finished. the status returns the http code. 200 indicates success. There was an answer and it returned a request body. All other codes indicate there was something wrong on the server side. Eg. 404, 403, or 500. You can safely ignore the other readystates. But catch any status other than 200 as failure.
You only ever get one status, but you get multiple states.
Check to see if the readyState is 4 or 0 (since either of those states indicate that there is no more of the response to wait for).
Then throw an error if it is 0 or test the status if it is 4.
If the readyState is any other value, then ignore it (unless you want to do stuff in other states).

JavaScript POST Request Issue

So I'm creating a mobile application using Intel XDK, I am sending a JavaScript POST request of a username and password. I also did some research on the HTTP status codes and found this:
200 OK - Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.
201 Created - The request has been fulfilled and resulted in a new resource being created.
202 Accepted - The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.
So I would assume that when a new user is inserted through a POST request the status would be 201. However when I had this code:
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.status == 201) {
alert("User created.");
} else {
alert("Error!");
}
}
It would show the "Error!" and not "User created." But when I added this on to the code:
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.status == 201 || XMLHTTP.status == 200) {
alert("User created.");
} else {
alert("Error!");
}
}
It showed "User created." So I was wondering how come the status is 200 even though I'm sending a POST request to insert in to a database.
Secondly, it alerts the "User created." 4 times? Is that because it is in the function onreadystatechange so it changes each time and is alerted? If so I can I make it so that it only alerts one? Should I have an if statement wrapped in a setinterval as shown below:
setInterval(function () {
if (XMLHTTP.status == StatusNumberHere) {
alert("Blah");
}
}, 10);
Very few websites use those headers, your back-end probably just sends a 200 even though the request was successful in inserting data.
About your second question, the reason your alert is triggered four times is because onreadystatechanged is called four times, each with a different readyState:
Server connection established
request received
processing request
request finished and response is ready
So you probably want to add XMLHTTP.readyState === 4 to your if statement so it in the end becomes:
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.status === 200 && XMLHTTP.readyState === 4) {
alert("User created.");
} else {
alert("Error!");
}
}
The status returned is based on how the server decides to handle it, in most cased you will simply get a success (200), so there is no issue or abnormality with what you have done.
setInterval = hack, avoid at all costs unless implementing some actual interval function.
You can check the the readystate of the XMLHTTP request with
XMLHTTP.readyState == 4
to filter out only the completed event.
Here is a list of the ready state events:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

parameter "true" in xmlHttpRequest .open() method

From the reference I read in MDN, it says
If TRUE (the default), the execution of the JavaScript function will continue while the response of the server has not yet arrived.
This is the A in AJAX.
I have been using AJAX but then I was a little confused when I read that. I think the problem may be that I am not understanding AJAX concept clearly. I know of course AJAX does not refresh the page which means the connection to the server and the response are completely done in the background.
But what I can imagine happening according to that reference is that if I have a code like this in my JavaScript:
//true, therefore process the function while server retrieves url
var xmlResponse;
var url = "http://example.com/file.xml";
xml_req.open("GET", url, true);
xml_req.onreadystatechange = function() {
if(xml_req.readyState == 4 && xml_req.status == 200) {
if(xml_req.responseText != null)
xmlResponse = xml_req.responseXML; //server response may not yet arrive
else {
alert("failed");
return false;
}
};
xml_req.send(null);
Doesn't that mean xmlResponse could be undefined in the sense that the server is still retrieving the data? Could somebody explain what really is the flow of the execution in AJAX technology? Thanks in advance.
I wrote a more detailed article here, but this is the basic idea.
Setting it to true means you are making an asynchronous request. That means the code does not pause until the http request is complete. A synchronous call locks up the browser so nothing else runs. That can cause problems, so people prefer asynchronous.
The XHR object updates us on what it is doing. It gives us the updates with the onreadystatechange event. We register a function with it so we can keep track of its status. The onreadystatechange gets called 4 times. Each with a different state
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
The data is available to us when the readystate is 4.
Now in the code you posted, it is checking for the complete state and it makes sure that the status is 200 [ok]
if(xml_req.readyState == 4 && xml_req.status == 200){
The value for xmlResponse will be undefined if you try to use it somewhere else in the code before it is returned. An example
ml_req.send(null);
alert(xmlResponse );
One of the very first articles on the XMLHttpRequest article might be a good read for you. Apple Article on xmlhttpreq
The important thing to understand is that your onreadystatechange handler is not executed immediately. And it is executed more than once. It may be easier to conceptualize, if you break the pieces out into individual functions:
function makeRequest(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = receiveResponse;
xhr.send();
}
function receiveResponse(e)
{
if (this.readyState == 4)
{
// xhr.readyState == 4, so we've received the complete server response
if (this.status == 200)
{
// xhr.status == 200, so the response is good
var response = this.responseXML;
...
}
}
}
First, makeRequest is called and then exits. Then, as soon as we hear anything back from the server, receiveResponse is called. Each time, we check to see if the response is fully received, and only then do we continue to process that response.

Categories