How to get data with jQuery ajax? - javascript

I'm try using jQuery Ajax for popularize a jqxGrid, but is not success
my jQuery code:
$.ajax(
{
url: "Cliente.aspx/GetClient",
type: "POST",
data: {},
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function(msg) {
alert("error"); //msg is returning error
}
});
I'm try get data with Entity Framework
[WebMethod]
public static string GetClient()
{
string dados;
using (SysContext db = new SysContext())
{
dados = new JavaScriptSerializer().Serialize(db.Clients.ToList());
}
return dados;
}
Where is my error? why

Look over here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
You are missing:
contentType: "application/json; charset=utf-8",
Which is needed to go to the Webmethod. So it will be:
$.ajax(
{
url: "Cliente.aspx/GetClient",
type: "POST",
data: {},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg);
},
error: function(msg) {
alert("error"); //msg is returning error
}
});

Related

Doing a validation check on a AJAX post and returning the error message

I have an AJAX post that does this.
$.ajax({
type: "POST",
url: "#MyWebSite.Url/myController/myView",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ myModel: myData }),
dataType: "json",
traditional: true,
success: function () {
alert('Success!');
},
error: function () {
alert('Error! ');
}
})
My controller does the validation check but it is not correctly returning the error message.
This is what my controller looks like:
if (totalQty < part.QtyInItem) {
//ModelState.AddModelError("", "My ERROR Message");
//RedirectToAction("myControler", myModel);
return this.Json(new { success = false, message = "My Error Message" });
}
When I tried adding an error to the model state it just returned "ERROR!" and not the error message I had associated with it. And when I try doing the this.JSON return it returns "success" to the view and not the error message.
How can I do this validation check for my AJAX post
You have to add data object to your function.
$.ajax({
type: "POST",
url: "#MyWebSite.Url/myController/myView",
contentType: "application/json; charset=utf-8",
data:
JSON.stringify({ myModel: myData }),
dataType: "json",
traditional: true,
success: function (data) {
alert(data.message);
},
error: function () {
alert('Error! ');
}
If you are still getting error, you should check your console for any server errors.

How To Post Json Data To Controller Without a Model in .net core

There is a huge data stored in grid that comes from a sql query joined more than ona table. Data type is Json. I filtered data and then want to sent filtered data to controller. But how it can be?
Here is test json data in javascript block:
var jsonData = {
"FirstName": "John",
"LastName": "Doe",
"DoB": "01/01/1970" };
And this is my javascript function:
function submitForm() {
var user = jsonData;
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(user),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
How to get the Json data in controller? Here is my [HttpPost] method:
[HttpPost]
public IActionResult GetJsonData(String user)
{
//...
return null;
}
user gets null.. Should i change type "String" in method or something else?
Since user is a string, you could try to create an object with a property user:
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
user: JSON.stringify(user)
},
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
Or using FormData:
var formData = new FormData();
formData.append('user', JSON.stringify(user));
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
contentType: false,
processData: false,
data: formData,
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});

Make AJAX post call with data

This is in my default.aspx
$.ajax({
url: "Default.aspx/Myfunction",
dataType: "json",
type: "POST",
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (d) {
alert("error");
}
});
And this is in my codebehind:
[WebMethod]
public static string Myfunction(string someParameter)
{
return "hello";
}
It keeps going to the error. I see that if I send the Ajax request with null for data and no parameters on the function I get the data "hello" out. So there is some issue in how I send the data, but it is unclear what
Put your parameters in quotes
$.ajax({
url: "Default.aspx/Myfunction",
dataType: "json",
type: "POST",
data: {'someParameter': 'some value'},
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (d) {
alert("error");
}
});
Data object must be a single string.
data: JSON.stringify({someParameter: "some value"})
Change this line:
data: {someParameter: "some value"},
to:
data: {"someParameter": "some value"},
JSON object properties needs to be enclosed with quotes.
Here is how I do the same thing:
$.ajax({
type: "POST",
dataType: "json",
url: "RouteService.asmx/getRouteData",
data: { techID: techID, jobID: jobID },
success: function(msg) {
processRouteData(msg);
}
Try removing this line:
contentType: "application/json; charset=utf-8",

Ajax post doesn't pass any data to MVC controller

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));
}
});

Not able to fetch data/Response on Success of Jquery.Ajax()

Hi people, I am craving myself from past 3 days and I just couldn't find the way to access json response seen on my browser
Here is my Ajax code :
$("[id*=btnModalPopup]").live("click", function () {
$("#tblCustomers tbody tr").remove();
$.ajax({
type: "POST",
url: "CallDataThroughJquery.aspx/GetLeadDetails",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hi Json");
alert(data.Leadno); // **Says data.leadno is undefined**
response($.map(data.d, function (item) { // **here I am going some where wrong**
//**cannot catch response. Help!**
}))
},
failure: function (response) {
alert(response.d);
}
});
});
Please help me on this.. Thanks in Advance!
I see that your JSON is an array with an object. Try data[0].Leadno
$.ajax({
type: "POST",
url: "CallDataThroughJquery.aspx/GetLeadDetails",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hi Json");
alert(data.d[0]['Leadno']); // **Says data.leadno is undefined**
response($.map(data.d, function (item) { // **here I am going some where wrong**
//**cannot catch response. Help!**
}))
},
failure: function (response) {
alert(response.d);
}
});
Try your alert with 'data.d[0]['Leadno']'.

Categories