I'm using SAPUI5 and I have a XML form that I wanna send the data to my REST service using Json Model.
I'm using the SAPUI5 MVC model to make my app.
How can I send the data to my server with REST and JSON?
sap.ui.controller("controller.NewTicket", {
onInit: function() {
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.attachRoutePatternMatched(this._handleRouteMatched, this);
},
_handleRouteMatched:function(evt){
if("NewTicket" !== evt.getParameter("name")){
return;
}
var id = evt.getParameter("arguments").id;
var model = new sap.ui.model.json.JSONModel({id:id});
this.getView().setModel(model,"data");
},
enviar:function() {
jQuery.sap.require("sap.m.MessageBox");
// open a fully configured message box
sap.m.MessageBox.show("Confirmar a abertura do chamado?",
sap.m.MessageBox.Icon.QUESTION,
"Confirmar",
[sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
function(sResult) {
if(sResult == sap.m.MessageBox.Action.YES)
{
var oModel = new sap.ui.model.json.JSONModel();
var aData = jQuery.ajax({
type : "POST",
contentType : "application/json",
url : "http://192.168.0.32:9082/maxrest/rest/mbo/sr/?description="+ **deviceModel.sr.description** +"&_format=json&_compact=true&_verbose=true",
dataType : "json",
async: false,
success : function(data,textStatus, jqXHR) {
oModel.setData({modelData : data});
sap.m.MessageBox.show("ABRIU");
},
error : function(data,textStatus, jqXHR) {
oModel.setData({modelData : data});
sap.m.MessageBox.show(textStatus);
}
})}
else
{
}
},
sap.m.MessageBox.Action.YES);
var deviceModel = new sap.ui.model.json.JSONModel({
sr : [{
description: "",
long_description: ""
}]});
deviceModel.setDefaultBindingMode("TwoWay");
sap.ui.getCore().setModel(deviceModel);
jQuery.sap.require("sap.m.MessageToast");
sap.m.MessageToast.show(deviceModel.getData().sr.description);
}
});
And the View...
<mvc:View xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:co="sap.ui.commons"
xmlns:f="sap.ui.layout.form" xmlns:core="sap.ui.core" controllerName="com.maximo.controller.NewTicket">
<Page id="NewTicket" enableScrolling="true" title="{i18n>newTicket}" >
<content>
<f:SimpleForm >
<core:Title level="H5"
text="O chamado será aberto em seu nome e você será o usuário afetado"/>
<Label text="Resumo"/>
<Input type="Text" maxLength="100" value="{/sr/description}"/>
<Label text="Detalhes"/>
<TextArea height="50%" cols="800" value="{/sr/long_description}"/>
</f:SimpleForm>
</content>
<customHeader>
<Bar>
<contentLeft>
<Button icon="sap-icon://nav-back" press="voltarMenu"/>
</contentLeft>
<contentMiddle>
<Label text="{i18n>newTicket}"/>
</contentMiddle>
</Bar>
</customHeader>
<footer>
<Bar>
<contentMiddle>
<Button id="btnSend" text="{i18n>send}" press="enviar" icon="sap-icon://add-activity-2"/>
</contentMiddle>
</Bar>
</footer>
</Page>
From my experience I found out that it's easier to use an OData model of "JSON" type.
var user = applicationContext.registrationContext.user;
var password = applicationContext.registrationContext.password;
var uri = "http://" + user + ":" + password + "#" + applicationContext.registrationContext.serverHost + ":8080/" + appId + "/"
var headers = {
//"Authorization" : "Basic " + btoa(applicationContext.registrationContext.user + ":" + applicationContext.registrationContext.password),
"X-SMP-APPCID" : applicationContext.applicationConnectionId
};
console.log("Try comunicating the first time");
var oModel = new sap.ui.model.odata.ODataModel(uri, {json : true}, user, password, headers, false, false, false);
oModel.setHeaders(headers);
oModel.read("/Brand", onSuccess);
function onSuccess(result) {
sap.ui.getCore()....getView().getModel("Brands").setData(result);
};
It's how I do all my requests, manual or automated (on manual event or page event).
For an "post" event, I used a token fech:
oModelRequest.setHeaders({
"Access-Control-Allow-Origin" : "*",
"Content-Type": "application/x-www-form-urlencoded",
"X-CSRF-Token":"Fetch"
});
// Declare a variable to handle the security token
var token;
// Create a read request to retreive the X-CSRF token
oModelRequest.read('/Brand', null, null, false,
function(oData, oResponse) {
if (oResponse.headers['x-csrf-token'] == undefined) {
//alert("Error on read process. No token ! Check read !");
}
token = oResponse.headers['x-csrf-token'];
},
function() {
alert(oModeli18n.getProperty("Brand_token_error"));
}
);
And after that I do the actual "POST" with the "Create" method:
// Set POST request header using the X-CSRF token
oModelRequest.setHeaders({
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
"DataServiceVersion": "2.0",
"Accept": "application/atom+xml,application/atomsvc+xml,application/xml",
"X-CSRF-Token": token
});
// Call the create request
oModelRequest.create('/Brand', requestData, null,
function(oData, oResponse) {
alert (Success);},
function(oData) {
alert(Error));
alert(oData.response.body);}
);
Related
This is my view file Book.cshtml script section. The problem coming is that it not fetching my data from my database.
Instead it is giving a error:
alert("Failed! Please try again.")
If I truncate the data from the database it shows ONLY the heading "BOOK ID" "BOOK NAME" "BOOK SERIAL NUMBER" "BOOK AUTHER" "BOOK PUBLISHER NAME"
$(document).ready(function () {
// This is for Get All Data
$("#btnAllBook").click(function () {
$.ajax({
url: "#Url.Action("GetAllBook","Books")",
data: "",
type: "GET",
dataType: "json",
success: function (data)
{
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
// this will use for Get Data based on parameter
$("#btnSearch").click(function () {
$.ajax({
url: "#Url.Action("GetBookWithParameter", "Books")",
data: { prefix: $('#txtSearch').val() },
type: "GET",
dataType: "json",
success: function (data) {
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
function loadData(data) {
// Here we will format & load/show data
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Book ID</th>');
thead.append('<th>Book Name</th>');
thead.append('<th>Book Serial Number</th>');
thead.append('<th>Book Auther</th>');
thead.append('<th>Book Publisher</th>');
tab.append(thead);
$.each(data, function (i, val) {
// Append database data here
var trow = $('<tr></tr>');
trow.append('<td>' + val.BookID + '</td>');
trow.append('<td>' + val.BookName + '</td>');
trow.append('<td>' + val.BookSerialNumber + '</td>');
trow.append('<td>' + val.BookAuther + '</td>');
trow.append('<td>' + val.BookPublisher + '</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#UpdatePanel").html(tab);
};
});
Looking into the documentation on http://api.jquery.com/jquery.ajax/, the callback error is called because the request failed. Then, I suggest you to check if the url #Url.Action("GetAllBook","Books") is returning the right string of the url, maybe you are trying to request in a url that doesn't exists.
Another point, being about a GET request, I suggest you to check opening in a browser if this URL that you are trying to return data, is returning the JSON data expected as you need to append to the HTML.
I have a google script running as a webapp to handle the backend of a slack app.
The app has been Authenticated and I have the OAUTH token from this.
I can currently post to a channel with button actions using the chat.postMessage using the for-mentioned token.
Actions url points back at my webapp and hook in via doGet, from this response i construct a JSON object.
var response_payload = {
"token" : access_token,
"ts" : message_ts,
"channel" : channel_id,
"text" : "Approved! you are a winner!"
})
response_url = "https://slack.com/api/chat.update";
sendToSlack_(response_url, response_payload)
posted via the following function:
function sendToSlack_(url,payload) {
var options = {
"method" : "post",
"contentType" : "application/json;charset=iso-8859-1",
"payload" : JSON.stringify(payload)
};
return UrlFetchApp.fetch(url, options)
}
however returned is the following:
{"ok":false,"error":"not_authed"}
I can't find any documentation about this error other than the following
Sending JSON to Slack in a HTTP POST request
However this is in regard to a chat.postMessage request of which in my implementation is working correctly.
You need to put token to header instead of json payload if using application/json. Here is doc for this.
So you request should look like this:
POST /api/chat.update HTTP/1.1
Authorization: Bearer xoxp-xxx-xxx-xxx-xxx
Content-Type: application/json;charset=UTF-8
{
"channel": "xxx",
"text": "Hello ~World~ Welt",
"ts": "xxx"
}
Note: there is no token field in payload.
Well according to the link your provided, Slack does not accept JSON data (weird).
Also, after playing around with their tester, Slack seems to be doing a GET request on https://slack.com/api/chat.update with query parameters attached like this:
https://slack.com/api/chat.update?token=YOUR_TOKEN&ts=YOUR_TIME&channel=YOUR_CHANNEL&text=YOUR_TEXT_URL_ENCODED&pretty=1
So use this code:
var response_payload = {
"token" : access_token,
"ts" : message_ts,
"channel" : channel_id,
"text" : "Approved! you are a winner!"
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
response_url = encodeURI("https://slack.com/api/chat.update?token=" + response_payload['token'] +
"&ts=" + response_payload['ts'] + "&channel=" + response_payload['channel'] + "&text=" + response_payload['text'] +"&pretty=1");
httpGet(response_url);
Ok! thankyou all for your input.. certainly I have learned a little more. After tweeting at slack_api my original code more or less worked as is.. I had to JSON.parse(payload); the payload in order to then access the object parameters within.. the full example is as below.
function post_update(url, payload) {
var options =
{
'method': 'post',
"payload" : payload,
};
var result = UrlFetchApp.fetch(url, options);
return result.getContentText();
}
function doPost(e) {
var payload = e.parameter.payload;
var json = JSON.parse(payload);
response_url = "https://slack.com/api/chat.update";
// get object elements
var action = json.actions[0].value;
var user = json["user"].name;
var message_ts = json["message_ts"];
var channel_id = json["channel"].id;
if (action == 'approved') // payload if action is 'approved'
{
var response_payload = {
"token" : access_token,
"ts" : message_ts,
"channel" : channel_id,
"text" : "Approved! *" + invitation_name + "* has been sent an invite!",
"attachments" : JSON.stringify([{
"text": ":white_check_mark: Approved by #" + user,
}])
}
}
if (action == 'denied') // payload if action is 'denied'
{
var response_payload = {
"token" : access_token,
"ts" : message_ts,
"channel" : channel_id,
"text" : "Denied. *" + invitation_name + "* has been declined an invite",
"attachments" :JSON.stringify([{
"text": ":exclamation: Declined by #" + user,
}])
}
}
post_update(response_url, response_payload);
return ContentService.createTextOutput().setMimeType(ContentService.MimeType.JSON);
}
I have a simple java application on Spring MVC and I send ajax request to Spring controller. When I set headers "Accept", "application/json" and "Content-Type", "application/json;charset=utf-8" in AJAX call I get error 400 in dubugger, when I delete it I get error 415.
If I change controller method signature to public String logoutPage (#RequestBody String obyavleniye) I get JSON string. What problem can be with parse request in controller?
JS method:
$("#advertForm").submit(function(e) {
e.preventDefault();
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var obyavleniye = {
title: "Title",
price: "80",
description: "desc",
date: "2016-11-07 18:30:21",
authorid: "2",
category: "A",
state: "new",
img1: "http",
img2: "http",
img3: "http",
img4: "http",
};
var post_data = JSON.stringify(obyavleniye);
console.log(post_data);
$.ajax({
url : "/upload",
type: "POST",
dataType: 'json',
data: post_data,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xhr.setRequestHeader(header, token);
},
complete: function() {
console.log("Sent");
},
success: function (response) {
console.log("success");
console.log("response" + response);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
Controller method:
#ResponseBody
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String logoutPage (#RequestBody Advert obyavleniye) {
// public String logoutPage (#RequestBody String obyavleniye) {
System.out.println("Enter: " + obyavleniye);
this.advertService.addAdvert(obyavleniye);
// return "{\"msg\":\"success\"}";
return "{\"title\":\"Title\",\"price\":\"80\",\"description\":\"normm\",\"date\":\"2016-11-07 18:30:21\",\"authorid\":\"2\",\"category\":\"A\",\"state\":\"new\",\"img1\":\"http\",\"img2\":\"http\",\"img3\":\"http\",\"img4\":\"http\"}";
}
My sample code.
js
Company.prototype.saveCompanyLocation = function() {
/* company */
var companyIdx = $('#companyIdx').val();
var locationIdx = $('#locationIdx').val();
var data = {
idx : locationIdx,
postCode : $('#postCode').val(),
address : $('#address').val(),
detailAddress : $('#detailAddress').val(),
tel : $('#tel').val(),
fax : $('#fax').val(),
email : $('#email').val(),
language : $("#language").val(),
latitude : $('#latitude').val(),
longtitude : $('#longtitude').val()
};
data = JSON.stringify(data);
$.ajax({
url : "/gpim/company/settings/location/save/" + companyIdx,
type : 'POST',
data : data,
contentType : 'application/json',
success : function(response) {
if (response == "success") {
document.location.reload(true);
} else {
$("#editMsg").text("you can`t save location information.");
}
},
error : function(request, status, error) {
}
});
};
controller
#RequestMapping(value = "/settings/location/save/{companyIdx}", method = RequestMethod.POST)
public #ResponseBody String saveLocation(#PathVariable int companyIdx, #RequestBody CompanyLocation location) {
Company company = companyService.findCompanyByIdx(companyIdx);
company = companyService.saveCompanyLocation(company, location);
if (company != null) {
return "success";
}
return "fail";
}
Do the below steps:
1) try to keep the jackson jar files in your classpath
2) eighter you have remove the datatype while sending ajax request i.e,
dataType : "json"
or you have to produce the application/json response as below
#RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
3) Check your DTO or Advert class properties which type should be matched with incoming request. i.e request params should match with DTO members both names and type.
These are possible ways to avoid your case.
I have copied the routine how to perform a post action towards Domino Access Service inspired by the example described here:
http://www.browniesblog.com/A55CBC/blog.nsf/dx/09042013111234MBRF6E.htm?opendocument
The problem is that all properties get submitted except the Form property. Why is this?
$(document).ready(function() {
$(".btnRegister").click(function(e) {
var firstName = $(".firstName").val();
var lastName = $(".lastName").val();
var email = $(".email").val();
var password = $(".wannebepassword").val();
var newName = $(".firstName").val() + " " + $(".lastName").val();
if (newName !== " ") {
var newPersonObj = {Form: "Person", FirstName: firstName, LastName: lastName, FullName: newName, InternetAddress: email, HTTPPassword: password, Form: "Person"};
$.ajax({
url: 'http://server/names.nsf/api/data/documents',
type: 'POST',
data: JSON.stringify(newPersonObj),
dataType: 'xml',
accepts: {
xml: 'text/xml',
text: 'text/plain'
},
contentType: "application/json"
}).done(function(data, textStatus, jqXHR) {
var newPersonLocation = jqXHR.getResponseHeader("Location");
$("#formResponse").html('Registration successfull. Location = ' + newPersonLocation + '<br>' + $("#myConsole").html());
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("Registration has failed:" + errorThrown );
console.log('Registration has failed.');
});
}
else {
alert("Please enter a name");
}
return false;
});
});
Try to add a field in your form with the name (I suggest also HTML Tag: ID) FORM, editable with default value:
Form
NB editable is not mandatory, Computed is also possible.
Could not find exact matches for the question (some similar posts found) ..
How can multiple models be send via JSON to MVC3 controller e.g having the following parameters:
public JsonResult Add(Project pr, List<Modules> mod)
{
}
following technique was tried but did not work
function AddModules() {
var pname = $("#ProjectName").val();
var data = new Array();
var modules = new Array();
$("#ModuleTable tr").each(function () {
var row =
{
"ModuleName": $(this).find(".moduleName").val(),
"ModuleDesc": $(this).find(".moduleDesc").val(),
"ModuleSize": $(this).find(".moduleSize").val(),
"StartDate": $(this).find(".startDate").val(),
"ModuleId": "",
"ProjectName": pname
}
modules.push(row);
});
var project =
{
"ProjectName": $("#ProjectName").val(),
"ProjectDescription" : $("#ProjectDescription").val(),
"StartDate" : $("#ProjectStartDate").val(),
"ModuleName" : modules
}
data.push(project);
$.ajax({
url: "AddProject",
data: JSON.stringify(data),
type: "post",
contentType: "application/json; charset = utf-8",
dataType: "json",
success: function (status) {
alert(status);
}
});
}
The project class also contains a List type of Module class.
You are sending a string of JSON back to the server, so you have a type difference. Try something like this instead:
Client Side
var myFunction = function(){
var projectName = $("#ProjectName").val();
var projectDescription = $("#ProjectDescription").val();
$.post("[URL TO YOUR CONTROLLER]",{pName : projectName, pDescription: projectDescription},function(response){
alert(response);
});
};
Server Side
public ActionResult MyActionResult(FormCollection fc)
{
var projectName = fc["pName"];
var projectDescription = fc["pDescription"];
var result = projectName + " hase been posted!";
return Content(result);
}
Good luck!