sending form data with javascript with XMLHttpRequest asynchronously - javascript

I am sending some form data with an XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
try {
let data = JSON.stringify(sendForm);
xhr.send(data);
alert(xhr.status);
}
catch (error) {
alert(error);
}
This works as it will go into this after the alert pops up in the browser
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
location.href = 'thanks.html';
}
and data will be inserted into the database as expected. However, if I comment out the alert after the xhr.send(data); this code will no longer inserts data into the database or display the correct page, it just displays the js file. If I set a break point at xhr.send(data) when I step past it is when the js file is displayed.
Any thoughts as to why the data is being sent if I include the alert(xhr.status) step in the code but not when I comment it out? Also, any thoughts why the try{}catch{} is not catching the error? Thanks I am not very familiar with javascript right now.

Related

No Access-Control-Allow-Origin header JS Get Request

I Have write a code using JS, to send GET Request to a URL. This error appears in the console when I'am clicking the button to make the GET request: ERROR
Below you can see the code, I saw some solutions but it didn't work for me. I'am working in a index.html file should I insert something in my code to fix this error?
function call()
{
var url = "http://urlexample";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
}
<button onclick="call();">Make a request</button>

How to everytime reload web, and get the newest data from back-end

What my purpose is below
Visting a web and the js.file in this web will load php file, and it will return data to html.
It's meaning every time when I reload web, I will get newest data.
I have try this in js.file
let XML = new XMLHttpRequest();
XML.open('post', url, true);
XML.send('mydata');
then use responseText to get data I want
Indeed, I don't need send any data.
I can do what I want to do, but I am not sure this way is right or not.
Because I think ajax should not use in this case, it must be send something and return something.
What you are saying is you only want to get data without sending anything which is called a http get request, you can do that as below.
function get(url)
{
var xm = new XMLHttpRequest();
// false for synchronous
xm.open("GET",url,false);
xm.send(null);
return xm.responseText;
}
console.log(get('your Url'));
You need to specify the url of your Http Endpoint ( Back-End ).
If your are making a asynchronous request then below code works,,
function get(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
// true for asynchronous
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
get('your url',(responseText)=>{
console.log(responsetext);
});

If HEAD-HTTP-Requests only fetch the HTTP-Header, why my XHR-request has a reponseText?

Today I researched about HTTP-methods and the differences between GET and HEAD in detail.
In theory I know, that HEAD only returns the HTTP header, not the HTTP body. Its useful to get information about ressources without downloading them completly.
I made a little Script using XHR to check out a HEAD-reques and tested it in Firefox 50.0.2.
http://codepen.io/anon/pen/oYqGMQ
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function () {
if (req.readyState === 4 && req.status === 200) {
alert("got response \n" + req.responseText);
}
}, false);
req.open("HEAD", location.href, true); // this is a HEAD-request, why I get a responseText?
req.send();
Why the HEAD-Request receives the complete data in the reponseText-property? I thought HEAD-Request will not receive any data of the body.
I can't see any difference between HEAD and GET.
Am I missing a point? I am using Firefox.

Using javascript to submit a post request to a server

I am working on a web crawler that can integrate with our partner portals and submit post requests to make bid changes.
The trouble is that the crawler runs in an environment which cannot execute jQuery, only native Javascript.
I have determined that the following AJAX code successfully sends the post request:
$.ajax({
type: "POST",
url: "http://acp.example.com/campaigns/122828",
data: "data-string"
});
Is there a way to translate the above statement into native javascript so that the crawler can execute it?
UPDATE
When executing hex494D49's native Javascript below, I am receiving a "NetworkError: 404 Not Found - http://acp.fyber.com/campaigns/122828" message.
However, when I execute the original AJAX code in firebug, it successfully sends the POST request.
Any idea why the same url would return a 404 error using native Javascript as opposed to AJAX?
Thanks
Sending AJAX request using POST method
var xhr = new XMLHttpRequest();
var url = "url";
var data = "email=hey#mail.com&password=101010";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(data);
Sending AJAX request using GET method
xhr = new XMLHttpRequest();
var url = "url?email=hey#mail.com&password=101010";
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
}
xhr.send();
To avoid unexpected requests to the server, it's a good practice to use encodeURIComponent() method on any user-entered parameters that will be passed as part of a URI.

First XHR request very slow in QML(javascript running on v8)

I have a QML page (Qt Quick 2) that makes an XHR request to an external server. Right now the server is running on my local machine and the first time this request is made it takes ~1.5 seconds. Each subsequent request is under 100ms.
When I make this same request using a browser I get a response in under 10ms everytime, so I know the problem isn't there.
Here is the offending code. Any ideas?
function login(key) {
var xhr = new XMLHttpRequest();
var params = "Fob_num=" + key;
xhr.open("POST","http://localhost:9000/customer_login",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if ( xhr.readyState == xhr.DONE) {
if ( xhr.status == 200) {
handleResponse(xhr.responseText);
} else {
console.log("error with login--status: " + xhr.status)
displayErr("Oops, something's wrong. Please try again.")
}
}
}
xhr.send(params);
}
The problem isn't with handleResponse() function, I've already tried replacing it with a console.log(“response”), and it still takes just as long. I also tried replacing localhost with my ip.
You may want to create a dummy XMLHttpRequest instance in a dummy QML component that you asynchronously load with a Loader. Just an idea. Perhaps creating the first XMLHttpRequest instance takes long?

Categories

Resources