XMLHttpRequest add custom header - javascript

I would like to pass access_token via HTTP header.
_xhr.setRequestHeader('x-customtoken', 'value');
When I want to get it on server it's value is null. I get it like this:
public final static String HEADER_SECURITY_TOKEN = "x-customtoken";
// ..
request.getHeader(HEADER_SECURITY_TOKEN)
Pass the token via header is the only solution for me. I can pass it like a request param, but I need to to it via HTTP-headers.
xhr: function(options){
var _xhr = new XMLHttpRequest(),
_to_send = options.params;
_xhr.open(options.type, options.url);
_xhr.setRequestHeader('Content-Type', 'application/json');
_xhr.setRequestHeader('x-customtoken', 'value');
_xhr.responseType = 'json';
_xhr.onload = function () {
if (_xhr.status === 200) {
var _json = _xhr.response;
if (typeof _json == 'string')
_json = JSON.parse(_json);
options.success(_json);
} else {
options.error(_xhr);
}
};
try {
_xhr.send(_to_send);
} catch (e){
options.error(_xhr);
}
}

Related

Symfony5 - formData object send by javascript XMLHttpRequest not Submited in controller

I am trying to save images when dropped over a canvas (saving the position it is dropped to, it source ...etc). To acheive this each image is considered an object that has a saveObject methode that will POST a formData object threw an XMLHttpRequest to a Symfony5 controller, that will receive the formData in a symfony Form.
The symfony form is binded to the the entity representing the objects in the canvas, and should save the formData content to the database on submit.
The problem I am facing is that the controller seem's not to consider the form as submitted.
I have checked : the formData object does contain all the data before the XMLHttpRequest, but on the controller side all the fields seem to be set to null.
this is the saveObject methode :
saveObject() {
console.log("In saveObject");
var xhr = new XMLHttpRequest();
var FD = new FormData;
// set FormData values
for (name in this) {
if (name === 'album_id') {
FD.append(name, this.parent_album);
} else {
FD.append(name, this[name])
}
}
//used to check if FD contains the data it is supposed to
for (var key of FD.entries()) {
console.log(key[0] + ', ' + key[1]);
}
xhr.open('POST', '/edit/storeObjects/');
xhr.send(FD);
xhr.onload = function () {
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
console.log("subission ok");
console.log(xhr.response);
}
}
}
And this is the controller receiving the request :
/**
* #Route ("/edit/storeObjects/", name="save_object")
*/
public function saveObj(Request $request, EntityManagerInterface $em, UploaderHelper $uploaderHelper, SluggerInterface $slugger)
{
$albumObj = new AlbumObjects();
$user = $this->getUser();
$form = $this->createForm(SaveObjectFormType::class);
$form->handleRequest($request);
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName()));
if ($form->isSubmitted() && $form->isValid()) {
/** #Var AlbumObjects $albumObj * */
$albumObj = $form->getData();
if (true == $form['destImg']->getData()) {
$destImg = $form['destImg']->getData();
$user_dest = $user->getOwneravatar();
$newFilename = $uploaderHelper->uploadProfilePicture($user_dest, $destImg, $slugger);
$albumObj->setDestImg($newFilename);
}
$em->persist($albumObj);
$em->flush();
return $this->json([
'saveStatus' => 'Saved'
]);
}
}
return $this->json([
'saveStatus' => 'Not saved',
'albumObj' => $albumObj
]);
}
I am obviously doing something wrong, and would appreciate a hint to what it is I'm missing
I had most of this wrong but with some advice from a friend and some time it is now working, so I am posting her the modifications I have made in case anybody else is having the same issue.
First the form wasn't validated nor submitted because of the csrf protection included in symfony forms.
To go around this the advice I got and that worked pretty well was instead of a plain xmlhttprequest to post the data to the form : do first a get request and on this get return from the form the csrf token.
Then when creating the formData object in javascript it need's to take as parameter the form's name attribute.
Finally, the image wasn't being submitted in the controller though it was sent to the controller (also I checked the enctype was correct). I worked around this by getting the image directly in the Request object. This solution though doesn't "feel right"
so this is how I changed the javascript xmlhttprequest part :
saveObject() {
let xhr = new XMLHttpRequest();
xhr.open('GET', '/edit/storeObjects/');
xhr.send();
xhr.onload = function () {
if (xhr.status !== 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
var formName = document.createElement('form');
formName.setAttribute('name', JSON.parse(xhr.response)['formName']);
var fD = new FormData(formName);
var attrListe = ['parentAlbum','pageNumber','type','dx','dy','dwidth','dheight','sx','sy','swidth','sheight','destImg','containedText','fontSize', 'fontType','fontColor','textMaxWidth','textLineHeight','album']
attrListe.forEach(attrName => {
if (attrName == 'destImg') {
var file = this.dataURLtoFile(this.destImg, 'img');
fD.append(attrName, file);
} else {
fD.append(attrName, this[attrName])
}
});
fD.append('_token', JSON.parse(xhr.response)['token']);
for (var value of fD.entries()) {
console.log(value[0] + ': ' + value[1]);
}
let xhrPost = new XMLHttpRequest();
xhrPost.open('POST', '/edit/storeObjects/');
xhrPost.send(fD);
xhrPost.onload = function () {
if (xhrPost.status !== 200) {
alert(`Error ${xhrPost.status}: ${xhrPost.statusText}`);
} else {
console.log("Object Saved")
}
}
}
}.bind(this)
}
And here are the modifications to the controller :
public function saveObj(Request $request, EntityManagerInterface $em, UploaderHelper $uploaderHelper, SluggerInterface $slugger)
{
$user = $this->getUser();
$form = $this->createForm(SaveObjectFormType::class);
$form->handleRequest($request);
if ($request->isMethod('POST')) {
$form->submit($request->request->all());
if ($form->isSubmitted() && $form->isValid()) {
/** #Var AlbumObjects $albumObj * */
$albumObj = $form->getData();
//Check if the image field contains a file and if it does process it
if ($request->files->get('destImg')) {
$dest_Img = $request->files->get('destImg');
$user_dest = $user->getOwneravatar();
$newFilename = $uploaderHelper->uploadProfilePicture($user_dest, $dest_Img, $slugger);
$albumObj->setDestImg($newFilename);
}
$em->persist($albumObj);
$em->flush();
return $this->json([
'saveStatus' => 'Saved',
]);
}
}
return $this->json([
'formName' => $form->createView()->vars['name'],
'token' => $form->createView()->children['_token']->vars['value']
]);
}

