Ajax call to .NET webservice.

Ajax call to .NET webservice.

SPSP Posts: 7Questions: 0Answers: 0
edited May 2010 in General
Hi Allan,

I am trying to use DataTables for an application in .NET. Since I am not sure of the certain variables/API please help me in resolving the following basic ideas:

I am making an AJAX call on document ready as follows :

[code]

$(document).ready(function() {
$('#dTable').dataTable({
'iDisplayLength': 20,
'oLanguage' : {'sInfo' : "_START_ - _END_ of (_TOTAL_+)"},
'sDom' : '<"divScrollContainer"fiprt>',
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : 'http://localhost/WService/WService.asmx/DataPull',
'fnServerData': function(sSource, aoData, fnCallback) {
$.ajax({
"type": "POST",
"dataType": 'json',
"contentType": "application/x-www-form-urlencoded; charset=utf-8",
"aoColumns": [{"sTitle": "Code"},{"sTitle": "Description"}],
"url": sSource,
//"data": "query="+$(this).val(),
"data":"query=test",
"success": fnCallback
});
}
} );
} );

[/code]

I am getting the following response from the webservice (this is how .NET generates JSON response with JavaScript Serializer class) :

[code]
<?xml version="1.0" encoding="utf-8"?>
[['0010','TestData1'],['0011','TestData2'],['0019','TestData3']]
[/code]

I would like to know,
1. Is this response fine for DataTable to populate tables? If yes, why am I not seeing the table updated with the JSON data. If not, what is the expected format?
2. How can I make the 'data' parameter of $.ajax to take what I type in the datatable's textbox? Setting it as "data": "query="+$(this).val() passes null data to webservice. I am trying to do an ajax webservice call on text change of the textbox.
3. What does "url": sSource signify? What value should I pass for sSource?
4. Are 'aoColumns' mandatory for AJAX calls?
5. What does fnCallback signify? When should I use this?
6. For AJAX calls if a JSON response is received will DataTable automatically populate the tables or do we need to set anymore settings?

I am totally confused on these basic stuffs. Please clarify so that it might help somebody else like me to grasp things easily. Thanks.


Regards,
SP.

