Send Custom HTTP Body with AJAX POST request - javascript

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

Related

How to send an API get request using JavaScript with HTML variables

I am trying to make a GET request to a web API using what is inputted in a textbox. So far I have the input value established but can't seem to figure out to send the request.
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
console.log(requestdata);
This function correctly but I can't seem to figure out the rest.
I am trying to do the following:
https://api.example.com/request?=${requestdata}
or
https://api.example.com/request/${requestdata}/test
Keep in mind that this is a static HTML site with no Node
Something like this should work to make an asynchronous GET request:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
httpGetAsync("https://api.example.com/request?=${" + requestdata + "}");
<input type="text" id="request" value="test">
If you check the developer tools > network tab you should see the GET request to the API endpoint.

Ajax POST request on https in vanilla js

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?

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.
}

Sending Http POST Request through Rest API in Javascript

I am trying to send an Http post request to parse.com server through Rest API keys. Not sure if I am doing it right as below. The following is my whole script and makes a button which should trigger the post request in a simple HTML page.
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
<script>
xmlhttp = new XMLHttpRequest();
var url = "https://api.parse.com/1/classes/english";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("X-Parse-Application-Id", "VnxVYV8ndyp6hE7FlPxBdXdhxTCmxX1111111");
xmlhttp.setRequestHeader("X-Parse-REST-API-Key","6QzJ0FRSPIhXbEziFFPs7JvH1l11111111");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var parameters = {
"ephrase": "english",
"pphrase": "farsi",
"nvote": 0,
"yvote": 0
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
function doFunction() {
xmlhttp.send(parameters);
}
</script>
xmlhttp.send(parameters);
^^^^^^^^^^
That needs to be a string, but it is an object, so will be converted to the string: "[object Object]".
You need to convert the data to the proper encoding first.
You've said:
xmlhttp.setRequestHeader("Content-type", "application/json");
so you can use JSON.stringify(parameters) for that.

send an http request without XHR in an event handler

How to send an http request with either post/get method using javascript as an eventhandler? Thanks! Paul
Okay, you don't want to use Ajax.
You can use an event handler to submit a form!
<a href='#' onclick='cow_submit("zoodle")'>send</a>
<form method='post' id='formie' action='find_some_action.php'>
<input type='hidden' id='snoutvar' name='snoutvar' value='snout'>
</form>
<script>
function cow_submit(a_var_to_set){
var plip=document.getElementById('formie');
var snout=document.getElementById('snoutvar');
snout.value=a_var_to_set;
plip.submit();
}
See https://developer.mozilla.org/en/DOM/form
use XmlHttpRequest
sample code:
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");
client.send();
function handler()
{
// your handler
}
You can use XMLHttpRequest for sending request from javascript
Sending GET request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
Sending POST request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
And don't forget to encode parameters using encodeURIComponent for param value encoding in case of user input
e.g.
params="paramName="+encodeURIComponent(paramValue);
The standard class for doing this is XmlHttpRequest, but it's not universally supported. On some browsers you have to use ActiveXObject("Microsoft.XMLHTTP") instead.
Look into the jQuery system which provides HTTP download (AJAX style) methods regardless of the underlying browser APIs (hence avoiding a lot of the code shown in Tzury's answer).
The jQuery AJAX documentation is at http://docs.jquery.com/Ajax
You should try to add atring in a hidden field and then call the form.submit() to submit your form into the page define in action.
<script type="text/javascript">
function doTestFormSubmit(yourString) {
document.getElementById("myString").value=myString;
document.getElementById("testForm").submit();
}
</script>
<form name="testForm" id="testForm" action="yourDesiredPage.php" method="post">
<input type="hidden" name="myString" id="myString" value=""/>
</form>
Ajax Tutorial (http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html)
var obj;
function ProcessXML(url) {
// native object
if (window.XMLHttpRequest) {
// obtain new object
obj = new XMLHttpRequest();
// set the callback function
obj.onreadystatechange = processChange;
// we will do a GET with the url; "true" for asynch
obj.open("GET", url, true);
// null for GET with native object
obj.send(null);
// IE/Windows ActiveX object
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
if (obj) {
obj.onreadystatechange = processChange;
obj.open("GET", url, true);
// don't send null for ActiveX
obj.send();
}
} else {
alert("Your browser does not support AJAX");
}
}
function processChange() {
// 4 means the response has been returned and ready to be processed
if (obj.readyState == 4) {
// 200 means "OK"
if (obj.status == 200) {
// process whatever has been sent back here:
// anything else means a problem
} else {
alert("There was a problem in the returned data:\n");
}
}
}

Categories

Resources