controller is not recognizing #requestparam from ajax - ajax

i am trying to send json from ajax to springboot controller but getting error [org.springframework.web.bind.MissingServletRequestParameterException: Required Item[] parameter 'myJsonString[]' is not present]
below is my ajax code
$.ajax({
type: "POST",
url: "/DBA_TOOLS/admin/tracker",
data: {myJsonString:myJsonString},
dataType: "json",
success: function (data){
if(data.status == "SUCCESS"){
alert("AJAX request successfully completed:"+JSON.stringify(data));
}else{
console.log('Error Msg'+JSON.stringify(data));
}
console.log('Error Msg'+data.message+''+JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.status);
console.log(textStatus);
console.log(errorThrown);
},
complete: function() {
}
});
below is my controller
#PostMapping(value="/tracker")
public int traker(#RequestParam(value="myJsonString[]") Item[] myJsonString){
System.out.println("getting somethig from tracker");
int count=0;
try{
for(Item item : myJsonString){
System.out.println("User is updating item id "+item.getName());
//count+= ggProcessRepository.changeAlert(row,isActive);
}
}catch(Exception e){
System.out.println("Exception Occured"+e);
}
return count;
}
i tried with requestparam required false and its let the block working but how to get the ajax data to my requestparam is the challenge for me.
in browser debug i see the form data getting send is --> myJsonString: [{"name":"product 2","price":20,"quantity":1},{"name":"product 3","price":30,"quantity":1}]

What happens if you change it to:
traker(#RequestParam(value="myJsonString")

Related

ajax - request error with status code 200

From client side, I wanna send some data to server and receive some <div> tags which responding from View (another controller).
My ajax code looks like this:
var sortTopic = function () {
var $list = [],
$address = '',
$formData = new FormData();
/* do something here to set value to $list and $address */
$formData.append('Category', $list);
$formData.append('Address', $address);
$formData.append('Tags', '[KM]');
$formData.append('Skip', 0);
$.ajax({
url: '/Topic/Sort',
type: 'POST',
data: $formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
if (!data.success) {
$('.jumbotron').html(data.ex);
} else {
$('.jumbotron').html(data);
}
},
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
});
};
In TopicController, action Sort was:
[AllowAnonymous]
[HttpPost]
public ActionResult Sort(SortTopicViewModel model)
{
try
{
if (model.IsValidSortTopicModel())
{
return PartialView("../Home/_Timeline", new TopicMaster().Sort(model));
}
return Json(new { success = false, ex = "Invalid model." });
}
catch (Exception e) { return Json(new { success = false, ex = e.Message }); }
}
I'm sure that the model is valid and method new TopicMaster().Sort(model) was working fine (because I had put breakpoint to view the return data). And the partial view _Timeline is a partial view of HomeController.
My problem is: I don't understand why I get error with status code 200 in ajax:
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
Can you explain to me?
Thank you!
as you told you receive <div> in response that is not json and you mention dataType:"json" in your ajax just remove it. this will solve your problem. error 200 occur when you did not get valid response which is you mention in ajax.
for mor information you can read it documentation

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

Ajax post can't find action controller

I'm writing a simple web app that allows users to login via facebook. When using the javascript sdk, I'm able to retrieve the proper credentials, but my ajax post is unable to find the mvc action to process the information.
Here's the js code:
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
var credentials = { uid: response.authResponse.userID, accessToken: response.authResponse.accessToken };
SubmitLogin(credentials);
}
});
function SubmitLogin(credentials) {
alert("Creds: " + credentials.uid + ":::" + credentials.accessToken);
$.ajax({
type: "POST",
ContentType: 'application/json',
url: '#Url.Action("FacebookLogin","Home")',
data:JSON.stringify(credentials),
success: function () {
window.location("~/Views/Account/Home.cshtml");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
}
and the corresponding controller:
[HttpPost]
public JsonResult FacebookLogin(string uid, string accessToken)
{
Session["uid"] = uid;
Session["accessToken"] = accessToken;
return null;
}
The model used in the controller:
public class FBLoginModel
{
public string uid { get; set; }
public string accessToken { get; set; }
}
The alert in the js function shows the correct token, but my ajax post is unable to the action. When I remove the "[HttpPost]" above the controller, I can access the action, but all data I attempt to pass is null.
Any help would be greatly appreciated. Thanks.
use
$.ajax({
type: "POST",
ContentType: 'application/json',
url: '#Url.Action("FacebookLogin","Home")',
data:JSON.stringify(credentials),
success: function () {
window.location("~/Views/Account/Home.cshtml");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
Ther should be single quote in 'Url.Action()'
Yout Controller action should be like below.Because you are not passing model items
public JsonResult FacebookLogin(long uid,string accessToken)
{
Session["uid"] = uid;
Session["accessToken"] = accessToken;
return null; //Because you are not posting anything back
}
I somehow devised a solution... By writing out the url and adding a forward slash to my ajax call, somehow my ajax call can find my action.
$.ajax({
type: 'POST',
url: 'Home/FacebookLogin/',
data: {
'uid': response.authResponse.userID,
'accessToken': response.authResponse.accessToken
},
cache: false,
success: function (result) { },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});

controller is not geting view data

function export(){
$.ajax({ url: "#Url.Content("~/controllr/method")",
type: 'GET',
data: { selectedValue : $("#BranchId option:selected").text() },
traditional: true,
async:false,
success: function (result ) {
},
failure: function () {
failed=true;
alert("Error occured while processing your request");
},
error: function (xhr, status, err) {
failed=true;
alert("Error occured while processing your request");
}}
Did you try setting a breakpoint on the controller action and see whether its is being hit ? Please try the following basic code and see whether the call is getting through
$.ajax({
url: ‘#Url.Content(“~/MyController/MyMethod”)’,
type: ‘post’,
data: {
selectedBranchId : $("#BranchId option:selected").text()
}
});
// I am the controller action
public ActionResult MyMethod(string selectedBranchId)
{
// your code
}
Please note I have dropped all the callback code and changed the controller name and the action name with the name of the postback variable

ajax call results in error instead of succes

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?
I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow
Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });
Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Resources