Ajax POST request on https in vanilla js - javascript

I'm trying to make an Ajax POST request in vanilla js (the site dosen't have jquery). I've tried to do something like this, but can't make it work.
var params = { name: "Test"};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.testurl.com/api/test/save', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
response = JSON.parse(xhr.responseText);
console.log(reponse);
}
};
xhr.send(JSON.stringify(params));
I get this error GET https://www.testurl.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)
Do anyone have any idea how to make the AJAX post request work with https in vanilla js?

Related

After authenticating via POST, I need to do a GET using Ajax

I'm attempting to create a dashboard that logs into an API then refreshes certain data elements that is fully automated. I can login and authenticate but after googling unsure how to 'chain' the GET request after the 'POST'
I've tried watching a few youtube tutorials and creating functions, attaching them to buttons and divs but I just can't get the data to display. The first batch of code completes and logs in OK, but then sits there and times out. I tried just adding a second open and making the login synchronous but it failed
<script type="text/javascript">
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send();
I'm expecting the login to be done behind the scenes and not visible, and just have the GET request show data in a div (I'll try and tidy up the xml response when I get the data working first).
In your code you never use your data variable :
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send(data); // <====== HERE

make a post request in js and open its results in a new window

I have a js file, containing a folder myFunc(phone_number)
Now when this js function is called, I want to make a POST request to the URI https://pay.something.in:443/FetchPhone/ passing the json {'phone_number' : 10 digit phone no. } as input to the request
and show its output in a new window.
Can somebody tell me how do I do that?
Seems to me like you want to make a POST request with xhr.
var xhr = new XMLHttpRequest();
xhr.open('POST', "https://pay.something.in:443")
xhr.setRequestHeader("Content-type", "application/json");
xhr.send( '{"phone_number" : 4455566677 }' );
xhr.onreadystatechange = function(){
if (xhr.readyState != 4) return;
if (xhr.status != 200 && xhr.status != 304) {
alert('HTTP error ' + req.status);
return;
}
console.log(xhr.responseText);//this is your response
window.sessionStorage['response'] = xhr.responseText;
window.open('Your window');//The data is accessible through sessionStorage.
}

Send Custom HTTP Body with AJAX POST request

How do I send a custom HTTP body with my POST AJAX request in plain Javascript (not JQuery)? I am actually trying to send a JSON file in the body. I can set the custom header fields but can't find how to set HTTP body.
below is the code
function calculateorder() {
document.getElementById("finalize").style.display = "inline";
url1 = "https://ethor-prod.apigee.net/v1/stores/";
url2 = "/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7";
url = url1 + store_id + url2;
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(calculate));
}
When I used the same headers and JSON file with Rested (a OSX HTTP client) It works perfectly
Add parameter in XmlHttpRequest Obeject's .send() method
Like this:
xhr.send('username=me');
Send JSON Format Data myData Like this:
xhr.send(JSON.stringify(myData));

(AJAX/PHP) Why is my POST request not working in this brief example?

Here is my JavaScript:
var xhr = new XMLHttpRequest();
xhr.open("POST", "pants.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var slot = document.getElementsByTagName("section")[0].innerHTML = xhr.responseText;
}
}
xhr.send("name=Sarah");
I am sending "name=Sarah" to testpage.php via POST, and when I get a response, I'm doing to display it on my page.
And here's pants.php:
echo $_POST['name'];
So I should just be displaying "Sarah" on the page. But instead, I get the error ": Undefined index: name". I can't seem to understand why this is...
You should add the following:
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
This header is mandatory for POST requests

Is there a way to do a http head request and get the time without a server side language

I am trying to do a http head request from the Javascript code to get the server time ...Can I do this from javascript or do I need a server side language to achieve this
Assuming your server sends the Date header (which the RFC says it MUST), sure:
$.ajax('/', {
type: 'HEAD',
success: function(r,status,xhr) {
alert(xhr.getResponseHeader('Date'));
}
});
Or without the use of jQuery, not much more code but possibly less error handling :
function getServerTime() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.getResponseHeader('Date'));
}
};
xhttp.open("HEAD", "/", true);
xhttp.send();
}

Categories

Resources