This question seems to have the answer to what I am trying to do, but it does not seem to work for me. The servlet posts fine and in the watch window I can see my json object there for the _parameters member variable of the servlet HttpRequest, but I can't seem to get the parameter out.
Here is my code.
Javascript:
// build data from input fields
var jsondata = '{"author":"TEST", "title":"XYZ"}';
$.ajax({
type : 'POST',
dataType : 'json',
data: jsondata,
url : '/submitquote',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
Servlet (I also tried with "author" and "title" but nothing comes back):
// get data
String postData = req.getParameter("jsondata");
This is what I see using variable watch for _parameters on the request object:
{{"author":"TEST", "title":"XYZ"}=}
How the heck do I get that stuff out?
Any help appreciated!
First, the datatype argument specifies the type of the data coming out, not the data going in.
Second, the data argument should give a dictionary of parameters, and one of the parameters in this case is the already-stringified JSON object:
var jsondata = {"author":"TEST", "title":"XYZ"};
$.ajax({
type : 'POST',
dataType : 'json',
data: { jsondata : JSON.stringify(jsondata)},
url : '/submitquote',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
Now, req.getParameter("jsondata") has the (still-JSON-stringified) data and you need to parse it yourself. JSON.org makes a very nice library you can use.
Two further notes:
There are two "jsondata" here. First is the JavaScript variable, assigned in the first line and used inside the stringify call; second is the Ajax parameter name, specified right after data: { and used in the getParameter call.
If you are really just passing "author" and "title", you can forget all about JSON and just use your original Javascript plus req.getParameter("author") and req.getParameter("title").
Related
I have a project with areas and would like to post a view model as JSON to a controller method.
This is what I have, with performance being generated in the default area and passed to the view in area SeatSelection:
$("#addToCartButton").click(function () {
var json = #Html.Raw(Json.Encode(performance));
$.ajax({
url: 'https://#(Request.Url.Host)/SeatSelection/Home/AddToCart',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
And the action method for testing:
[System.Web.Http.Route("SeatSelection_AddToCart")]
[System.Web.Http.HttpPost]
public JsonResult AddToCart(PerformanceViewModel performance)
{
return Json(performance.Name);
}
I created the following route:
context.MapRoute(
"SeatSelection_AddToCart",
"SeatSelection/Home/AddToCart",
new { action = "AddToCart", controller = "Home", id = UrlParameter.Optional },
namespaces: new string[] { "myProject.Areas.SeatSelection.Controllers" }
);
But all I get is a internal server error 500. I also tried to use [FromBody] and setting a breakpoint to the method, but it is not invoked. I can't figure out what's wrong or missing, please help.
UPDATE
This is the json / performance:
PerformanceID=00000000-0000-0000-0000-000000000000&Name=Performance+15&StartDate=%2FDate(1360364400000)%2F&EndDate=%2FDate(1500328800000)%2F&LatestDateBookable=%2FDate(1450911600000)%2F&Organizer=Organizer+15&Location=Location+15&Availability=75&IsFull=false&IsBookable=true&HasPrice=true&BookableSeats=11&BookedSeats=94&Description=Description+of+Performance+15&Price=443
I found an error: "invalid json primitive: performanceid"
First of all, I would recommend you to use #Url.Action helper method instead of generating url like this: https://#(Request.Url.Host)/SeatSelection/Home/AddToCart.
Secondly, always validate params which comes from the browser. return Json(performance.Name) looks suspicious. What is performance will be null? This might be a problem of your internal server error 500.
If this is not a problem then try to send string instead of JSON to the server and validate and parse JSON on the server side.
You can use Url.Action method like this. I suppose SeatSelection is an area in your project.
$.ajax({
url: '#Url.Action("AddToCart", "Home", new { Area = "SeatSelection"})',
This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'
I have following Json returned from an web api
{"PayHistories":
[{"Id":3,"RateChangeDate":"2014-09-03T06:00:00","Rate":10.00,"PayFrequency":7,"JobTitle":"Production Manager","Gendre":"M"}],
"JobCondidates":
[{"Id":3,"Resume":null,"JobTitle":"Production Manager","Gendre":"M"}],
"JobAssignments":
[{"Id":2,"DateStarted":"2014-09-03T05:00:00","DateFinished":"2014-09-03T05:00:00","DepartmentName":"Sales And Distributations","JobTitle":"Production Manager","SupervisorName":"Production Manager"}],
"Skills":
[{"Id":3,"SkillName":"Designer","DateSkillAcquired":"2014-09-03T06:00:00","SkillLevelCode":"103"},{"Id":4,"SkillName":"Agile Developer","DateSkillAcquired":"2014-09-03T06:00:00","SkillLevelCode":"104"}]
}
I want to save every Node into seperate knockoutjs observableArray()
here is
my code
self.skills=ko.observableArray();
self.PayHistories=ko.observableArray();
self.JobCondidates=ko.observableArray();
self.JobAssignments=ko.observableArray();
var employeeUri='/api/employees/';
function ajaxHelper(uri, method, data) {
//Clear error message.
self.error('');
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
})
.fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllEmployees() {
ajaxHelper(employeesUri, 'GET').done(function (data) {
// data is successfully loading into this data variable in this done function.
//But i want to store data seperatly into specific observableArray() say i want to store Skills int self.Skills observableArray()
});
}
I want to load data to proper observable for every node for Skills i want to store in self.Skills observable, for JobAssignements i want to store it into self.JobAssignments observableArray and voice versa. Thanks in Advance.
Have you tried Knockout's mapping plug-in. That would seem to do what you want automatically.
i need help ! i want to retrieve json data from a Codeigniter server.
This is my html local file (d://myproject/index.html)
$.ajax({
type: "POST",
url : serverUrl+'mobcontroller/users/',
crossDomain: true,
async: false,
data : $("#formlogin").serialize(),
dataType : MobileJsonType[1],
beforeSend : function(){//do stuff here},
success : function(responseData) {
alert(JSON.stringify(responseData));
},
error : function(jqXHR, textStatus, errorThrown) {
// do stuff here
},
complete: function(xhr, settings){
alert(JSON.stringify(xhr)+'\n'+settings);
}
});
and codeigniter controller look like this
public function index()
{
$type_message = 'success';
$message = 'Mobile plateform';
$this->output->set_header("Access-Control-Allow-Origin: *");
$this->output->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
$this->output->set_status_header(200);
$this->output->set_content_type('application/json');
$this->output->_display();
echo json_encode( array('type_message' => $type_message, 'message' => $message) );
}
i obtain json data response with the js error
Uncaught SyntaxError: Unexpected token :
Please help me!
Change your success function to
success: function(data) {
console.log(data)
}
and let us know what the output is.
I'm unfamiliar with codeigniter but is it possible that $this->output->_display(); echos something which the JS is trying to parse? If you place
ob_clean();
above your
echo json_encode(...
it will clear the buffer which was going to be sent back to the JS, and that way only your encoded JSON will go back which the JS can parse.
You ajax request should be something like this.
$.ajax({
type: "POST",
url : serverUrl+'mobcontroller/users/',
crossDomain: true,
async: false,
data : $("#formlogin").serialize(),
beforeSend : function(){//do stuff here},
success : function(responseData) {
alert(JSON.stringify(responseData));
},
error : function(jqXHR, textStatus, errorThrown) {
// do stuff here
},
complete: function(xhr, settings){
alert(JSON.stringify(xhr)+'\n'+settings);
}
});
I have removed propertydata dataType : MobileJsonType[1]
Also you dont need to use JSON.stringify.
The returned result is already json due to php's json_encode
And the error you are facing is due to beforeSend because beforeSend first hits the server to check if the request is allowed or not. if it sends true the actual request will proceed otherwise you need to handle it yourself. I assume you need to send some token with serialized data. Hope it helps. if you remove property beforeSend the request will work fine i think.
I'm setting up a select2 with the following JavaScript
$j("#" + name).select2({
placeholder: "",
width:"300px",
minimumInputLength: 3,
ajax: {
url: "/MyService.asmx/ServiceMethod",
dataType: 'json',
data: function (term) {
return {
q: term // search term
};
},
results: function (data) {
alert('results');
return {results: data};
},
success: function() {
alert('success');
},
error: function () {
alert('error');
},
},
});
The method I'm calling is the following:
<WebMethod(enableSession:=True)>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function ServiceMethod(q as String) As String
Dim temp As String = "[{'id':'35','text':'Drew'}]"
Return temp
End Function
I also have <ScriptService()> around the class. The enableSession is there because eventually I'm going to be running a lot of logic in the service that requires it, but for now I'm just trying to return a simple string with JSON.
I've put a breakpoint in the webservice, and I know it is being called. I know it is returning the JSON. I also know that the select2 expects "id" and "text" in the JSON return
My problem is the following: after I input 3 characters, the data function calls (I put an alert in it), the webservice breakpoint is hit, but none of the results, success, or error events fire afterwards. The select2 just spins and nothing ever happens. No javascript errors are entered in the console, and I'm at a loss about even where to look for information as to why the ajax isn't handling the returned value from the service.
Can anyone point me in the direction of at least where to look to see why this isn't working?
So I fixed this myself after getting a hint to look at the network log. The service was returning correctly, but it was returning XML, not JSON. I had to make 2 modifications and everything worked.
My working ajax:
ajax: {
url: "/MyService.asmx/ServiceMethod",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
The important changes were the type, putting the contentType in the params wrapper, and JSON.stringify-ing the data. I'm going to change what's passed and how its passed, but things are at least communicating now. Hope this helps anyone else who was looking for a similar solution.