I have a simple Web API application which can GET or POST data back to the user.
Data being a simple array of Strings, ["foo", "bar"]. If I try and POST data to the Web API, the data is read successfully into the POST method, but upon returning to the Web API with another call, the data previously Posted would not be there anymore.
How do I keep the data on the Server with every POST.
This is what is on my server:
[HttpPost]
public HttpResponseMessage Post([FromBody]string value)
{
data.Add(value);
var msg = Request.CreateResponse(HttpStatusCode.Created, "Added element");
msg.Headers.Location = new Uri(Request.RequestUri + "/" + (data.Count - 1).ToString());
return msg;
}
Sending a POST with data = John Doe will add it to a List<String> called data, but it won't persist upon returning to the server.
This is how I am calling the server:
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data), // data = "John Doe"
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
Essentially, how can I make "John Doe" persist on the server when sending a POST to it. Making the List<String> data = ["foo", "bar", "John Doe"]
List<String> data = simply won't work and persist as you would expect cause that list is defined in your API controller and it gets destroyed after every request since on every request you get a new controller instance.
If you really want to persist it then Cache the data by using any kind of caching mechanism distributed cache like Redis or non-distributed one.
Related
I'm trying to send the data I gathered from my web app to a google spreadsheet.
I'm using the script from Martin Hawksey:
https://gist.github.com/mhawksey/1276293
I've set it up and did everything as shown in the manual. And I am getting data back, but it's showing up as undefined values:
This is the code I use to send the JSON string to my spreadsheet:
function sendData(){
var url = 'https://script.google.com/macros/s/AKfycby3SUJvfEjdHWVoEON0L5hN4uXod8M4Jv1LAIWH3Ny16MIUz9o/exec';
var data = JSON.stringify(member);
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: function (response) {
console.log("succes! I sent this: " + data);
console.log("got this back: " + JSON.stringify(response));
},
});
}
This gives me a success message, it even tells me which row it was placed on.
This is the JSON string I'm sending:
{"Voornaam":"Name","Achternaam":"Name","Mail":"x#x.com","Verjaardag":"0/0/0000","Foto":"https://graph.facebook.com/xxxxx/picture?width=1020","School":"School X","Richting":"Course X"}
I even checked this JSON with a JSON parser online and it didn't return any errors.
For starters, I'm not entirely sure how to check which string I'm receiving at my spreadsheet. If it's still correct when it arrives. I tried logging it, but can't seem to get any response from the google logger.
If anyone could point out what I'm doing wrong, you would be greatly appreciated!
The Web script expects a JSON object. However, Ajax call is made with a string using the stringify function
var data = JSON.stringify(member);
Modifying the script to make the GET call with JSON object as is resolved the issue, like so
var data = member;
I am trying to pass some data from the frontend to the backend of my site using AJAX. This is the post request view in my django views:
def post(self, request):
id_ = request.GET.get('teacherID', None)
print(id_)
args = {}
return JsonResponse(args)
This is the function I have in javascript. I know the correct value is being passed because the console.log(teacher_id) prints the right value.
function send(teacher_id){
console.log(teacher_id)
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'teacherID': teacher_id,
},
dataType: 'json',
success: function (data) {
//location.href = data.url;//<--Redirect on success
}
});
}
When the code is run, and the print statement in my view is run, regardless of what the teacher_id is, None is printed.
what is wrong with the code?
In your Django view the data is being retrieved using GET.get() while the AJAX request is sending it using method: "POST".
POST data can't be retrieved in the same way as GET data so you should either change the way the data is being send (by changing the method in the AJAX call to GET) or read it using the related POST methods.
You can visit this Stack Overflow question if you are doubting which method to use.
Below is the code which i m trying to send. As you can see, ajax call is made at UI and data 'sub' is passed through. this 'sub' has an array of objects in it. So data is present when it is passed.
UI SIDE
$scope.save = function () {
var sanit = $scope.gridOptions.rowData;
var sub = JSON.stringify(sanit);
$.ajax({
type: 'POST',
url: '/api/Pr/PM',
data: sub, //this has data in it
contentType: "application/json"
}).success(function (response) {
window.alert("Database updated successfully.");
})
};
However, when i debug the code at backend, the parameters is showing as null. i have commented the section showing this is null where the data is showing as null at the start of backend function.
BACKEND C# SIDE
[HttpPost]
public HttpResponseMessage PM([FromBody] string parameters) //this is null.
{
string message = string.Empty;
try
{
var model = JsonConvert.DeserializeObject<List<PODetails>>(parameters);
message = "Insert Successfull";
return Request.CreateResponse(HttpStatusCode.OK, message);
}
catch (Exception ex)
{
message = "Insert fail";
return Request.CreateErrorResponse(HttpStatusCode.NoContent, message);
}
}
Can someone please let me know why it is showing as null value at backend.
You need to ensure the data you're sending via AJAX is an object with a single parameter, which should be named the exact same as the parameter your backend is expecting.
In this case:
$.ajax({
type: 'POST',
url: '/api',
data: JSON.stringify({ parameters: sub }),
contentType: "application/json"
}).success(function (response) {
...
})
Next, if the variable "sub" is an array of objects then you must create a class model server side to match the structure of the data being sent. Then, your API's interface should be expecting a list of that newly created class.
For example:
[HttpPost]
public HttpResponseMessage PM(List<YourClassModel> parameters)
{
...
}
Your API should now be able to receive and read the data being sent via the AJAX call above.
Take a look at this: Post a json object to mvc controller with jquery and ajax
You are sending a list of objects but trying to recieve it as string. You should change your function parameter from (String parameters) to (List parameters) and change your ajax request according to the link above. That will probably solve your problem.
(ps: i couldn't try it myself that's why i said probably :) )
According to this post Remove String from JSON, I want to fill a Dojo Selectbox with JSON Data. The Problem is that I have to change the JSON Data before I can handout the data to the dijit.form.select Box.
I get the data via JsonRest. The question if, how I can load the Json Data into a normal object variable? I tried this here but it did not work.
var processStore = new JsonRest({
target: "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit",
headers: {"Authorization": "Basic a2VybWl0Omtlcm1pdA=="},
allowNoTrailingSlash: false
});
var processes = processStore.query("",{});
I simply want to load the JSON data from the JsonRest store in a normal variable.
Thank you
The JsonRest store only accepts an array, so you're not able to retrieve the data, because your store is not able to read that data for you.
If you're only interested in reading the data (so no updating/creating/deleting has to be done), the easiest way is to retrieve that data using an AJAX request and manually put it inside a dojo/store/Memory store, for example:
require([ "dojo/request/xhr", "dojo/store/Memory" ], function(xhr) {
var url = "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit";
xhr(url, {
handleAs: json
}).then(function(data) {
if (data.data !== undefined) {
var myStore = new Memory({
data: data.data
});
// Do something with "myStore"
});
});
If you're interested in the full capabilities of the JsonRest store, you will have to extend it by yourself. If you look at the code you can see several AJAX requests, in:
get()
put()
remove()
query()
Now you can write your own store and extend those methods.
I need to save some data and return the ID that is created in the SQL 2005 database. I need the ID to pass to another object before saving that so I can associate them correctly.
What is the best way to accomplish this with Ext? Is there anything built into the Framework that makes this simple?
Thanks.
function AddPromotionType() {
var currentDate = new Date();
var newTypeJsonObject = {
promotionTypeId: '0',
promotionType: Ext.getCmp('txtPromoType').getValue(),
updatedBy: userid,
updateDate: currentDate
}
// serialize our service object
var newLevelJsonData = Ext.encode(newTypeJsonObject);
// call the web service and pass over our service object
Ext.lib.Ajax.defaultPostHeader = 'application/json';
Ext.Ajax.request({
url: 'Service/AddPromoType',
method: 'POST',
params: newLevelJsonData,
success: function(response, options) {
AddTypeWindow.destroy();
AddTypeWindow.hide();
// refresh dropdown to reflect new data
Ext.getCmp('newPromoType').getStore().reload();
},
// if data fails to save, show message
failure: function(response, options) {
Ext.MessageBox.alert('Error saving new promotion type', response.responseText);
}
});
}
Assuming your server is passing back the updated data with the new id the response param of your success callback should contain it. When using the facilities built into Stores that automate Ajax calls (e.g., Ext Direct, REST API support, etc.) the id gets automatically updated on the appropriate Record for you and you can handle the store's add event to inspect the Record. However, since you're doing a manual Ajax call it's up to you to inspect your response if you need the id immediately.