AJAX request cannot pass DateTime to server if using GET method - javascript

I have a form which uses Kendo controls, and when user click the button, an AJAX request gathering these controls' value will be sent to server and download a file based on these criteria. One of the controls is DateTimePicker.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '#Url.Action("MyGenerateReportMethod")',
async: true,
data: getViewModel(),
...
});
function getViewModel() {
...
viewModel.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return JSON.stringify({ para: viewModel });
}
public ActionResult MyGenerateReportMethod(MyModel para)
{
try{
...
}
}
public class MyModel
{
public DateTime? DateFrom { get; set; }
}
The above simplified code demonstrate my situation.
I have a POST ajax request to server, which passes a serialized JSON object including a Kendo DateTimePicker Value.
The server side action try to catch this JSON object as parameter and do the stuff which is irrelevant to this question.
My question is, for some reason I have to changed the request from POST to GET.
While it works using POST method, it does not work if I change "POST" to "GET".
I checked the request sent in Chrome's Developer Tools, It does sent the JSON object in the following format: (In Query String Parameters section in the Network Tab)
{"para": {
...
"DateFrom":"2016-04-13T16:00:00.000Z"
...
}
}
However, at server side, MyModel para does not seems to catch this object successfully (if I change from "POST" to "GET"). Other fields still can be bound while all DateTime fields become null.
Why is this happening, and how can I change the request from "POST" to "GET"?
Thanks.
EDITED
Based on some comments / answers, I have tried to modified the AJAX request to the following code, but it is still not working... (Same behavior)
$.ajax({
type: 'GET',
url: '#Url.Action("SumbitOutstandingReportList")',
data: getPlanViewModel(),
async: true,
...
}
function getPlanViewModel(){
var obj = {};
...
obj.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return { para: obj };
}

A GET does not have a body, so remove the contentType: "application/json; charset=utf-8", option (does no harm but its only applicable to a POST) and adjust the data so that the ajax call is
$.ajax({
type: 'Get',
url: '#Url.Action("MyGenerateReportMethod")',
data: getViewModel(),
...
});
function getViewModel() {
var obj = {};
...
obj.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return obj; // return the object, not a stringified object containing another object
}
Note this assumes the value is in a format that matches your server culture, or in ISO format (e.g. the request will be DateFrom: '2016-04-13T16:00:00.000Z')

This is happening because of, GET method is pass data in a header or url, while json data can not passed through header, change the method of passing data, which is currently in a json format.
You could do like even :
var fd = new FormData();
fd.append('data', yourData);
and send fd as a directly data object, it will work.

GET request has no body, it passes the parameters in either cookies or URL query string, so pass the data you want in a query string parameter like below:
var url = #Url.Action("MyGenerateReportMethod",new {DateFrom="_X_"});
url = url.replace("_X_",$("#DateRangeFrom").data("kendoDatePicker").value());
$.ajax({
type: 'GET',
url: url,
async: true
});

Related

Ajax Data Call with or without slash in Codeigniter getting error

suppose my URL is example.com/controller/method/
when I use this ajax code it makes URL like example.com/controller/method/method which not getting data.
function getProductList() {
var category = document.getElementById('Category').value;
$.ajax({
type: 'POST',
url: 'GetProductList',
data: {CategoryId: category},
dataType: 'json',
cache:false,
success: function (response) {
}
});
}
but when my URL is example.com/controller/method then ajax getting data correctly. but i want to get data from the database on both situations.
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. So you can not use example.com/controller/method/method.The segments in a URI normally follow this pattern: example.com/class/function/id/ , So your last method argument treated as a id. so create method in controller with the default argument Ex. public function mymethod($method = ''){ /** Your logic goes here */ }

Problem sending information between Django template and views using AJAX call

I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page.
With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix.
This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert.
var arr = { City: 'Moscow', Age: 25 };
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = norm_data.toString();
alert( norm_data );
}
});
This is my Django URLs code to receive the request:
path('applications/1/normalize', views.normalize, name="normalize")
This is the python view to retrieve the code and send it back to the javascript file:
from django.http import JsonResponse
def normalize(request,*argv,**kwargs):
norm_data = request.POST.get(*argv, 'true')
return JsonResponse(norm_data, safe = False)
You need to parse your Object to an actual json string. The .toString() will only print out the implementation of an objects toString() method, which is its string representation. By default an object does not print out its json format by just calling toString(). You might be looking for JSON.stringify(obj)
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = JSON.stringify(norm_data);
alert( norm_data );
}});
I've observed that there's a difference between POST data being sent by a form and POST data being sent by this AJAX request. The data being sent through a form would be form-encoded whereas you are sending raw JSON data. Using request.body would solve the issue
from django.http import JsonResponse
def normalize(request):
data = request.body.decode('utf-8')
#data now is a string with all the the JSON data.
#data is like this now "arr%5BCity%5D=Moscow&arr%5BAge%5D=25"
data = data.split("&")
data = {item.split("%5D")[0].split("%5B")[1] : item.split("=")[1] for item in data}
#data is like this now "{'City': 'Moscow', 'Age': '25'}"
return JsonResponse(data, safe= False)

Issue sending json from JQuery to MVC Controller

