How to Send method POST to ajax calls

How to Send method POST to ajax calls

dmssdmss Posts: 3Questions: 0Answers: 0
edited March 2009 in General
How to Send method POST for ajax calls in DataTables , help help please thanks..
example
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/index/ajaxpost" // Zend Framework (PHP)
example (here method POST): POST params =>(how to send method)

} );
} );

Replies

  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    Hi dmss,

    Not quite sure what you mean. Have you looked at the Ajax source demo: http://datatables.net/examples/example_ajax_source.html

    Or if you are looking for server-side processing: http://datatables.net/1.5-beta/examples/data_sources/server_side.html

    Do these help assist in what you are trying to do?

    Allan
  • dmssdmss Posts: 3Questions: 0Answers: 0
    ok but I need to send the POST method, because Zend Framework not send allows using the GET method
    example
    $(document).ready(function() {
    $('#example').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "server_processing.php"
    (here method send (POST or GET)=> how to send method)
    )
    } );
  • vexvex Posts: 30Questions: 0Answers: 0
    edited March 2009
    With the current code it isn't possible, if you look at the code for DataTables you'll see that Allan uses $.getJSON(), hence it will always use get. Replacing that code with something like this (untested) should probably work:

    [code]
    $.ajax({
    dataType: 'json',
    type: oSettings.sAjaxMethod,
    url: oSettings.sAjaxSource,
    success: function(json) {
    /* Got the data - add it to the table */
    for ( var i=0 ; i
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    Oh I see! Sorry I didn't release that you wanted to use HTTP POST rather than GET. This is indeed possible in DataTables, you just need to override the function that DataTables uses to request data from the server (fnServerData). You can see an example of this here: http://datatables.net/1.5-beta/examples/server_side/custom_vars.html - in this example I add an extra variable to the list sent to the server, but hopefully you can see that rather than using $.getJSON() you could use $.ajax() with a 'POST' instruction.

    This is probably an important point that DataTables allows for this. I'll put an example together for this in a little while.

    Allan
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    In 1.5 beta 6 I've included an example of how POST can be used. See http://datatables.net/1.5-beta/examples/server_side/post.html .

    Allan
  • dmssdmss Posts: 3Questions: 0Answers: 0
    great thanks allan problem solved
  • GaryFGaryF Posts: 16Questions: 0Answers: 0
    How can I add my own additional parameters to send in the ajax POST request please? At the moment I bolt my own params onto the sAjaxSource URL which isn't ideal.

    Thanks.
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    Hi Gary,

    Check out this example here: http://datatables.net/1.5-beta/examples/server_side/custom_vars.html

    It shows how you can use fnServerData() to override the built-in server get function and add whatever variables you want to the request.

    Allan
  • GaryFGaryF Posts: 16Questions: 0Answers: 0
    It doesn't work because, I think, I'm using $.ajax rather than $.getJSON. I added the aoData.push(...) line but Firebug shows me that no extra data is being posted apart from "undefined : undefined" which indicates I've done something wrong.

    Thanks for your patience.
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    Hi Gary,

    You can still use a similar method as to that outlined in the custom vars example. The "data" parameter used by $.ajax is exactly the same as that used by $.getJSON (indeed $.getJSON just wraps $.ajax).

    So by combining the code the the custom vars example and that here: http://datatables.net/1.5-beta/examples/server_side/post.html - you should get exactly what you are looking for :-)

    Allan
  • GaryFGaryF Posts: 16Questions: 0Answers: 0
    Sorry Allan, I must be thick, but I can't add my own data to the data that DataTable needs to post.

    "data : aoData" posts DataTable's own params via $.ajax() so I need to add my own params to that, right?

    Adding aoData.push({ "test" : "hello"}) just before $.ajax doesn't work. I then tried adding my params to aoData like this: aoData+=({ "test" : "hello"}) but I guess that was a long shot. Can't treat aoData like a string, right?

    So I'm still stuck. :-(
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    Hi Gary,

    You need to add new data to the object using something like the custom vars example:

    aoData.push( { "name": "more_data", "value": "my_value" } );

    So in this case you might use:

    aoData.push( { "name": "test", "value": "hello" } );

    Hopefully that will do the trick for you :-)

    Allan
  • GaryFGaryF Posts: 16Questions: 0Answers: 0
    Doh! I didn't see that I had to literally include the words "name" and "value". I though it was just a regular key:value pair. It's working now, thank you. So how many rounds of drinks do I owe you? You'll be staggering home. ;-)
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    I've no idea why jQuery does it that way - seems a bit counter productive and counter intuitive to me, particularly when you want to grab the information from inside such an object, you need to loop over it...

    Heh - there is a pub just around the corner from where I am - it's not a long trip (depending on the amount of weaving involved ;-) ).

    Allan
  • djohdjoh Posts: 23Questions: 0Answers: 0
    Hi,
    Got the same stupid issue, trying to push one more variable.
    Getting undefined:undefined, since "name" and "value" have to be included...
    o_0
  • akleurakleur Posts: 2Questions: 0Answers: 0
    If you want to use method POST for your ajax call, use this:
    [code]
    "sAjaxSource": "server_processing.php",
    "fnServerData": function ( sSource, aoData, fnCallback ) {
    $.ajax( {
    "dataType": 'json',
    "type": "POST",
    "url": sSource,
    "data": aoData,
    "success": fnCallback
    } )
    }
    [/code]
    For the "server_processing.php" file, take the example there:
    http://www.datatables.net/examples/data_sources/server_side.html
    Change it for your needs and replace $_GET with $_POST
  • hoodlumj3hoodlumj3 Posts: 5Questions: 0Answers: 0
    Let me first start off by saying dataTable is massively fantastic, I can't get over how good it is! I'm currently using it in a project at work etc...

    OK, Can I be a pain and ask how to request an enhancement.
    It's to do with sending extra parameters along with the ajax call.
    I currently have modded my 1.8.1 source to allow me to send extra ajax parameter data without requiring the use of fnServerData at all.

    This is a typical dataTable calls of mine, which uses ajax :-
    [code]
    $(document).ready(function() {
    var sgHREF = window.location.pathname;
    /* Init ajax defaults */
    $.ajaxSetup( {type: "POST", url: sgHREF, dataType: "html", async: false, success: function(result) { result = ajaxWhatJustHappened(result);} } );

    /* init dataTable and push */
    var oPostData = {rt:'RUPLOADEDFILES'} ;
    $('#tblUploadFiles').dataTable({
    sAjaxSource: sgHREF,
    aoAjaxData: oPostData,
    sAjaxDataProp: 'data',
    sDom:'t',
    'oLanguage': {
    'sZeroRecords': 'No files have been uploaded.'
    }
    });
    });
    [/code]

    now notice my hacking attempt ... aoAjaxData to be exact.
    It has my post data in it, as you can see, I then get back JSON data, you all knew that already. :)

    so on the 1.8.1 source created on 28/3/2008
    [code]
    ---------------------------------------------------
    Line 1305 :
    ---------------------------------------------------
    Original:

    New:
    this.aoAjaxData = [];
    ---------------------------------------------------
    Line 2387 (old 2386 without line 1305 inserted) :
    ---------------------------------------------------
    Original:
    oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, [], function(json) {
    New:
    oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, oSettings.aoAjaxData, function(json) {
    ---------------------------------------------------
    Line 6963 (old 6962 without line 1305 inserted ) :
    ---------------------------------------------------
    Original:

    New:
    _fnMap( oSettings, oInit, "aoAjaxData");
    ---------------------------------------------------
    [/code]

    Sorry if this is in the wrong area, it's late so i'll try to find the proper area later.
    Very easy enhancement, so much code saving (like jQuery, more with less)

    Cheers!
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    I think this is a good call. It's quite a common thing to do to want to add data to what is being sent to the server, so I seems sensible that this should be made as easy as possible. I think a callback function specifically for this might be more appropriate than a static array through, since it is not unusual to want to read dynamic information from the page (search string etc) and send that. Having said that, it might be possible to support both.

    Added to the list :-)

    Thanks!
    Allan
  • hoodlumj3hoodlumj3 Posts: 5Questions: 0Answers: 0
    Cheers, that's good news, I like!

    But don't waste your time with writing a callback...

    I believe that functionality can be attained via the fnReloadAjax plugin. (here http://www.datatables.net/plug-ins/api#fnReloadAjax )

    but Note... a slight mod is needed to that plugins call to fnServerData, i had to change the second parameter to oSettings.aoAjaxData instead of [] and also fix the aaData references so it uses "sAjaxDataProp" ( see my fresh post here http://www.datatables.net/forums/discussion/4361/fnreloadajax-fix-and-feature/p1 )

    It has worked for me, well it is working for me just right!

    I'll give an example. (I use jqueryui too)

    [code]
    $(document).ready(function() {
    /* Init ajax defaults */
    var sgHREF = window.location.pathname;
    $.ajaxSetup( {type: "POST", url: sgHREF, dataType: "html", async: false, success: function(result) { result = ajaxWhatJustHappened(result);} } );

    var oPostData = { rt: 'RSTAFFSEARCHLIST', txt: ''};
    /* init datatable */
    $('#tblSearchResults').dataTable({
    'sAjaxSource': sgHREF,
    'aoAjaxData': oPostData,
    'sAjaxDataProp': 'data',
    'bAutoWidth': false,
    'sDom':'t',
    'oLanguage': {
    'sZeroRecords': 'No entries found, please revise your search criteria.'
    }
    });

    /* capture search button clicks */
    $('#btnSearchNow').button({icons: { primary: 'ui-icon-search'}}).click(function() {

    var oTxtSearch = $('#txtSearch');
    var oTable = $('#tblSearchResults').dataTable();
    var oSettings = oTable.fnSettings();

    var oPostData = { rt: 'RSTAFFSEARCHLIST', txt:oTxtSearch.attr('value')};
    oSettings.aoAjaxData = oPostData;

    /* or I could just oSettings.aoAjaxData['txt'] = oTxtSearch.attr('value'); */

    oTable.fnReloadAjax(null, null, true);

    });
    });
    [/code]

    But all in all - a big Yummo from ME!!!!

    HTH
  • hoodlumj3hoodlumj3 Posts: 5Questions: 0Answers: 0
    edited February 2012
    Hey,

    Just tried DT1.9.0... excellent!!!
    But... this enhancement didn't work for me straight up (coming from a hacked v1.8.1)

    I believed passing a JSON object to .datatable() via my aoAjaxData was the solution, this didn't seem to get adopted, even though i suggested it... so inevitably sadness prevailed... but that's ok, I can take it... ;)

    Our attempts to use the fnServerData parameter was fraught with danger, well not really - it just didn't work as we expected it to... boo hoo
    We figured out that to version up we would have to restructure *all* of the datatable post parameters into name value pairs
    e.g.

    Our way... (Yay so simple)
    [code]

    $.ajaxSetup( {'type': 'POST', 'url':'MyWebService.asmx/HelloWorld', 'dataType': 'json' } );

    var oPostData = {'hello':'there', 'name2':'value2', 'name2':'value2'};

    oPostData['name3'] = this.options.value3;

    $('#TableInTheDOM').datatable({

    'sAjaxSource': $.ajaxSettings.url,

    'aoAjaxData':oPostData

    });
    [/code]

    The highway...
    [code]
    var self = this;

    $.ajaxSetup( {'type': 'POST', 'url':'MyWebService.asmx/HelloWorld', 'dataType': 'json' } );

    // This fixes datatable's overridden type on the .ajax call

    $.extend($.fn.dataTable.defaults, {'sServerMethod': 'POST' });

    $('#TableInTheDOM').datatable({

    'sAjaxSource': $.ajaxSettings.url,

    'fnServerParams' : function (aoData) {
    aoData.push({"name":"hello", "value":"there"}, {"name":"name2", "value":"value2"});
    aoData.push({"name":"name3", "value":self.options.value3});
    }

    });
    [/code]
    blurk - talk about code bloat and can you see my dilemma.


    So, can I suggest a slight modification / enhancement to v1.9.0 source, it will in no way break or become incompatible with whomever is currently using this functionality...
    Actually I believe DT will become a little more flexible, so...
    [code]
    //current line 8385...
    "data": aoData,
    //new line 8385...
    "data": aoData.length!=='undefined'?aoData[0]:aoData,
    [/code]
    Explanation : This just tests aoData for the length property, arrays [] have one and objects {} don't (Anyone know of better way?).

    So now to rehash (and summarize) my original code from above...
    [code]

    var oPostData = {'hello':'there', 'name2':'value2', 'name2':'value2'};

    oPostData['name3'] = this.options.value3;

    $('#TableInTheDOM').datatable({

    'sAjaxSource': $.ajaxSettings.url,

    'aoAjaxData':function (aoData) { aoData.push(oPostData); }

    });
    [/code]

    I believe this will cater for masses or was it just me... ;D

    Cheers!
  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin
    So basically rather than mandating name / value pairs you are looking for DataTables to accept JSON objects as the name/value pair? Is that the summary of this change?

    The reason that DataTables doesn't do this by default is for compatibly with old versions of jQuery when you had to use {"name": ..., "value": ... } and unfortunately I'm a bit suck with it now.

    How about just converting your post data array to name value array object pairs on-the-fly:

    [code]
    fnServerParams: function ( aoData ) {
    for ( var key in oPostData ) {
    if ( oPostData.hasOwnProperty(key) ) {
    aoData.push( "name": key, "value": oPostData[key] );
    }
    }
    }
    [/code]

    I will look at expanding the abilities of DataTables to built this in in future.

    Allan
  • lyradlyrad Posts: 8Questions: 3Answers: 0
    Hi guys,
    Was just you hoodlumj3, it cater for me :)...
    I'm trying to use datatables with this godDamn Zend Framework (me too!). For that, two ections needed :

    - To rewrite Server side (PHP) code (http://datatables.net/release-datatables/examples/data_sources/server_side.html) to use dBTable class included in Zend ;

    - To find a way to make ajax post http request with datatable ;

    I try to use your code to do that, but there's something i should have missed :
    My firebug give me an error when testing it :

    [quote]
    $("#centredoc_list").datatable is not a function
    [Stopper sur une erreur]
    'aoAjaxData': function (aoData) { aoData.push(oPostData); }
    [/quote]

    The code :
    [code]
    ...





    $.ajaxSetup( {'type': 'POST', 'url':'/centredoc/ajax/lister', 'dataType': 'json' } );
    var oPostData = {'hello':'there', 'name2':'value2', 'name2':'value2'};
    //oPostData['name3'] = this.options.value3;

    $('#centredoc_list').datatable({
    'sAjaxSource': $.ajaxSettings.url,
    'aoAjaxData': function (aoData) { aoData.push(oPostData); }
    });

    ...

    ...

    [/code]

    Could you give me a link to a exemple page with your code working? Could help me to understand...
    Thanks!!!
This discussion has been closed.