send the request id with XMLHttpRequest to the serverside - javascript

Here I deployed the Get request with Id to pass from the client-side to the server-side to download excel file according to the Id.
client-side js file
$scope.getAUGFile = function () {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var params = JSON.stringify({ articleId: articleId });
var url = RESOURCES.USERS_DOMAIN + '/AUGFile/excelDownload/'
xhr.open("GET", url+"?"+params);
xhr.setRequestHeader("authorization", getJwtToken());
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status === 200) {
saveAs(xhr.response, "mvvAUGExcelTemplate.xls");
}
};
xhr.send(null);
};
server-side js file(spring boot)
#RequestMapping(value = "/AUGFile/excelDownload/{articleId}", method = RequestMethod.GET)
public ResponseWrapper excelGenerateAUG(HttpServletRequest request, HttpServletResponse response,#PathVariable Long articleId){
try{
fileService.downloadAUGFile(request,response,articleId);
return ResponseWrapper.successWithMessage(messageSource.getMessage("success_code",null, Locale.ENGLISH));
} catch (Exception e){
lOG.error(">> Excel file Download error", e);
return ResponseWrapper.failWithMessage(messageSource.getMessage("fail_code", null, Locale.ENGLISH));
}
}
When I execute the client-side function, In the serverside take the articleId value as NULL. How can I fix it? Any advice, help, pointers welcome!

first
console.log(articleId) inside your function to see if its defined and accessible to xhr to send
& try this this instead xhr.open("GET", url+articleId);
or try this
xhr.open("GET", url+"?articleId="+articleId);

I got the correct way of this! It is working now.
client-side js file
$scope.getAUGFile = function () {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var url = RESOURCES.USERS_DOMAIN + "/AUGFile/excelDownload/"+articleId;
xhr.open("GET", url);
xhr.setRequestHeader("authorization", getJwtToken());
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status === 200) {
saveAs(xhr.response, "mvvAUGExcelTemplate.xls");
}
};
xhr.send(null);
};
server-side js file
#RequestMapping(value = "/AUGFile/excelDownload/{articleId}", method = RequestMethod.GET)
public ResponseWrapper excelGenerateAUG(HttpServletRequest request, HttpServletResponse response,#PathVariable("articleId") String articleId){
try{
fileService.downloadAUGFile(request,response,articleId);
return ResponseWrapper.successWithMessage(messageSource.getMessage("success_code",null, Locale.ENGLISH));
} catch (Exception e){
lOG.error(">> Excel file Download error", e);
return ResponseWrapper.failWithMessage(messageSource.getMessage("fail_code", null, Locale.ENGLISH));
}
}

Related

Byte array from backend is converted to something else on front-end

[Route("encrypted")]
[HttpGet]
public sbyte[] Encrypted()
{
var mm = System.IO.File.ReadAllBytes("C:\\test\\" + "fill.txt");
sbyte[] sbt = new sbyte[mm.Length];
Buffer.BlockCopy(mm, 0, sbt, 0, mm.Length);
return sbt;
}
when I hover over with mouse it shows following bytes (which is correct):
But when I check on the front-end (javascript). It becomes a different arrayBuffer:
Here is the front end code:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/encrypted/', true);
xhr.responseType = 'arraybuffer'; //i have tried without this line too
xhr.onload = function (e) {
if (this.status === 200) {
console.log("received from server--------");
console.log(e.currentTarget.response);
console.log("received from server-------");
}
};
xhr.send();
You did not ask a specific question, but I think this might help.
Your controller action is responding with JSON. Dumping json to the console shows the same array values on the front-end as does dumping sbt to the console on the back-end. Here is the front-end code that dumps the values.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/values', true);
xhr.responseType = 'json';
xhr.onload = function (e) {
if (this.status === 200) {
console.log("json");
const json = e.currentTarget.response;
console.log(json);
console.log("json");
}
};
So, you're sending a JSON array.
As an aside, here are some links about the arraybuffer response type.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

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)

JavaScript: How to get http response as a result of click

I'm trying to get response of GET request, that starts after document.getElementById('btnPdf').click();
I'm using Selenium Webdriver as JavaScriptExecutor.
My question is similar to this How do I capture response of form.submit but I don't know exact url and would prefer to use pure JS without AJAX (if it's possible).
function get
Response() {
var send1='senddata'; // this is a var to send
var send2='senddata2'; // this is another var to send
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myGetPageName',true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onload = function() {
if (xhr.status === 200) {
var myResponse = xhr.responseText;
alert(myResponse);
}
};
xhr.send('myvar1=' + send1 + '&myvar2=' + send2)
}

XDomainRequest open("get", url) gives Access Denied error in IE

I'm using following code in one of my JavaScript file.
xhr = new XMLHttpRequest();
xhr.open("GET", dest, true); // dest is the URL
xhr.onreadystatechange = checkData;
xhr.send(null);
But when I run the script in IE,m it is giving me following error.
SCRIPT5: Access is denied.
Then I thought to check the browser type and execute a separate code for IE like below.
if(isIE){
xhr = new XDomainRequest();
xhr.onerror = function (res) { alert("error: " + res); };
xhr.ontimeout = function (res) { alert("timeout: " + res); };
xhr.onprogress = function (res) { alert("on progress: " + res); };
xhr.onload = function (res) { alert("on load: " + res); };
xhr.timeout = 5000;
xhr.open("get", dest); // Error line
xhr.send(json);
}
But again it is giving me the same error where I have used following code
xhr.open("get", dest);
At the end I want to call checkData function like I have done below with other browsers.
xhr.onreadystatechange = checkData;
What have I missing there to get Access Denied error at the IE console?
Try below.. It worked for me in IE8 and IE9.
if ($.browser.msie && window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", serviceURL+'GetItem/50000');
xdr.onload = function() {
//parse response as JSON
var response1 = $.parseJSON(xdr.responseText);
if (response1 == null || typeof(response1) == 'undefined') {
var result = $.parseJSON(data.firstChild.textContent);
alert(result);
} else {
$(response1.ResultData).each(function(i, item) {
alert(item.BorrName.toString());
});
}
};
xdr.send();
xdr.onerror = function(errormsg) {
alert('in error');
};
}
Service looks like below
[OperationContract]
[WebGet(UriTemplate = "GetItem/{itemnumber}", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
ItemEntity GetItem(string itemnumber);

function to return string in javascript

I am trying to call an ajax request to my server for json data using a function. If I console out the resp variable inside the ajax function it will show the data successfully. If i try to set the ajax function to a variable, and then console that variable it returns undefined. Any ideas who to make the function request the data and then set ti to a variable to be consoled?
function jsonData(URL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
return resp;
}
}
xhr.send();
}
jsonString = jsonData(http://mywebsite.com/test.php?data=test);
console.log(jsonString);
This is actually pretty simple.. Change your call to by synchronous..
xhr.open("GET", URL, false);
That being said this will block the browser until the operation has been completed and if you can use a callback instead it would likely be preferred.
function jsonData(URL, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
cb(resp);
}
}
xhr.send();
}
jsonData("http://mywebsite.com/test.php?data=test"
, function(data) { console.log(data); });

Categories

Resources