Unable to send JSON object to XMLHttpRequest - javascript

I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");
However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send(JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
}));

You're sending very different information in your two calls. Some sample code:
var _stringify = JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
});
console.log(_stringify);
var _orig = "apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456"
var _encoded = encodeURI(_stringify);
console.log(_orig);
console.log(_encoded);
when your original string is printed to the console log, it looks as you would expect:
apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456
when the result of JSON.stringify is printed to the console, it returns:
{"apikey":"ee6915d4ee4b4df66bba82277e3","firstname":"Kumar","lastname":"Sunder","phone":"5557773334"}
That is, it comes complete with lots of extra double quote marks and left and right brackets. If you want to send all of that as a string (as in your initial example), you would need to URI encode the result of the JSON.stringify call. This is what happens with the "_encoded" variable, which contains:
%7B%22apikey%22:%22ee6915d4ee4b4df66bba82277e3%22,%22firstname%22:%22Kumar%22,%22lastname%22:%22Sunder%22,%22phone%22:%225557773334%22%7D

You are sending via a POST action, but then sending the data via a url string. If you want to send it that way you need to set it to GET.

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

Why isn't my POST XMLHttpRequest.Send working?

I am having issues correctly setting up my XMLHttpRequest object to POST data to a server. The data (from an HTML form) never seems to get posted, or at least readyState == 4 && status are never reached.
function PostToAPI() {
var payersName = document.forms["myForm"]["payersName"].value;
var recipientPhoneNumber = document.forms["myForm"]["recipientPhoneNumber"].value;
var apiKey = document.forms["myForm"]["apiKey"].value;
var params = "payersName="+payersName+
"&recipientPhoneNumber="+recipientPhoneNumber+
"&apiKey="+apiKey;
alert(params); // Note#1
var Url = "https://api.blackShawls.af/c2b"; // Note#2
var xhr = new XMLHttpRequest();
xhr.open('POST', Url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText.headers.Host); // Note#3
}
}
xhr.send(params);
}
Notes
(Note#1) This alert yields the following result:
This suggests that the various fields from the HTML form have been successfully read in, and that everything is working just fine to this point.
(Note#2) The Url value here is fictitious, in contrast to one in my code.
(Note#3) The alert(xhr.responseText.headers.Host); never seems to fire-up, suggesting that the readyState and the status conditions are never met.
Or could it be that the xhr.send(params) is never sent?
Can someone kindly point out where I am going wrong in my code?
Looking forward to your help.

How to send JSON response from python server to the javascript using ajax call

elif self.path == "/recQuery":
r = requests.get('http://example.com') # This returns some json from a request to another server.
print r.json()
self.wfile.write(r.json())
.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
console.log(http.responseText);
How can i send data from python server to javascript using ajax call. The one i am using does not return anything in the console. Can you please tell me what i am doing wrong here. I need send the response of what i get from requests.get method to the ajax call. The json should be returned to the ajax call in response. Problem is with the self.wfile.write method, When i use this i dont get anything on javascript side.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
I was not fetching the response onreadystatechange. So this works for me. Thanks !

How to send XMLHttpRequest Put call (error: too many redirects)

I can make GET calls fine, but I don't know how to make PUT requests. The error I'm getting is "Failed to load resource: too many HTTP redirects"
Code:
var url = "https://{{shop.domain}}/cart.js";
var xhrPut = new XMLHttpRequest();
xhrPut.open("PUT", url, true);
xhrPut.setRequestHeader("Content-Type", "application/json");
xhrPut.send("{\"total_price\":50}");
The JSON that I'm trying to change is this:
{"token":"a97c89f7e2c7c22becab8cfef40fa272","note":null,"attributes":{},"original_total_price":100,"total_price":100,"total_discount":0,"total_weight":0,"item_count":1,"items":[{"id":19673785606,"properties":null,"quantity":1,"variant_id":19673785606,"key":"19673785606:59d774c1f413525441dcb716e0c982e2","title":"Short Sleeve Shirt","price":100,"line_price":100,"original_line_price":100,"total_discount":0,"discounts":[],"sku":"","grams":0,"vendor":"Dev Store","product_id":6213990086,"gift_card":false,"url":"\/products\/short-sleeve-shirt?variant=19673785606","image":"https:\/\/cdn.shopify.com\/s\/files\/1\/1278\/7069\/products\/happyman.jpg?v=1462811058","handle":"short-sleeve-shirt","requires_shipping":true,"product_type":"","product_title":"Short Sleeve Shirt","product_description":"description","variant_title":null,"variant_options":["Default Title"]}],"requires_shipping":true}
The total_price variable is currently 100, I'm trying to set it to 50.
Editing this so I may get answers
I changed the code to the following and then get error 400: bad request
var url = "https://{{shop.domain}}/cart.json";
var xhrPut = new XMLHttpRequest();
xhrPut.open("PUT", url, false);
xhrPut.setRequestHeader("Content-Type", "application/json");
xhrPut.send('{"token":"a97c89f7e2c7c22becab8cfef40fa272","note":null,"attributes":{},"original_total_price":100,"total_price":50,"total_discount":0,"total_weight":0,"item_count":1,"items":[{"id":19673785606,"properties":null,"quantity":1,"variant_id":19673785606,"key":"19673785606:59d774c1f413525441dcb716e0c982e2","title":"Short Sleeve Shirt","price":100,"line_price":100,"original_line_price":100,"total_discount":0,"discounts":[],"sku":"","grams":0,"vendor":"Dev Store","product_id":6213990086,"gift_card":false,"url":"\\/products\\/short-sleeve-shirt?variant=19673785606","image":"https:\\/\\/cdn.shopify.com\\/s\\/files\\/1\\/1278\\/7069\\/products\\/happyman.jpg?v=1462811058","handle":"short-sleeve-shirt","requires_shipping":true,"product_type":"","product_title":"Short Sleeve Shirt","product_description":"description","variant_title":null,"variant_options":["Default Title"]}],"requires_shipping":true}"');
From my knowledge of how the PUT request works, this should overwrite the entire document, but the only changes made were:
The variable total_cost was reduced from 100 to 50
The escape character '\' was used before the characters '\' in the variable 'url' in the array 'item'
Here is a GET request that I am sending before this PUT request, which returns no errors and writes the expected values to console. Note that the errors with the PUT request occur whether this is run or commented out.
var totalCost;
var url = "https://{{shop.domain}}/cart.json";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var resp = xhr.responseText;
console.log(resp);
var json = JSON.parse(resp);
console.log(json);
totalCost = json.total_price;
console.log(totalCost);
}
};
xhr.open("GET", url, false);
xhr.send();
console.log(totalCost);
The only reason this is synchronous is so that I can log the totalCost after the API call.

How to write http request in javascript?

I know it can be done but i am no good with http request at all. I have a very specific one i need to write. The code is here but i dont know which line to return to my app for the response.
var request = new XMLHttpRequest();
request.open('POST', 'https://v2.api.xapo.com/oauth2/token');
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Authorization', 'Basic YTVlMGExMTViYTc1MThjYzphNWUwYTExNWJhNzUxOGNjYTVlMGExMTViYTc1MThjYw==');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = "grant_type=client_credentials&redirect_uri=https://myURI.com";
request.send(body);
This is what im trying to do.
curl --include --request POST --header "Content-Type: application/x-www-form-urlencoded" --header "Authorization: Basic MYKEYHERE[auth]" --data-binary "grant_type=client_credentials&redirect_uri=MYREDIRECTURI" 'https://v2.api.xapo.com/oauth2/token'
The api for this is here
please see the following code :
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
first you define an instance of XMLHttpRequest() that will do the http request for you
second the method xhttp.onreadystatechange = function()will be listening to state change that means it will be executed once an http responde is returned
third xhttp.open method will determine your connection config for example here we set a property "POST" then determining the link you want to post to it along with the variables you want to post like this :
enter the link
put ? mark
put the variable name
put =
put the varible value
put & mark and repeat the steps 3 4 5 if you want to post more variable else put nothing .
fourth the method xhttp.send()will start the http request to the server and once the response is gotten the xhttp.onreadystatechange = function()will be called then you can get the content of the response with xhttp.responseText
I hope this example is clear

Categories

Resources