I have that POST method:
function saveSchemaInDatabase(schemaName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName);
}
and i am catching that shoot in my controller in that way:
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName) {
return "redirect:/user";
}
Can someone tell me how i can send multiple params to that controller? For example i want something like that:
//shoot
function saveSchemaInDatabase(schemaName, diagramJson) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName, diagramJson);
}
//catch
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName, #RequestBody String diagramJson) {
return "redirect:/user";
}
I hope you know what i mean. Of course my way doesn't work. Error 400 appears.
Can someone help me? Im done :(
You can crete FormData object and add as many values as you want inside it
var data = new FormData();
data.append("email", "eve.holt#reqres.in");
data.append("password", "pistol");
Then send this formData object to the post request
Like this
xhttp.send(data);
Related
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));
}
}
I am having problem sending base64 image data using ajax post
I think I have the wrong value for Content-Type but have tried application/json, text/json and image/jpeg without any success
Javascript
function sendFormData(fD)
{
var urls = fD.get('urls');
console.log('urls', urls);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
alert(urls);
xhr.setRequestHeader("Content-type", "image/jpeg");
xhr.send(urls);
}
Browser console shows
["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMWFhUXGRgbGBgXGR0aGRgXHRgYFx4YGxkYHiogGh4lGxgdIjEhJSkrLi4uGh8zODMtNygtLisBCgoKDg0OGhAQGy0lHSUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIANEA8QMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAECBwj/xABGEAACAQIEBAQDBAUJCAIDAAABAhEDIQAEEjEFIkFREzJhcQaBkRRCobEjUsHh8AcVM2JygsLR8RZDRFNzg5KyJDSzw8T/xAAZAQADAQEBAAAAAAAAAAAAAAABAgMABAX/xAAqEQACAgEDBQACAQQDAAAAAAAAAQIRAxIhMQQTFEFRImGRYnGh8AUjMv/aAAwDAQACEQMRAD8AsoosJt9cSpSdeYKYEXxKlQs4E2kEx6dMWJFBEDr0OPey5nCrR58MalwJUpB1nENbJWthpTyQDG5H5Y0gGqNQOJLLXA7h9K9VypGITSPbD+tSGIFy4mSJx0xz7EXjE7UscacNamW30jAlbLsNxiscqZNwoCK4wDEzJjkLiuoQjGNEYnCY5ZcawkMY5bEkY5GGsUijG1XtjcYPyFAQWMbbdsac9Ks0Y2wQphlwTKLUZg2wAwFmq8m5HYY5HFTRph0VnBI1QDZZgsZGwEnHPmn/ANb+lMcVqLFWRafKMTU+L6bRb88V/LcY+0otQKVmbdcbq1wsSYkgDfc7C3fHIoRlDVIs5tSpFzyXEtcdCdvlhopwp4RSpwvcAf64bj0x5mbSpUjrhdbmicSU1xi08djEWylGRjRGOsC5uodl379sBK2F8HbMAJxUON5lqrQFMA4f1CVU62ke2FaZlWqXgAbepx29MtD1VZzZXaol4RwYKsuAWP4…
Java Server code
public String updateArtwork(Request request, Response response)
{
System.out.println("Received artwork");
for(String s:request.queryParams())
{
System.out.println("---"+s);
}
System.out.println("ReadParms");
return "";
}
just outputs
Received artwork
ReadParms
Updated to Send as Form Instead
// Once we got everything, time to retrieve our objects
function sendData()
{
var fD = new FormData();
// send Files data directly
var files = imgList.filter(
function isFile(obj)
{
return obj.type === 'file';
}
);
files.forEach(
function appendToFD(obj)
{
fD.append('files[]', obj.file);
}
);
// for elems, we will need to grab the data from the server
var elems = imgList.filter(
function isElem(obj)
{
return obj.type === "element";
}
);
var urls = elems.map(
function grabURL(obj)
{
return obj.element.src;
}
);
if (urls.length)
fD.append('urls', JSON.stringify(urls));
sendFormData(fD);
};
function sendFormData(fD)
{
// but here we will just log the formData's content
var files = fD.getAll('files[]');
console.log('files: ', files);
var urls = fD.get('urls');
console.log('urls', urls);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(fD);
}
then on server I have
public String updateArtwork(Request request, Response response)
{
System.out.println("Received artwork");
for(String s:request.queryParams())
{
System.out.println("***"+s);
System.out.println(request.queryParams(s));
}
System.out.println("ReadParms");
return "";
}
and its outputs
Received artwork
***-----------------------------330219842643
Content-Disposition: form-data; name
"urls"
["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSEhUSExIWFhUXFxgXGBcYFRgXFxkdGBcWGBgYFx0YHSggHR0lHRkYITEhJSkrLi4uFyA1ODMtNygtLisBCgoKDg0OFQ8PFSsZFRkrLSstLSstKysrLS03KystLSstKy03LSstLSstNzc3KysrLS0tKysrKysrKysrKysrK//AABEIAKoBKQMBIgACEQEDEQH...."]
-----------------------------330219842643--
ReadParms
So I'm now getting the data but I don't understand really understand how to parse the Content-Disposition part in Java.
This code wasn't originally written by me, as you can see the FormData is constructed it doesnt come from an actual form. My first attempt was to try and extract from FormData and send in different way, an alternative would be to not store in FormData in the first place but dont know how to do this.
Update 2
Tried just sending first url rather than formdata or an arrya of urls, because actually there is only ever one url.But it just doesnt work, nothing received by server ?
function sendFormData(urls)
{
console.log('urls', urls[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
xhr.setRequestHeader("Content-type", "text/json");
alert(JSON.stringify(urls[0]));
xhr.send(JSON.stringify(urls[0]));
}
You are trying to view data in the body using queryParams(), which will give you the query params that are located in the url.
Load data from the request body using body().
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/
I am trying to POST a JSON object to a servlet via AJAX. However, the object is null in the servlet. I am unable to figure out what's wrong with this code.
JAVASCRIPT
function submitValues(event, val1, val2)
{
var xmlHttpObj = new XMLHttpRequest();
if(window.XMLHttpRequest)
{
xmlHttpObj = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");
}
var jsonObject = submitTheValues(event, val1, val2);
alert("json is:" +jsonObject);
var json = JSON.stringify(jsonObject);
alert("json after stringify:" +json);
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/json");
xmlHttpObj.send(json);
}
SERVLET
String jsonObj = request.getParameter("json");
If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode.
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");
xmlHttpObj.send('json='+encodeURIComponent(json));
Is this possible?
xmlHttp.send({
"test" : "1",
"test2" : "2",
});
Maybe with: a header with content type : application/json?:
xmlHttp.setRequestHeader('Content-Type', 'application/json')
Otherwise I can use:
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
and then JSON.stringify the JSON object and send it in a parameter, but it would be cool to send it in this way if it's possible.
With jQuery:
$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });
Without jQuery:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));
If you`re not using jQuery then please make sure:
var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
And for the php receiving end:
$_POST['json_name']
I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.
Wrap up content like below,
var params = {
"IDs": IDs,
"ID2s": IDs2,
"id": 1
};
In my case I had already json'd the arrays and passed the result to the function
var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());
Then call the XMLHttpRequest POST and stringify the object
var ajax = new XMLHttpRequest();
ajax.open("POST", '#Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
var blob = new Blob([this.response], { type: "application/octet-stream" });
saveAs(blob, "filename.zip");
}
};
ajax.send(JSON.stringify(params));
Then have a model like this
public class MyModel
{
public int[] IDs { get; set; }
public int[] ID2s { get; set; }
public int id { get; set; }
}
Then pass in Action like
public async Task<IActionResult> MyAction([FromBody] MyModel model)
Use this add-on if your returning a file
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
Adding Json.stringfy around the json that fixed the issue