My idea was create my own js method that i will pass in three parameters (method,url,data)

Js method
I have create a js post method using xmlhttprequest posting data to my
php page. The problem is how i will get the data after post request is
successful and display on my html page Below is my code.
I am currently working on a project that i have to use js method to post,get delete other more. All I want is an idea of how to get the data deplayed when the submit form function is called after successful submission of the data.
The code is working the part but the feedback part
//define form variables
var formSubmition = document.getElementById('formSubmition');
//addEventListener
formSubmition.addEventListener('submit',dataSubmit,true);;
function pageView(){
//localstorage_cookie = localStorage setItem('userpage_id','27727');
}
// connect to server via XMLHttpRequest
function serverConnection(){
this.object = {
method:'',
url:'',
data:'',
connect:function(a,b,d){
if(window.XMLHttpRequest){
server_http = new XMLHttpRequest();
}else{
server_http = new ActiveXObject('Microsoft.XMLHTTP');
}
server_http.onprogress = function(event){
console.log(event);
}
server_http.onreadystatechange = function(e){
if(server_http.readyState == 4 && server_http.status == 200){
var res = server_http.responseText;
return res;
}
}
server_http.open(a,b,true);
//server_http.setRequestHeader("Content-type","application/x-www-
form-urlencoded");
server_http.send(d);
}
}
}
var conn = new serverConnection(),response_xmlhttp = new serverConnection();
function serverConn(c,method,URI,formdata){
//defining data configurations
c.object['method'] = method; //defined key data for method
c.object['url'] = URI; //defined key data for url
c.object['data'] = formdata; //defined key data for data
//store in global variables
var method,url,data;
method = c.object['method'];
url = c.object['url'];
data = c.object['data'];
c.object.connect(method,url,data);
}
//submit_data using the class conn
function dataSubmit(e){
e.preventDefault();
var formdata,method,URI,username,password;
//define username and password
username = document.getElementById('username').value;
password = document.getElementById('password').value;
if(username == '' && password == ''){
alert('fill in all the fields');
}else{
formdata = new FormData(this);
formdata.append('submit_data','SIGNIN');
method = 'POST';
URI = 'admin/php_data/loginCredentials.php';
serverConn(conn,method,URI,formdata);
}
}
You need to pass a call back function to serverConnection which it can call when it receives the data from backend, something alone the lines of
function serverConnection(cb){
this.object = {
method:'',
url:'',
data:'',
connect:function(a,b,d){
if(window.XMLHttpRequest){
server_http = new XMLHttpRequest();
}else{
server_http = new ActiveXObject('Microsoft.XMLHTTP');
}
server_http.onprogress = function(event){
console.log(event);
}
server_http.onreadystatechange = function(e){
if(server_http.readyState == 4 && server_http.status == 200){
var res = server_http.responseText;
cb(res);
return res;
}
}
server_http.open(a,b,true);
//server_http.setRequestHeader("Content-type","application/x-www-
form-urlencoded");
server_http.send(d);
}
}
}
and then create a function to handle response
function handleResponse(res) {
// set the res in some element
}
Now just pass it to server connection
var conn = new serverConnection(handleResponse)

How can I pass a parameter from javascript to RESTful web service using XMLHttpRequest

When i try to print the received parameter at the web service.
The parameter is empty.
If I view domain server log of glass fish server I can see the following
print:
Inside getJson()
countryKey =
So I understand the request arruved to the web service, but the parameter
that was sent from the javascript url is empty
// This is the code of the web service method
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson(String countryKey) {
System.out.println("Inside getJson()");
System.out.println("countryKey = " + countryKey);
return "countryKey = " + countryKey;
}
// This is the javascript method
function populateDistrictList() {
var element = document.getElementById("selectCountry");
var selectedCountryKey = element.value;
var selectedCountry = element.options[element.selectedIndex].text;
var xmlHttp = new XMLHttpRequest();
var url = "http://localhost:8080/MissionWS/webresources/generic?selectedCountryKey="+selectedCountryKey;
xmlHttp.open('GET', url, true);
xmlHttp.responseType = 'json';
if (xmlHttp) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
} else {
alert("Something is wrong !");
}
}
};
xmlHttp.send();
}
}
Please try adding the #QueryParam to your method signature as follows.
public String getJson(#QueryParam("selectedCountryKey") String countryKey)

Login using Javascript and REST

I made a REST service, which will return a String "hej" if the log in is true.
I have tested in Java with a rest client and it works fine, but pretty new to javascript and need some help.
I'm using this function
function UserAction() {
console.log(User());
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login");
xhttp.setRequestHeader("login", User());
xhttp.responseType = 'text';
xhttp.onreadystatechange = function () {
console.log('DONE', xhttp.readyState);
if (xhttp.readyState == 4) {;
// handle response
var response = xhttp.responseText;
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url;
}
}
};
// send the request *after* the callback is defined
xhttp.send();
return false;
}
function User() {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I show you the client i have i Java, maybe you can see why it's not working.
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
String root="http://localhost:8080/Footballmanagerrestservice/webresources/";
String functionPath="login";
String parameters="?username=s153518&password=holger";
Response res = client.target(root+functionPath+parameters)
.request(MediaType.APPLICATION_JSON).get();
String svar = res.readEntity(String.class);
System.out.println(svar);
}
first part of the code looks ok, the following instead must be handled inside a function because is intrinsically asynchronous
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
return false;
doc: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/onreadystatechange
essentially you're trying to handle the response as a syncrhonous call, but it's not, the response it's not immediatly avaiable, for this reason you have to register a callback (from the doc must be attached to the field onreadystatechange) that will be triggered by javascript as soon as the server response is available.
try to change it like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
// handle response
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
}
}
xhr.send();

Problems inheriting XMLHttpRequest / ActiveXObject classes

I have the following JavaScript class:
var Server = function(onError)
{
/* public As, onError; */
var that, Key, Headers;
this.__construct = function()
{
that = this;
that.As = false;
that.onError = onError;
that.resetHeaders();
onError = null;
// Here I try to call the parent constructor (it seems I can't).
if(window.XMLHttpRequest)
that.XMLHttpRequest();
else
that.ActiveXObject('Microsoft.XMLHTTP');
}
this.Request = function(File, PostData, Function)
{
var Method, HeaderKey;
if(PostData == null)
Method = 'GET';
else
Method = 'POST';
try
{
that.open(Method, File, that.As);
/* Each request sets X-Requested-With to XMLHttpRequest by default.
If PostData is given, then we treat it's content type as a form.*/
that.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if(PostData != null)
that.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
for(HeaderKey = 0; HeaderKey < Headers.length; HeaderKey++)
that.setRequestHeader(Headers[ HeaderKey ].Name, Headers[ HeaderKey ].Value);
if(Function != null)
that.onreadystatechange = function()
{
if(that.readyState == 4 && that.status == 200)
Function.call();
}
that.send(PostData);
}
catch(Exception)
{
if(that.onError != null)
that.onError(Exception);
}
}
this.addHeader = function(Name, Value)
{
Headers[ Key ] = {};
Headers[ Key ].Name = Name;
Headers[ Key ].Value = Value;
Key++;
}
this.resetHeaders = function()
{
Headers = [];
Key = 0;
}
this.__construct();
}
if(window.XMLHttpRequest)
Server.prototype = new XMLHttpRequest();
else
Server.prototype = new ActiveXObject('Microsoft.XMLHTTP');
Server.prototype.constructor = Server;
Where I make an inheritance depending on the state of the window.XMLHttpRequest var. In the __construct method I re-check this again for call the parent constructor.
I don't know if this is the correct form, but I would like that anyone could tell me what's wrong in here. By the way, when I check the console in Chrome I get the following exception: "Uncaught TypeError: Object [object Object] has no method 'XMLHttpRequest'", so I assume that it is not identifying the correct reference, however, I can see that all the properties / methods are present when I put the "." in the console, but I can't get access from a internal / external way (this is commenting the parent constructor condition). Thank you, I'll wait for your replies.

Categories

Resources