Replies

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    1. No - this is not a valid JSON string. In order for DataTables to be able to process the information the string returned must be valid JSON ( http://jsonlint.com ). If you can't return valid JSON then you must convert it using Javascript to be valid JSON. If you are using server-side processing as well (which you are) then you are missing a number of parameters. See http://datatables.net/usage/server-side .

    2. http://datatables.net/examples/server_side/custom_vars.html

    3 and 5. http://datatables.net/usage/callbacks#fnServerData

    4. No - aoColumns are not mandatory for Ajax sourced data / server-side processing. They can be used to configure DataTables as you want - but if you don't specify them, then DataTables will use it default settings and automatic detection.

    6. That is what fnCallback is for - to do all the hard work of drawing the table etc :-)

    I'd suggest reading the following pages from the documentation:
    http://datatables.net/usage/#data_sources
    http://datatables.net/usage/server-side

    And poking around the examples (particularly with Firebug):
    http://datatables.net/examples

    Regards,
    Allan
  • SPSP Posts: 7Questions: 0Answers: 0
    edited May 2010
    Thanks Allan.

    So I believe setting 'data' parameter is inappropriate in a AJAX call because sSource relays the textbox value being typed in. I am not sure of sSource still - is that set same as sAjaxSource?

    It would be helpful if you can tell me what I am trying to achieve is feasible.

    I am trying to get data from server side through a webservice call as and when the user types in the Data table textbox. Serverside operations will not involve sorting, pagination etc so I am not setting the bServerside option (false). I would rather prefer to get chunks of data from server side through AJAX call and provide it to datatable as json data through a js varibale and let data table handle the pagination, sorting etc for that result set.

    Following might clarify better:

    [code]

    $(document).ready(function() {
    $('#dTable').dataTable({
    'iDisplayLength': 20,
    'oLanguage' : {'sInfo' : "_START_ - _END_ of (_TOTAL_+)"},
    'sDom' : '<"divScrollContainer"fiprt>',
    'bProcessing' : true,
    'sAjaxSource' : strJson //-------------------> a string populated with json response from server side.
    'fnServerData': function(sSource, aoData, fnCallback) {
    $.ajax({
    "type": "POST",
    "dataType": 'json',
    "contentType": "application/x-www-form-urlencoded; charset=utf-8",
    "url": "http://localhost/service/service.asmx/Pull"
    "success": fnCallback
    });
    }
    } );
    } );

    [/code]

    If its feasible, then the question is how can I intercept the data from server (which I need to convert to JSON from XML) and set it to strJson so that datatable can take it as json source?
  • SPSP Posts: 7Questions: 0Answers: 0
    Hi Allan,

    I am happy to say that I was able to post data to the webservice as and read get back a response now I am just stuck up on how to read the xml response on success in fnCallback.

    I am not sure on following :

    1. How to read back the xml response in fnCallback.
    2. If I can the value (not sure how) then I can give it to some custom gfunction to output JSON but how do I say datatable to take up the JSON output on ceit is done?

    I belive all of these needs to be done in the fncalback but not I am not sure of the reading response and setting/triggering datatable to display it.

    This will resolve my issue. Waiting for your inputs :).

    Thanks.
  • SPSP Posts: 7Questions: 0Answers: 0
    edited May 2010
    Here is how I have the code:

    [code]
    $(function() {
    $('#dTable').dataTable({
    'iDisplayLength': 20,
    'oLanguage' : {'sInfo' : "_START_ - _END_ of (_TOTAL_+)"},
    'sDom' : '<"divScrollContainer"fiprt>',
    'bProcessing' : true,
    'bServerSide' : true,
    'sAjaxSource' : 'http://localhost/DQService/DQService.asmx/DummyPull',
    'fnServerData': function(sSource, aoData, fnCallback) {
    //aoData.push( { "sSearch":"TEST"});
    aoData.push( { "name": "query", "value": "test" } );
    $.ajax({
    "type": "POST",
    "dataType": 'xml',
    "contentType": "application/x-www-form-urlencoded; charset=utf-8",
    //"aoColumns": [{"sTitle": "Code"},{"sTitle": "Description"}],
    "url": sSource,
    //"data": "query="+$(this).val(),
    "data":aoData,
    "success":function(xml){
    json = '{\"aaData":[[\"10126\",\"10002253\"],[\"10126\",\"10002253\"]]}';
    fnCallback(json);
    }
    });
    }
    } );
    } );
    [/code]

    Now I am trying to set the datatype param as XML and just trying to show up some dummy the data on table to test. But i am encountering an error 'json.aaData is undefined' at the following line in jquery.datatables.min.js although I can see the json param with the hardcoded json in Firebug:

    [code]
    if(bReOrder){var aiIndex=_fnReOrderIndex(oSettings,json.sColumns)}for(var i=0,iLen=json.aaData.length;
    [/code]

    Pls provide your valuable inputs.
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    1. You need to convert the xml into JSON using standard Javascript techniques. Have a look around Google for how to read an XML document, and then just parse that into a JSON string.

    2. I'm not sure I understand. If you give DataTables valid JSON, in the format it is expecting, then it will work fine.

    Misc 1. Did you read through the examples and the documentation I linked to? In your latest code you have server-side processing enabled, but the json string is missing a number of the required parameters.

    Misc 2. The JSON string is invalid - you don't need the quites, since you are using single quotes as the delimiter.

    Allan
  • SPSP Posts: 7Questions: 0Answers: 0
    edited May 2010
    Sorry for dragging this on. I went through the link and understand that I need to pass through several other params too following is how I am having my json data:
    [code]
    json = '{sEcho: 1, iTotalRecords: 2, iTotalDisplayRecords: 2, aaData: [ [Tasman,Internet Explorer 4.5],[Tasman,Internet Explorer 5.1]]}';
    [/code]
    Is this how it should be? I have removed the double quotes as you have mentioned. But the aadata param -
    [code]
    aaData: [ [Tasman,Internet Explorer 4.5],[Tasman,Internet Explorer 5.1]]
    [/code]
    is invalid as per jsonlint.com. But with double quotes it works fine.

    If I hardcode the following lines
    [code]
    json = '{sEcho: 1, iTotalRecords: 2, iTotalDisplayRecords: 2, aaData: [ [Tasman,Internet Explorer 4.5],[Tasman,Internet Explorer 5.1]]}';
    fnCallback(json);
    [/code]
    DataTable should have rendered the data. Isn't so? But I am getting the same error - 'json.aaData is undefined'. I am not getting what is missing.


    Regards,
    SP.
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    It was the escaped quotes (the slashes) which were incorrect - not the quote marks themselves :-). Have a look at the JSON that is returned for my server-side scripts using Firebug - you'll see exactly what DataTables is expecting and how it changes. One example is that sEcho cannot be hardcoded - it might work the first time, but there after won't redraw the table. Have a poke around the examples, to see what is happening:

    http://datatables.net/examples/
    http://datatables.net/examples/server_side/server_side.html

    Allan
  • SPSP Posts: 7Questions: 0Answers: 0
    Thanks Allan.

    Sorry I am not able to make out what's wrong with the aadata Following is the JSON data I am passing but still it throws the same error - 'json.aadata is undefined'.

    [code]
    json = '{"sEcho": 1, "iTotalRecords": 2, "iTotalDisplayRecords": 2, "aaData": [ ["Tasman","Internet Explorer 4.5"],["Tasman","Internet Explorer 5.1"]]}';
    fnCallback(json);
    [/code]

    When I debug using Firebug I can see the value of json as harcoded but 'aadata' remains undefined.
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    That's because it's a string and not a JSON object...

    [code]
    json = {"sEcho": 1, "iTotalRecords": 2, "iTotalDisplayRecords": 2, "aaData": [ ["Tasman","Internet Explorer 4.5"],["Tasman","Internet Explorer 5.1"]]};
    fnCallback(json);
    [/code]
    Will assign an object to the variable 'json'.

    Allan
  • SPSP Posts: 7Questions: 0Answers: 0
    Thank Allan! That's my mistake its working fine now. Indeed that was great support :).
This discussion has been closed.