Jquery post to Action with Dictionary Parameter - javascript

I am feeling dejavu, but I cannot find the answer to this:
I have an array of objects that needs to look like this when inspecting a jQ $.post call:
limiter[0].Key
limiter[0].Value
so that it is mapped in the action
public ActionResult SomeAction(Dictionary<Guid, string> dictionary) { }
However, this javascript:
// Some Guid and Some Value
var param = [ { 'Key' : '00000000-0000-00000-000000', 'Value': 'someValue' } ];
$.post('/SomeController/SomeAction/',
{
dictionary: limiter,
otherPostData: data
},
function(data) {
callback(data);
}
)
produces this when inspecting it in firebug:
limiter[0][Key] = someKey // Guid Value
limiter[0][Value] = someValue
This is in jq 1.4.2. I seem to remember some flag you need to set to render json a different way in jQ. Does this ring any bells?

Try like this:
var param = {
'[0].Key': '28fff84a-76ad-4bf6-bc6d-aea4a30869b1',
'[0].Value': 'someValue 1',
'[1].Key': 'd29fdac3-5879-439d-80a8-10fe4bb97b18',
'[1].Value': 'someValue 2',
'otherPostData': 'some other data'
};
$.ajax({
url: '/Home/SomeAction/',
type: 'POST',
data: param,
success: function (data) {
alert(data);
}
});
should map to the following controller action:
public ActionResult SomeAction(Dictionary<Guid, string> dictionary, string otherPostData)
{
...
}

var dict = {}
dict["key1"] = 1
dict["key2"] = 2
dict["key3"] = 3
$.ajax({
type: "POST",
url: "/File/Import",
data: dict,
dataType: "json"
});
public void Import(Dictionary<string, int?> dict)
{
}
just send your obj as dataType: "json"

You can use this flag -
jQuery.ajaxSetting.traditional = true;
To get jQuery to post the data in a different format to the one you are seeing. See this question for further info -
Passing arrays in ajax call using jQuery 1.4

You will see the post param as limiter[0][Key] because jquery serializes the json data before it posts it. This is very well interpreted by the controller action and you get the required input in the action.

You can also use a list of objects and the result will be the same as what you wanted. This is a nice example.
http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery

Related

How to get array list data using ajax call (pass array list data controller to ajax method)

My controller class like that.
#RequestMapping(value = {"/ajaxcallabd"}, method = RequestMethod.POST)
#ResponseBody// <== this annotation will bind Arr class and convert to json response.
String addAnotherAppointmenttt(HttpServletRequest request, HttpServletResponse response, #RequestBody String userJson, Model model, BindingResult errors) {
System.out.println("*******88888" + userJson);
List<stageViiChartData> chartData = stageViiChartDataServices.findBystageViiChaData(userJson);
return chartData.toString();
}
The above code create the List data. I want to pass above list data using ajax call.
My ajax method like that.
$.ajax({
type: "POST",
url: "/MobitelProgressTool/ajaxcallabd",
data: userJson,
contentType: "application/json; charset=utf-8",
// dataType: 'JSON',
datatype:'text',
success: function (mJSONArray) {
alert(mJSONArray);
},
failure: function (erroes) {
alert(erroes + ">>>>>");//handle it in a proper way
}
});
But above mJSONArray is string type. I want to get Json type. I don't know how I create it.
my chartData array like that.
[[stageViiChartDataModal: Updated_Scope = Ericsson, Dependency = WIP, On_Air_date = 4-Dec-15], [stageViiChartDataModal: Updated_Scope = Ericsson, Dependency = WIP, On_Air_date = 9-Dec-15]]
Just do..
success: function (mJSONArray) {
var d = JSON.parse(mJSONArray);
alert(d);
},
Change your Content-Type Content-Type: application/jsonthen you can pass json arral list data.
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.ignoreAcceptHeader(true).defaultContentType(MediaType.TEXT_HTML);
configurer.ignoreAcceptHeader(true).defaultContentType(MediaType.APPLICATION_JSON);
}

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

Deserialize JSON into dictionary in Web Api controller

I have such JSON string:
'{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'
I want to send it to the Web Api Controller without changing using ajax request:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
data: JSON.stringify(sendedData),
dataType: "json"
});
In Web Api I have such method:
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}
And always sendedData == null. Another words: I don't know how to deserialize JSON into (Dictionary<int, List<int>>.
Thank you for answer.
Try this
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
var d1 = Request.Content.ReadAsStreamAsync().Result;
var rawJson = new StreamReader(d1).ReadToEnd();
sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);
}
You can send the data like this:
{"sendedData":[{"key":"1","value":[1,3,5]},{"key":"2","value":[2,5,6]},{"key":"3","value":[5,6,8]}]}
Image of the function in the controller:
Dict
Try it:
Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");
Try using:
public ActionResult Parse(string text)
{
Dictionary<int, List<int>> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<int>>>(text);
return Json(dictionary.ToString(), JsonRequestBehavior.AllowGet);
}
This works when the sent data doesn't have quotes around the indices:
{1:[1,3,5],2:[2,5,6],3:[5,6,8]}
Also make sure that you send an object in the Javascript:
data: {
text: JSON.stringify(sendedData)
},
specify the content type parameter when performing ajax call, dataType is for return result:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
contentType: "application/json; charset=utf-8", //!
data: JSON.stringify(sendedData)
});
You missed the [FromBody] annotation in the sendedData param. Try this:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public object Dict([FromBody] Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}

How to construct the POST data values in an AJAX call?

i've this piece of code that performs an AJAX call
$.ajax({
url : 'inviaCommento.php',
type : 'POST',
data : {page: page, category: category}
dataType : 'json',
success : function (msg)
//...and so on
The problem is that i want to check if a search parameter is set, if yes i've to add the word to the data parameters.
The question is: can i costruct the data parameters before the call appendig values to it?
Something like this:
if $('#searchBtn').val()!=''
{
data.append(search: $('#searchBtn').val())
}
Yeah, just create an array.
var data = {something: [], page: page, category: category, somekey: "default"};
data.something.push("a");
data.something.push("b");
if (...) {
data.somekey = "new value";
}
$.ajax({
...
data: data
});
Yup, but data isn't a list, it's an object, so you just assign to the appropriate key.
var data = {page:page}; // ... current value of data: param in the $.ajax call
if($('#searchBtn').val()!=='')
{
data.search= $('#searchBtn').val();
}
You'd put this above the $.ajax() call.

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