This question already has answers here:
JQUERY ajax passing value from MVC View to Controller
(6 answers)
Closed 3 years ago.
I'm trying to pass the id and the value of some textboxes from the view to the controller. The ajax call works, but the value that it pass is always Null. How can i solve this problem??
This is the ajax call:
function TakeInput() {
var count = document.getElementsByTagName('input').length;
var element = document.getElementsByTagName('input');
for (var i = 0; i < count; i++) {
$.ajax({
type: 'POST',
url: '#Url.Action("Input", "Home")',
data: JSON.stringify(element[i].id, element[i].value),
processData: false,
success: function () {
//make something
},
error: function (errorThrown) {
alert(errorThrown);
}
})
}
And this is the controller:
public JsonResult Input(string id, string value)
{
//do something with the id and the value
return Json(new { result = "Success" });
}
Thanks in advance for your time and your answers.
If you are looping the ajax call ,you can bind an object and pass it to controller then you can iterate it in server side. Whatever according to your code you can try the below one
$.ajax({
type: 'POST',
url: '#Url.Action("Input", "Home")',
data: JSON.stringify({ id: element[i].id, value: element[i].value}),
dataType: 'json',
async: false,
contentType: 'application/json',
success: function () {
//make something
},
error: function (errorThrown) {
alert(errorThrown);
}
})
When you are making an ajax call you need to declare the parameter like you declared in your json result for example id,value etc and bind it into data attribute
Related
I want to pass the variable from view to controller I am using ajax call to achieve it i am getting the error below. I don't know what i am missing here.
WARN 41440 --- [nio-8080-exec-9] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
This is my code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "UserController/delete",
contentType: "application/json; charset=utf-8",
data: {key:myvalue},
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
My controller method looks like below
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String key) {
System.out.println("My Array value"+key.toString());
return key;
}
What i am missing here? Any Help
Finally i could able to pass the values from my view to controller I am posting the code.
This is my js code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
var myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "/delete",
dataType : "JSON",
contentType:"application/json; charset=utf-8",
data: JSON.stringify(selchbox),
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
And my controller code
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String value){
System.out.println("My Array value"+value.toString());
return value;
}
First, if you want to delete, why not use the verb delete http?
I think you are not using the correct parameter: RequestParam is used to map your sORGID parameter to the URL (a parameter you did not use on the client side, you must use it or delete it).
If you want to map Json, you must use #RequestBody.
I hope it helps
At leaset two problems
url: "UserController/delete" in your ajax won't match "/delete/{sORGID}" in your controller.
data: {key:myvalue} in your ajax, the property name is key, in your controller it's myvalue[], this should also be the same.
I have a problem posting a value from java-script in my razor page to a controller. - the value received is always null.
I have seen similar questions being asked, but have not been able to find the right solution to the problem.
I get to a break point in the controller, (so the routing is okay) but the parameter value passed is always null, and not being the sharpest in java-script, I would like some tips from you folks.
I basically have the java-script below:
var clickButton = function (buttonId) {
$.ajax({
type: "POST",
async: false,
cache: false,
crossDomain: false,
contentType: "application/json; charset=utf-8",
url: "v1/buttons",
dataType: "json",
data: '{ buttonId:'+JSON.stringify( "buttonId" ) + '}',
success: function (result) {
//console.log("clickButton OK => " + result);
}, //success: function (result) {
timeout: 500 // 0.5 sec.
}); //$.ajax({
}//var clickButton = function(buttonNo) {
and the C# controller code below too:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult OnButtonClicked( string buttonId )
{
// buttonId = null !!!
...
I have a similar problem getting a boolean value across to another controller.
where the bool is always false.. i.e. the default value.
I am wondering if it is a security issue, with not allowing the post to contain data, when the user is unauthorized...
The problem was in the JSON, and I got the value through with this minor change, but it was hiding well.
var clickButton = function (buttonNo) {
console.log("clicked: " + buttonNo);
$.ajax({
type: "POST",
url: "v1/buttons/",
dataType: "json",
data: { "buttonId": buttonNo }, // < === this is where the problem was !!
success: function (result) {
}, //success: function (result) {
}); //$.ajax({
}//var clickButton = function(buttonNo) {
I've changed the controller to receive a string to id the button.
And it now looks like this:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult PostButtonClick( string buttonId ) {
// buttonId now has a value !!!
}
}
i am writing a function in jquery which post the data to controller. currently it is posting form data to controller fine but when i post checkbox list with form data then it send always count 0 in controller here is my code.
function SubmitForm() {
var studentFormData = $("#frmStudent").serialize();
debugger;
var SubjectArraydata = new Array();
$(".chkSubject:checked").each(function () {
var row = {
"SubjectId": $(this).data("id")
};
SubjectArraydata.push(row);
});
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
async: true,
success: function (msg) {
},
error: function () {
}
});
}
Controller:
[HttpPost]
public ActionResult StudentForm(Student student, List<Subject> subjectData)
{
return Json(true);
}
any one tell me where is the problem in my code thank you.
Your cannot mix 'application/x-www-form-urlencoded' data (the contentType of your serialize() method) and 'application/json' data (the contentType of the JSON.stringify() method) like that.
Sinve you have confirmed that your only submitting one property of Subject, which is SubjectId and is typeof int, then you can append the SubjectId values to the serialized data.
var studentFormData = $("#frmStudent").serialize();
$(".chkSubject:checked").each(function () {
studentFormData += '&' + $.param({ SubjectIds: $(this).data("id") });
};
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData,
success: function (msg) {
},
error: function () {
}
});
and change your controller method to
[HttpPost]
public ActionResult StudentForm(Student student, List<int> SubjectIds)
{
....
I think you use 'POST' method not correctly. You try to mix sending data as json and as url parameters.
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
what you send in data:
[
{...},
[{SubjectId: ''}, {SubjectId: ''}]
]
or:
{
1: {...},
subjectData: [{SubjectId: ''}, {SubjectId: ''}]
}
or some data sended as json, some in url?
Send all data in json, and dont serialize (jquery do it for you):
var data = [strudentFormData, subjectData];
$.ajax(..., data: data, ...);
I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm using an AJAX call in a function to retrieve some data from the server, in this way:
getPolicies: function() {
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
return jsonList;
},
failure: function(err) {console.log("Error");}
});
}
I correctly get the JSON array:
[
{
"policyName": "policy1"
},
{
"policyName": "policy2"
},
{
"policyName": "policy3"
}
]
This JSON array is returned by the function.
But when I call the function getPolicies() I only get an empty JSON object {}. Specifically, if i try
var policies = getPolicies();
console.log(policies[1].policyName);
I get this:
Uncaught TypeError: Cannot read property 'policyName' of undefined
So, how is possible that even if I correctly get the JSON array, the function returns an empty object?!
Thanks...
Even though the AJAX request is synchronous *), the return statement still returns only from the success handler. Try something like this:
getPolicies: function() {
// Declare variable here
var resultList = null;
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
// Set the variable in the scope of getPolicies.
resultList = jsonList;
},
failure: function(err) {console.log("Error");}
});
// This one actually returns getPolicies
return resultList;
}
But in general, it's regarded bad practice to make AJAX calls synchronous. Instead, you can better call the necessary functionality from the success handler. That can also be another function. For instance, you can declare
function processPolicies(policies)
{
console.log(policies[1].policyName);
}
And your call handler can look like this (:
$.ajax({
async: true, // just let it run,
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
processPolicies(jsonList);
},
...
*) The first A even stands for Asynchronous. But on the other hand, the X stands for XML, so what you're doing here should actually be called JaJ rather than AJAX. ;)