Ajax post doesn't pass any data to MVC controller - javascript

This:
$.ajax({
url: '/Merchant/SaveDirty',
type: 'POST',
dataType: 'json',
data: ko.toJSON(dirtyItems),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// get the result and do some magic with it
//var message = data.Message;
alert(ko.toJSON(dirtyItems));
}
});
...currently calls this:
[HttpPost]
public void SaveDirty(string json)
{
}
...but when I hit the breakpoint in SaveDirty, no data is passed. I've verified that ko.toJSON(dirtyItems) returns a JSON string in the javascript. What am I doing wrong?
Thanks!

#KillingsWorth, is there any specific reason for which you are posting a JSON string? If not then, you could create a class corresponding to dirtyitems type and in your controller method you can accept a list of dirtyItems.
Class DirtyItem
{ // dirty item properties }
[HttpPost]
public void SaveDirty(List<DirtyItem> dirtyItems)
{
}

you can use the following:
$.ajax({
url: '/Merchant/SaveDirty',
type: 'POST',
dataType: 'json',
data: JSON.stringify(dirtyItems),
contentType: 'application/json; charset=utf-8',
success: function (data) {
///
///
}
});
But if you are using knockout.js in your applicantion then you should do the following:
$.ajax({
url: '/Merchant/SaveDirty',
type: 'POST',
dataType: 'json',
data:JSON.stringify(ko.mapping.toJS(dirtyItems)),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// get the result and do some magic with it
//var message = data.Message;
alert(ko.toJSON(dirtyItems));
}
});

This should works:
$.ajax({
url: '#Url.Action("SaveDirty", "Merchant")'
type: 'POST',
dataType: 'json',
data: JSON.stringify(dirtyItems),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// get the result and do some magic with it
//var message = data.Message;
alert(ko.toJSON(dirtyItems));
}
});

Related

how to create a javascript rusable class to pass parameters to ajax

im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,
function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.
You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.
Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.
A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)
There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});

failed 500 internal server error

I m getting Internal server error (500) making an AJAX request. I m not sure why the request is failing. Need help in this. Here is my code.
$('#LanguageId').on('change', function(){
var setValue =JSON.stringify( $('#LanguageId').val());
console.log(typeof(setValue));
$.ajax({
url: '/RootObjects/SaveLanguage',
type: 'POST',
dataType: 'json',
data:setValue ,
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});
})
and the controller's action
[HttpPost]
public ActionResult SaveLanguage(string LanguageId)
{
GlobalVariables.LangId = LanguageId.ToString();
return View("Index");
}
can't understand what is wrong
Change your ajax request like this:-
$('#LanguageId').on('change', function(){
var setValue =$('#LanguageId').val();
console.log(typeof(setValue));
$.ajax({
url: '/RootObjects/SaveLanguage',
type: 'POST',
dataType: 'json',
data:{'LanguageId':setValue} ,
success: function (data) {
}
});
})

when use contentType: 'application/json; charset=utf-8', then my data is not passed to api controller

I,m updating a record using PUT in web api, when I use contentType: 'application/json; charset=utf-8', then my data is not passed to api controller but when i comment this line data is transfered. can any one explain this ? below is my Call from mvc view
$(function () {
$("#btnSubmit").click(function () {
var id = $("#hdnProductID").val();
var ProductName = $("#txtProductName").val();
var QuantityPerUnit = $("#txtQuantityPerUnit").val();
var ReorderLevel = $("#txtReorderLevel").val();
var UnitPrice = $("#txtUnitPrice").val();
var UnitsInStock = $("#txtUnitsInStock").val();
var UnitsOnOrder = $("#txtUnitsOnOrder").val();
$.ajax({
url: "http://localhost:2821/api/Products"+ "/" + id,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data:{ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder},
success: function (data) {
alert("success");
},
error: function (msg) {
alert(msg);
}
});
});
});
Below is my controller method
public IHttpActionResult PutProduct(int id, Product product)
{}
If contentType is not specified in the request, it takes default contentType, i.e., "application/x-www-form-urlencoded; charset=UTF-8" and no need to stringfy the post data but if contentType is "application/json; charset=utf-8", need to stringfy post data explicitly. So it should be:
$.ajax({
url: "http://localhost:2821/api/Products"+ "/" + id,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data:JSON.stringify({ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder}),
success: function (data) {
alert("success");
},
error: function (msg) {
alert(msg);
}
});

Converting $.post into $.ajax

I have a post statement,
$.post("panel.php", 'data=[{"action":"UserInfo"}]', function (userInfo){
//processing
});
I need it to be converted to $.ajax so made it thus,
$.ajax({
type: "POST",
url: "panel.php",
data: { data: [{"action":"UserInfo"}]},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(userInfo) {
//processing
}
});
But the post variable isn't being sent. Is this not the correct way?
Can you try something like this:
$.ajax({
type: "POST",
url: "panel.php",
data: {"action":"UserInfo"},
success: function(userInfo) {
//processing
}
});
Try this
$.ajax({
type: "POST",
url: "panel.php",
data: "action="+"UserInfo",
success: function(userInfo) {
//processing
}
});
Remove data from your data and keep it in a variable, stringify before your send as below
var data={"action":"UserInfo"};
$.ajax({
type: "POST",
url: "panel.php",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(userInfo) {
//processing
}
});
Your data attribute was not written as correct JSON:
data: { "data": [{"action":"UserInfo"}]},
You need quotation marks around the items inside your JSON object. You can use JSONLint to check if your JSON object is valid.
$.ajax({
type: "POST",
url: "panel.php",
data: {"action":"UserInfo"},
dataType: "json",
success: function(userInfo) {
//processing
}
});
Need a small change. there is a predefined format to send data in ajax,
data: {status: status, name: name},
data: "status="+status+"&name="+name.
Follow any one of the approach.
try like this,
$.ajax({
type: "POST",
url: "panel.php",
data: {"action":"UserInfo"},
success: function(userInfo) {
}
});

AJAX POST JSON value

I have AJAX POST, the result is JSON:
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var upload = JSON.stringify(result);
console.log(upload);
}
});
The upload result is:
{"Link":0,"Title":"d","Description":"dada","Keywords":"dad"}
How can I get the value of Title?
Do not stringify the result, just use result.Title.
As you already have JSON string, It's simple as a pie!
All you need to do is to call the property you want from the variable you assigned your result to.
for example:
var post_response;
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
post_response = JSON.stringify(result);
console.log("Title: "+post_response.Title);
}
});
hope this helps.

Categories