I can't get a response from the server - javascript

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

Related

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.

Tableau REST API: Using Javascript to get the Token

I am a complete beginner with REST API and I could not figure out how I am to proceed.
I installed Postman and was successfully able to get the Token, but I am not sure how to send the raw XML payload in javascript.
<tsRequest>
<credentials name ="XXX" password="YYY" >
<site contenturl = "" />
</credentials>
</tsRequest>
I have :
httpRequest.open('POST', 'http://MY-SERVER/api/2.4/auth/signin', false);
httpRequest.setRequestHeader("Content-type", "application/xml");
Not sure how to add the xml payload. I have access to a Tableau Server(MY-SERVER) and everything.
Any help would be greatly appreciated!
Thank you!
You are getting closer, you just need to use the send method to send your XML: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
Just make sure that your XML is properly encoded in javascript when you're inputting it. So if you are using double quotes inside your XML, make sure you have single quotes to declare your string in javascript (e.g.) var data = '<credentials name="XXX" >';
Related: Send POST data using XMLHttpRequest
In addition to #AnilRedshift answer, here's the functioning code:
login_details=[];
function getToken() {
var url = "http://yourServerAddress/api/2.0/auth/signin";
var params = "<tsRequest><credentials name='Username' password='UserPassword' ><site contentUrl='' /></credentials></tsRequest>";
return zuo = new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.withCredentials = true;
xhr.onload= function(){
if (this.status === 200) {
var parsed_xml = JSON.parse(JSON.stringify(x2js.xml_str2json(xhr.responseText)))
login_details.push(parsed_xml.tsResponse.credentials._token); login_details.push(parsed_xml.tsResponse.credentials.site._id);
resolve(login_details);
}
}
xhr.onerror=reject;
xhr.send();
})
}
function getWorkbooks(){
var url = "http://serveraddress//api/2.3/sites/"+login_details[1]+"/workbooks?pageSize=1000";
return zuo = new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-Tableau-Auth",login_details[0]);
xhr.onload= function(){
if (this.status === 200) {
var workbooks = JSON.parse(JSON.stringify(x2js.xml_str2json(xhr.responseText)))
for (var f=0;f<workbooks.tsResponse.workbooks.workbook.length;f++){
if(workbooks.tsResponse.workbooks.workbook[f].project._name=="Default"){
workbooks_list.push(workbooks.tsResponse.workbooks.workbook[f]._id)
}
resolve();
}
}
}
xhr.onerror= function(){
console.log(xhr.responseText);
}
xhr.send();
})
}
Invoke the code with:
getToken()
.then(function(login_details){
console.log(login_details[0]+"/"+login_details[1]);
})
.then(function(){
getWorkbooks();
})
getToken() function gets the login token which has to be used in all subsequent calls.
getWorkbooks() fetches all dashboards in 'Default' project but this kind of request can be used for all GET type requests.
Please note that this approach uses hardcoded values for password and username which is generally not the best practice. It would be way better to use server side scripting or encrypting (better but still with flavs).
You can find whole step by step tutorial and running code here:
http://meowbi.com/2017/10/23/tableau-fields-definition-undocumented-api/

Unable to send JSON object to XMLHttpRequest

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.

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.

Normal redirect or preload

So on the net I've come across a several ways to preload / redirect a webpage.
Now's the question is this the proper way to handle a redirect with preload (Load the next page async while still showing the current page)
$.get("page.php", function (data) {
document.open();
document.write(data);
document.close();
window.history.pushState("Title", "Title", "/page.php");
$.cache = {};
}, "html");
Or should I better stay with a regular redirect?
window.location = "page.php";
The next page contains a fullscreen video and a soundtrack (audio)
Thanks.
You can use Ajax to load next page asynchronous.
Here is an example of a simple Ajax request using the GET method, written in JavaScript.
AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to behave as AJAX, the async parameter of the open() method has to be set to true: xhr.open('get', 'send-ajax-data.php', true);
get-ajax-data.js:
// This is the client-side script.
// Initialize the Ajax request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php', true); // `true` makes the request asynchronous
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
alert(xhr.responseText); // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
And at the end you can use below codes to reload or redirect page data:
document.getElementById("myDiv").innerHTML = xhr.responseText;

Categories

Resources