I'm sending Json from Jquery to an Action Controller, but for some reason, the first and the last elements from the Json string are not being received correctly in my action controller, it seems that a curly brace is being added as a value to the last element , and the first element is always null when is a nullable field or if it is an int its value is 0.
This is my JQuery code:
$(function () {
$("#myButton").click(function () {
var student= JSON.stringify($("#myForm").serialize());
alert(student);
$.ajax({
type: 'post',
url: $("#myForm").data("url"),
data: JSON.stringify({ 'policy': student}),
success: //more code..
})
I'm using an alert to show the value of the $("#myForm").serialize() and the values are being set correctly when the alert is executed. The problem is on the way to the action controller. This is what the alert message shows:
"first_field=7.5&aut_id=3456690&..........more info in here no
problem..........&birthday=&last_field="
For that json string when is received by the Action Controller this is what it get: first_field= null(is a nullable field in my Model)
And last_field = "\\\"\"}" .It contains 3 escape characters so I imagine that the value is receiving is = \""}
What should be happening??? All the other values that are in the middle are being received correctly, it's just he ones in the edges
This is my action controller:
[HTTPPost]
public ActionResult EditStudent(Student student)
{
//some code...
}
You can just send the data using the serialized data
$.ajax({
....
data: $("#myForm").serialize(),
which will use the default 'application/x-www-form-urlencoded; charset=UTF-8' for the contentType
If you stringify the data, then you need to also set the contentType to 'application/json', so that the DefaultModelBinder uses the JsonValueProvider to convert your data, and in that case the format needs to be
$.ajax({
....
data: JSON.stringify($("#myForm").serialize()),
contentType: 'application/json; charset=UTF-8',

Why is my json object empty in my ASP API?

I'm trying to test my asp api.
One of the endpoints needs to take a json object from a browser. To test this I'm placing a json object into a text field and then making an ajax call to my api. When the api is hit, the json object is always null.
I've checked this post: how to pass json post data to web api method as object and that did not resolve my issue.
Here is my object:
{ "userName": "063bcdf2-36fd-4b8c-a5af-808da63744f6",
"password" : "Password"
}
Here is my ajax call:
var submission = function () {
var url = urlBase + "/api/Submission/";
var testdata = $("input[name=submission]").val();
alert(testdata);
$.ajax(url, {
type: "POST",
data: JSON.parse(testdata),
contentType: 'application/x-www-form-urlencoded'
}).always(showResponse)
return false;
};
And here is my api:
[HttpPost]
[ResponseType(typeof(SubmissionOutputModel))]
public IHttpActionResult POST([FromBody]SubmissionInputModel submission )
{
if (ModelState.IsValid)
{
SubmissionService service = new SubmissionService();
return Json(service.Submit(submission));
}
else
{
return BadRequest("Invalid Model State");
}
}
SubmissionInputModel:
public class SubmissionInputModel
{
[Required]
public string userName { get; set; }
[Required]
public string password { get; set; }
}
The alert in the ajax shows me that the data is being sent and in debug mode, the api is getting hit however the submission object is not getting set to the data being sent from the ajax call.
If anyone can help, it would be greatly appreciated!
I think you need to JSON.stringify instead of parse, since parse if used the other way around.
JSON.parse takes a string and converts it to a JSON object.
Try to stringify your testdata
$.ajax(url, {
type: "POST",
data: JSON.Stringify(testdata),
contentType: 'application/x-www-form-urlencoded'
}).always(showResponse)
return false;
};
If that doesn't work, leave out the contentType from the ajax call, or write contentType:"application/json" instead.
And also post your SubmissionInputModel. Could be some naming that is wrong there :)
What does the "testdata" look like? Is it already a string in json format?
1.The JSON.Parse parses a string as JSON only, for example:
JSON.parse('{}'); // {}
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
2.The content-type should application/json in your case, and the value you specified now is default value:
contentType: 'application/json'
3.At the mean time, as your action already marked as [POST] so the ModelBinder will try to bind your model from the request body, so it is not necessary to specify as [FromBody].
Okay, I found my happy place!
The following ajax call finally got the data through to the API:
var submission = function () {
var url = urlBase + "/api/Submission/";
var testdata = $("input[name=submission]").val();
alert(testdata);
$.ajax(url, {
type: "POST",
data: testdata,
contentType: 'application/json'
}).always(showResponse)
return false;
};
Notice that there is no JSON method on the data in the call and the contentType is 'application/json'.
Thank you everyone for your help. I hope this helps the next poor soul that runs into this problem!

Jquery ajax post to MVC2 action

I'm using the following script to post to and endpoint, it's hitting the breakpoint on the server so I know the routing is correct.
$(document).ready(function() {
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(o),
dataType: 'json',
url: 'home/PingBack',
success: function(result) {
alert(result.success);
}
});
});
The endpoint on the server looks like this.
public JsonResult PingBack(MHolder message)
{
return Json(new { success = "steve"});
}
and the Model looks like this.
public class MHolder
{
public string message { get; set; }
}
I'm sure that in the past the values have been automatically bound to the model, but I can't seem to get anything to be bound atm! Even if I just pass the value as a string, I'm sure it's something silly that I'm missing any ideas?
A few things to notice. You are sending the request as a JSON string (contentType: 'application/json' and JSON.stringify(o)) while on the server you are expecting an object of type MHolder. The default model binder won't do this transformation. You will need to either write a custom model binder capable of deserializing JSON back to an MHolder instance or send the request as key=value pairs (do not stringify):
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
data: o,
dataType: 'json',
url: 'home/PingBack',
success: function (result) {
alert(result.success);
}
});
The code seems OK to me, at first glance.
try using...
data : {message : "Hi from the page."},
...to see if this causes the MHolder instance to be populated.
Also, use something like Fiddler to capture your requests and allow you to see exactly what is being posted.

Categories

Resources