I've been trying to post data to jquery Data Tables but i couldn't. I have a web method in server side which returns data as object array. I need to get data with ajax post. But i can't. So i need some help.
Here is my c# web method:
[WebMethod]
public static object[] Questions()
{
table = new DataTable();
List<object> questionList = new List<object>();
table = RunSelectCommand("SELECT QUESTION_ID,QUESTION_TEXT,QUESTION_GROUP FROM QUESTIONS WHERE QUESTION_ACTIVE='Y'");
for(int i=0 ; i<table.Rows.Count ; i++)
{
questionList.Add(new
{
q_id = table.Rows[i]["QUESTION_ID"].ToString(),
q_text = table.Rows[i]["QUESTION_TEXT"].ToString(),
q_group = table.Rows[i]["QUESTION_GROUP"].ToString()
});
}
return questionList.ToArray();
}
And jquery:
$(document).ready(function () {
$('#questTable').DataTable({
processing: true,
serverSide:true,
ajax: {
url: 'Question.aspx/Questions',
type:'POST'
},
columns: [
{ data: 'q_id' },
{ data: 'q_text' },
{ data: 'q_group' }
]
});
});
But i debuged it with break point and i noticed that web method doesn't work. And here is the error that i get: DataTables warning: table id=questTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
Thanks in advance.
Problem solved. It was about my web method returns object array and data tables doesn't accept it. That's why i got Invalid JSON response. error. So i change my js structure. I post data as usual then i use data tables data property for post. It works:
function GetData()
{
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Question.aspx/Questions',
data: '{}',
success: function (result) {
$('#questTable').DataTable({
data:result.d,
columns: [
{ data: 'q_id' },
{ data: 'q_text' },
{ data: 'q_group' }
]
});}
}
Related
I have this code where i am trying to retrieve data from model.findall() and display in UI as table
model.js
define(['jquery', 'can'], function ($, can) {
var serviceModel = can.Model.extend({
findAll: function (params,servicename) {
return $.ajax({
type: 'POST',
dataType: 'JSON',
contentType: 'application/json',
url: 'data/+ servicename',
success: function (data) {
console.log("Success ");
},
error: function () {
console.log("Error");
}
});
}
}, {});
return serviceModel;
});
controller.js
serviceModel.findAll(params,"SP_table", function(data) {
if (data.status === "success") {
$('#idtable').dataTable().fnClearTable();
$('#idtable').dataTable().fnAddData(data.result);
}else{
alert("inside alert");
}
});
issue is in serviceModel.findAll() i am unable to get data inside serviceModel.findAll() because data is in the form of stored procedure or macro, which i am getting using "servicename" from function above
please let me know how to resolve this issue.
You can access the raw xhr data from the ajax call and convert it to an appropriate format by overriding the parseModels method:
https://canjs.com/docs/can.Model.parseModels.html
Overwriting parseModels If your service returns data like:
{ thingsToDo: [{name: "dishes", id: 5}] } You will want to overwrite
parseModels to pass the models what it expects like:
Task = can.Model.extend({ parseModels: function(data){ return
data.thingsToDo; } },{}); You could also do this like:
Task = can.Model.extend({ parseModels: "thingsToDo" },{});
can.Model.models passes each instance's data to can.Model.model to
create the individual instances.
In their example above, the response is a nested JSON: in yours, it is your procedure or macro. You have the opportunity here in parseModels to rewrite the response in the appropriate format.
I have following code to send DATA to controller action and return the plain HTML
I am getting empty object in controller action.
var employees = [
{ Title: "John", DataType: 1 },
{ Title: "Anna", DataType: 2 },
{ Title: "Peter", DataType: 3 }
];
$("#btn-continueedit").click(function () {
$.ajax({
type: 'POST', // I tried post also here
cache: false,
url:'/user/UserinfoWizard',
data: { values: employees },
success: function (data) {
$("#editUserInfo").html(data);
}
});
return false;
});
Here is my controller action
[HttpPost]
public ActionResult UserInfoWizard(List<UserInfoEditDetail> values)
{
// I get empty object 'values' here :(
}
The data passed with the ajax call should be an object containing the parameter which you want to use in the controller action. Your action expects a values parameter passed with the data, so your data object should be data: { values: getSelectedAttributes() }
JavaScript:
$("#btn-continueedit").click(function () {
$.ajax({
type: 'POST',
//..
data: { values: getSelectedAttributes() }, //Use the data object with values
//..
});
return false;
});
C#:
[HttpPost]
public ActionResult UserInfoWizard(object values) // parameter name should match the name passed in data object
{
//..
}
EDIT
Indeed you action expects an object, while your values is an array. I don't know what the values are, but in your action you should have the int[] values or string[] values as parameter or any other array type you are expecting.
$("#btn-continueedit").click(function () {
$.ajax({
type: 'GET', // I tried post also here
cache: false,
dataType:JSON,
url:'/user/UserinfoWizard',
data: JSON.stringify({ data:getSelectedAttributes()}),
success: function (data) {
$("#editUserInfo").html(data);
}
});
return false;
});
Updated:
When you are passing data during an ajax call, it should be in the form of an object and not an array
I try to get started with ExtJs, and I have quite basic question.
I have a model
Ext.define('Mb.model.User', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int' },
{ name: 'name', type: 'string' },
...
],
proxy: {
type: 'ajax',
url : 'server/gui/getUser.php'
}
});
getUser.php returns a json string (it is the logged in user, and not a user out of a user table):
{"id":"1","name": ... }
I tried the following to load the data, but I get an error Uncaught TypeError: Object [object Object] has no method 'load'
Ext.define('Mb.Application', {
...
launch: function() {
....
user = Ext.create('Mb.model.User');
user.load();
}
});
What is the correct way to load that data ?
An additional question: What is the benefit of using Modelhere ?
Couldn't I do something like this ?
Ext.Ajax.request({
url: 'server/gui/getUser.php',
success: function(response){
var user = Ext.JSON.decode(response.responseText);
}
});
In this case load is a static method. You can load a model from your server by passing the id.
Mb.model.User.load(id, {
success: function(rec) {
console.log('loaded', rec.getData());
}
});
The advantage to using a model is the layer of abstraction, + the extra functionality you get from using a model.
You can do, but with little changes
myRequest = Ext.Ajax.request({
url: 'getdata.php',
method: 'GET',
callback: function(response) {
console.log(response.responseText);
}
});
I am trying to load a JSON data which is replied back by an AJAX request to a grid.
My store definition:
Ext.define('Report.store.CustomerDataStore', {
extend: 'Ext.data.Store',
requires: [
'Report.model.Customer'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
storeId: 'CustomerDataStore',
model: 'Report.model.Customer',
proxy: {
type: 'ajax',
url: '',
reader: {
type: 'json',
root: 'data',
record: 'fields'
}
}
}, cfg)]);
}
});
There is a button in my app which is defined as follows:
xtype: 'button',
handler: function(button, event) {
var queryform = this.up('form').getForm();
var me = this;
if(queryform.isValid())
{
Ext.Ajax.request({
url: 'customers/', // where you wanna post
success: function(response) {
var mystore = Ext.data.StoreManager.lookup('CustomerDataStore');
var myData = Ext.JSON.decode(response.responseText);
console.log(myData.toSource());
mystore.loadData(myData);
},
jsonData: Ext.JSON.encode(queryform.getValues())
});
}
},
The problem is that my grid doesn't show the replied data! I am sure that my replied JSON format is OK. I have checked it with a json file. also myData.toSource() returns my desired JSON format.
I am pretty confused what I am doing wrong?
Could you plz help?
I found the solution, I had to use loadRawData() function instead of loadData().
loadData() loads models i.e. records, and doesn't parse JSON data inside. You need to specify your JSON format in proxy reader and then store will automatically do Ajax call when you call store.load()
how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen