Passing a string array to mvc controllers using ajax - javascript

I need to pass list of strings from multiple select to the controller. Though the requirement looked very simple to me, I was breaking my head for the past hour in this. I have did a fair research on this, but unable to succeed.
Below is my Javascript code. Please ignore the comments. I was successfully able to fetch the list of items in the multiple select. While i do the ajax call, I get the error "Object reference not set an instance of an object.
function submitForm() {
var selected = $('#selectedTasks option').map(function(){
return this.value
}).get()
var postData = { selectedTasks : selected } //corrected as suggested
//selectedTasks = JSON.stringify({ 'selectedTasks': selected });
alert(postData);
$.ajax({
type: "POST",
//contentType: 'application/json; charset=utf-8',
url: '#Url.Action("AssignTasks", "MonthEndApp")',
dataType: 'json',
data: postData,
traditional: true,
success: function (data) {
alert("Success");
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
MonthEndAppController.cs
[HttpPost]
public void AssignTasks(List<String> selectedTasks)
{
//do something
}
Can someone guide me where exactly I have gone wrong? Can someone suggest me what is wrong?
EDIT : As suggested by Mr. Rory I have made the java script changes. Now the Java script part works absolutely fine. But the Controller is not getting called when the ajax request is made. Can someone help me out if something wrong in the call made to controller ?

Have you tried with string[] instead of List<String> ?

The parameter your AssignTasks action is expecting is called selectedTasks, not values:
var postData = { selectedTasks: selected };
Also note that when debugging anything in JS you should always use console.log() over alert(), as the latter coerces all types to a string, which means you're not seeing a true representation of the actual value.

Related

Ajax request not passing parameter to ASP.NET MVC controller

Tried looking in stackoverflow because this looked so trivial. Found many similar questions and read through them. Found no solution using these examples. Here is my code, can anyone help?
function testAjax() {
return $.ajax({
type: "GET",
url: '#Url.Action("Nodes","Competence", new { userId = Sven });',
contentType: "application/json;charset=utf-8",
dataType: "json"
});
}
var promise = testAjax();
promise.success(function (data) {
var dataConverted = JSON.stringify(data);
$('#tree').treeview({ data: dataConverted, multiSelect: true });
});
ASP.NET MVC method
public JsonResult Nodes(string userId)
{
var temp = userId;
var list = new List<Node>();
list.Add(new Node("Test1"));
list.Add(new Node("Test2"));
list.Add(new Node("Test3"));
return Json(list, JsonRequestBehavior.AllowGet);
}
EDIT:
Just before I was about to turn crazy on Halloween night, i figured out to try in a new session. Turns out it was just a caching problem..Thanks for the help everyone
Since your server may not expecting a request with JSON content, try removing the contentType parameter on your ajax call. Its default value is "application/x-www-form-urlencoded; charset=UTF-8" and is fine for most cases.
It's type should be "POST"
return $.ajax({
type: "POST",
url: '#Url.Action("Nodes","Competence")',
data: { userId: "Test" },
contentType: "application/json;charset=utf-8",
dataType: "json"
});
As it's a GET verb, it'll be easiest to pass this in as a querystring value. This also conforms better with a RESTful design.
For example replace #Url.Action("Nodes","Competence")
with
#Url.Action("Nodes","Competence", new { userId = id });
Then you can delete the data property. This will append ?userId=valueOfId into your url and then it should be mapped correctly to your action with the userId correctly populated.
Update
As #freedomn-m stated:
This will generate the url when the view is built server-side. If the
parameters never change, then fine - but it's relatively unlikely that
the parameters won't change, in which case you should add the url
parameters at runtime if you want them on querystring.
This is completely accurate. Without knowing your exact implementation I can only make assumptions. But technically you could wrap your ajax call in a function and then you could either pass in the userId and generate the url within that function or pass in the url, performing the url generation outside of the function.
This would mean that you only need one function that performs the ajax request and you can have another function that gets the userId (and possibly generates the url) and then passes that into the ajax function. How you store the userId is entirely up to you, but one thing I would suggest is investigating data attributes which is a fairly well defined way for storing data on html elements.

Data in ajax call not being passed to controller

I have this simple javascript in a Spring MVC with jQuery application:
console.log("POST Variables:",postVariables);
$.ajax({
type: "POST",
url: theUrl,
traditional: true,
data: postVariables,
complete: modelCallback,
fail : errorFunction
});
the console logs this:
POST Variables: applicationId=977
Which is correct. I have this in my controller:
public HashMap<String, Object> getApplication(HttpServletRequest request) {
String applicationId = (String) request.getParameter("applicationId");
logger.error("ApplicationId:"+applicationId);
Iterator<?> it = request.getParameterMap().keySet().iterator();
logger.error("Begining parameters:"+request.getParameterMap().keySet().size());
This produces null for the String applicationId, and a 0 for parameter map size. I originally had the method annotated with #RequestParam, but that failed and I could not figure out why. I removed that, and I see that the ajax call is not sending anything.
I have tried JSON, Javascript Object, and (in this example) a String of request parameters. I have tried with and without the traditional.
I AM using this call inside a callback function from a jQuery get function like this:
$.get(templateUrl).complete(callback);
But why is NOTHING getting to my controller?
UPDATE If I change it to a GET, the parameters are added at the end of the call like they should and everything works fine.
What is even stranger, is that this is in a function, that gets called before, and it works as a POST. same function. (different URL and data of course) but SAME function. Works once, then looks like it fails. Is there like some socket I need to close? I grabbing at straws here.
You should pass the data to the controller as key value pairs.Not with the equals sign in it.
For example, Not,
applicationId=977
it should be,
applicationId:977
add this for the ajax request.
$.ajax({
type: "POST",
url: theUrl,
traditional: true,
data: {applicationId : "Your application ID as a number"},
complete: modelCallback,
fail : errorFunction
});

Making an AJAX request to an MVC controller and getting the data from the response in js

On button click I am trying to send a product name value that the user enters into a textbox to the server to be modified and then back to the page using AJAX. I am getting into the ChangeName method in the controller but not getting into my success function to alert the new name.
The JS:
$("#changeNameButton").click(function () {
var productName = $("#Name").val();
$.ajax({
url: '/Products/ChangeName/',
type: 'POST',
dataType: 'JSON',
data: {name: productName},
success: successFunc
});
});
function successFunc(data) {
alert(data);
}
The controller:
public string ChangeName(string name)
{
string changedName = ChangeNameHelper(name);
return changedName;
}
If anyone can give recommendations on the proper way to make asynchronous calls to a controller in MVC5/6 this would be great.
My main problem is that I am never getting into the successFunc() on response.
Regarding your comment, if you return just a string MVC will convert that to json.
Now, in your updated code you still call a method inside itself. Please call string changedName = ChangeNameForResult(name); or any function with another name.
Install Newtonsoft.Json via nuget package manager and in your controller do this
Public ActionResult ChangeName(string name)
{
// get your object you want to serialize let's say res
return JsonConvert.SerializeObject(res);
}
I needed to set dataType: 'text' rather than JSON since I am returning a simple string.
dataType is the type of data being returned and contentType is the type of data being sent.

jQuery AJAX response JSON get child node

i am trying to take the responseJSON from an AJAX call and just extract one element to the variable formDigestValue. I have tried about a dozen ways of trying to return the response, using JSON.parse(), $.parseJSON() and some others, but there are 2 main issues that i cant seem to figure out. I put in a check for if (data.lenght > 0){do something}, response.length, responseJSON, jqXHR, XHR, i cant seem to find the variable that holds the data that would end up sent to success function. I've tried just setting the ajax call to a variable (var y = $.ajax()...) and manipulating it that way.
I just keep reading different articles and trying different ways, but nothing seems to quite get it right and it seems to be fairly simple, but i feel like im just missing something simple on this.
$(document).ready(function () {
var siteURL = "xxx";
var formDigestValue = "";
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(){
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.FormDigestValue;
}
});
...
any advice would be greatly appreciated. For reference, the JSON returned looks like the below. i am trying to figure out if i also need anything extra to get at child nodes, as it looks like it comes back buried a bit (i broke it out with indents just to show the depth):
{
"d":
{
"GetContextWebInformation":
{
"__metadata":
{
"type":"SP.ContextWebInformation"
},
"FormDigestTimeoutSeconds":1800,
"FormDigestValue":"0xADC9732A0652EF933F4dfg1EF9C1B75131456123492CFFB91233261B46F58FD40FF980C475529B663CC654629826ECBACA761558591785D7BA7F3B8C62E2CB72,26 Jun 2015 21:20:10 -0000",
"LibraryVersion":"15.0.4631.1000",
"SiteFullUrl":"http://example.com/",
"SupportedSchemaVersions":
{
"__metadata":
{
"type":"Collection(Edm.String)"
},
"results":["14.0.0.0","15.0.0.0"]
},
"WebFullUrl":"http://www.example.cm"
}
}
}
edit 6/27
Alright, I think between the comment on accessing the child nodes and the rest on passing the argument to success function, ive almost go it. My main thing is, I cannot seem to pass it as an argument. I tried to say it initially, but dont think I write the explanation properly. I tried:
Success: function(responseJSON)...
As well as
Success: function(data)...
But the data never seems to actually enter the function, its null values. I know the json returned, but having issues passing it into success function
Here is a look at firebug when this runs:
Try to add dataType option with json value and don't forget the callback success function take at least one parameter which is the data returned by the server.
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
dataType: 'json',
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(data){
console.log(data);
}
});
Posting from my iPhone, so, it's hard. From the first look, you're not capturing the returned result in success. Try the following.
success: function(responseJSON) {
contextHeaders = $.parseJSON(responseJSON);
if that block of json is what you get returned by $.parseJSON(responseJSON) then you're right, you just need to dig a bit deeper:
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.d.GetContextWebInformation.FormDigestValue;
hope that helps :)

Jquery POST unicode string to codeigniter php

I'm trying to implement a custom suggestion engine using jquery.
I take the user input, call my codeigniter v2 php code in order to get matches from a pre-built synonyms table.
My javascript looks like this:
var user_str = $("#some-id").val();
$.ajax({
type: "POST",
url: "http://localhost/my-app/app/suggestions/",
data: {"doc": user_str},
processData: false
})
.done(function (data)
{
// Show suggestions...
});
My PHP code (controller) looks like this:
function suggestions()
{
$user_input = trim($_POST['doc']);
die("[$user_input]");
}
But the data is NOT posted to my PHP :( All I get as echo is an empty [] (with no 500 error or anything)
I've spent 2 days looking for an answer, what I've read in SO / on google didn't help. I was able to make this work using GET, but then again, this wouldn't work with unicode strings, so I figured I should use POST instead (only this won't work either :()
Anyone can tell me how to fix this? Also, this has to work with unicode strings, it's an important requirement in this project.
I'm using PHP 5.3.8
Try using the $.post method, then debug. Do it like this:
JS
var user_str = $("#some-id").val();
var url = "http://localhost/my-app/app/suggestions";
var postdata = {doc:user_str};
$.post(url, postdata, function(result){
console.log(result);
});
PHP
function suggestions(){
$user_input = $this->input->post('doc');
return "MESSAGE FROM CONTROLLER. USER INPUT: ".$user_input;
}
This should output the message to your console. Let me know if it works.
For those interested, this works for me, even with csrf_protection being set to true
var cct = $.cookie('csrf_the_cookie_whatever_name');
$.ajax({
url: the_url,
type: 'POST',
async: false,
dataType: 'json',
data: {'doc': user_str, 'csrf_test_your_name': cct}
})
.done(function(result) {
console.log(result);
});

Categories

Resources