Is there a way to preserve cookies between two separate XMLHttpRequests? - javascript

As indicated in the code snippet below, I am trying to extract a token from the response obtained from the first call made on XMLHttpRequest. I then want to send the token in the second POST call ensuring that cookies are the same. But, I am not able to figure out a way to preserve the cookies yet. Could someone share what I am missing here?
//First XMLHttpRequest below
xhr = new XHR();
xhr.onreadystatechange = extractLoginToken;
xhr.open( "GET", url );
xhr.setRequestHeader('Set-Cookie', "abc");
xhr.withCredentials = true;
xhr.send();
function extractLoginToken() {
var params = "token=" + this.responseText.query.token;
var cookie = xhr.getResponseHeader('Set-Cookie');
//Second call
xhr = new XHR();
xhr.withCredentials = true;
xhr.open( 'POST', url_1 );
xhr.setRequestHeader('Set-Cookie', cookie);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send( params );
}

Related

I am not able to send a string correctly from javascript to server

I am trying to send a string to my server using the following script:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.send(data);
However, on the server side, when execute.php is executed,
isset($_POST['name'])
it returns false. This is the only request to the server.
Why isn't $_POST['name'] set and how to fix it?
Try setting a request header before sending the data:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
There are various ways to encode your data when POSTing (MIME types). PHP's $_POST only automatically decodes www-form-urlencoded
var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
var data = 'name=John';
xhr.send(data);
If you send JSON encoded data, you must read the entire post body and json decode it yourself.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
var data = JSON.stringify({'name':'John'});
xhr.send(data);
in PHP...
$entityBody = file_get_contents('php://input');
$myPost = json_decode($entityBody);
$myPost['name'] == 'John';
Use your browser's network inspector (f12) to see what is going on.

How to handle CSRF token using XMLHTTPRequest?

I am using an API which is protected by CSRF. So I need to do a get call to fetch CSRF token and then pass the same token to do POST call.
Below is the way I tried, but i always get CSRF Token Validation failed as response for the POST call.
var tryout = new XMLHttpRequest();
tryout.open("GET", "/api/1.0/csrf");
tryout.withCredentials = true;
tryout.setRequestHeader("x-csrf-token", "fetch");
tryout.setRequestHeader("Accept", "application/json");
tryout.setRequestHeader("Content-Type", "application/json; charset=utf-8");
tryout.onreadystatechange = function () {
console.log(this);
var csrfToken = this.getResponseHeader('x-csrf-token');
if(tryout.readyState == 4){
console.log(csrfToken);
tryout.open('POST', '/api/1.0/create');
tryout.setRequestHeader('x-csrf-token', this.getResponseHeader('x-csrf-token'));
tryout.onreadystatechange = function () {
console.log("call 2");
console.log(this.responseText);
};
tryout.send();
}
};
tryout.send();
I am suspecting may be POST call is starting new session and so CSRF is not valid for that session.
Please guide me How to do two xhr calls in same session ?
I tried sync calls with XMLHTTPRequest using same xhr object for both calls ( fetching csrf token and next http post call passing csrf token in header and it worked. Below is the sample code.
var res = null;
var tryout = new XMLHttpRequest();
tryout.open("GET", "/odata/1.0/service.svc", false);
tryout.withCredentials = true;
tryout.setRequestHeader("x-csrf-token", "fetch");
tryout.setRequestHeader("Accept", "application/json");
tryout.setRequestHeader("Content-Type", "application/json; charset=utf-8");
tryout.send(null);
if(tryout.readyState === 4){
var csrfToken = tryout.getResponseHeader('x-csrf-token');
tryout.open('POST', '/odata/1.0/service.svc/Clients', false);
tryout.setRequestHeader('x-csrf-token', csrfToken);
tryout.setRequestHeader("Content-Type", "application/json; charset=utf-8");
tryout.setRequestHeader("Accept", "application/json");
tryout.send(JSON.stringify(obj));
if(tryout.readyState === 4){
res = JSON.parse(this.responseText);
}
}
"x-csrf-token", "fetch" is for the GET method to fetch the data. Then you will get the csrf token value. Just copy that and add that in your code may be it will work.

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/

Php does not recognized formdata send via Ajax js

I send a Formdata with an Ajax request and try to read it in my php file. But in the php file, when i try to read what is in the $_POST with my key i see nothing. I don't understand why.
I did some research on the forum and tried to see why my code isn't working as i wanted to.
EDIT :
I saw the differents links but i was wondering i there is any ways to do it without JQuery.
My ajax call
function pageSend_DataRun ()
{
var formElement2 = document.forms.namedItem("data_to_send_general");
ajaxCallUrl ( "send.php",new FormData(formElement2), pageconfig_acq_generalDataCallback );
}
function ajaxCallUrl ( url, params, callback /*, ... */ )
{
var xhr = new XMLHttpRequest();
xhr.callback = callback;
xhr.arguments = Array.prototype.slice.call( arguments, 3);
xhr.onload = ajaxSuccess;
xhr.onerror = ajaxError;
xhr.open( "POST", url, true );
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send( params );
}
EDIT2 :
I found the solution there : [Using FormData object, the server receives an empty POST
I deleted the line to "setRequestheader" in my ajax configuration and it started working.
function ajaxCallUrl ( url, params, callback /*, ... */ )
{
var xhr = new XMLHttpRequest();
xhr.callback = callback;
xhr.arguments = Array.prototype.slice.call( arguments, 3);
xhr.onload = ajaxSuccess;
xhr.onerror = ajaxError;
xhr.open( "POST", url, true );
xhr.send( params );
}
I edit the answer of my question in the "EDIT2" section.
Hope it will help !

Taxee API (http://www.taxee.io/) - JavaScript - How To: POST Request and Pass Parameters

Thanks for helping out with my question. I've been trying to get the federal, state, and FICA tax from a POST Request on this Taxee API (https://market.mashape.com/stylinandy/taxee), but haven't been able to get it working. I was able to access certain data (simply to figure out how this API works) using one of the two GET requests available for this API:
var state = 'CA';
var year = 2014;
var url = ' https://taxee.io/api/v1/state/'+year+'/'+state;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onload = function() {
var result = JSON.parse(this.responseText);
console.log(result.single.income_tax_brackets);
xmlhttp.abort();
}
xmlhttp.send();
But the data I really need is in the POST request. I would like to know how to access a POST request for this, and more specifically, pass the parameters as noted on the link above. Thanks for any help you can provide, it's always greatly appreciated.
Figured out how to do it actually. The problem was the way that parameters are passed differently in POST requests. Hopefully this helps someone else out there:
var url = 'https://taxee.io/api/v1/calculate/2014';
var params = "filing_status=married&pay_rate=100000&state=CA";
var http = new XMLHttpRequest();
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);

Categories

Resources