Post Multiple Selected Rows to PHP (Non-Server Side Processing)

Post Multiple Selected Rows to PHP (Non-Server Side Processing)

bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
edited August 2011 in DataTables 1.8
Hello,

Fair warning as I'm a newbie just getting into PHP/JQuery.

I have been working with DataTables the last couple days and can retrive and render a DataTable and select multiple rows just fine from a PHP script, but now I need to figure out how to post the multiple selected rows to PHP. I've looked extensively, but am unable to find a suitable example (the only one's I can find are either for single-row, GET, or server-side processing). I would very much appreciate any help.

Thanks,
Blake

Replies

  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    Please explain what you mean by "post rows to PHP".

    I think what you're asking for is how to send an HTTP request to a server side script that lists ID's (or some other identifying info on rows in DT) for some processing.

    I think the simplest approach to this would be
    1) mark rows/cells with CSS class as they are "selected" (whatever your selection process is, probably clicking on them, or clicking a checkbox in them)
    2) use jquery and a CSS selector to iterate those rows/cells to get ID's
    3) send HTTP request to PHP script with a list of those ID's
    4) receive feedback from PHP server? display somehow?

    is this what you mean?
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    fbas,

    First of all, thanks so much for your quick reply and assistance.

    Yes, I think what you describe is what I want. I want to capture the values of a specific column of all selected rows, and return those values back to the PHP script via an HTTP POST method for further processing. In fact, since my original post, I am able to get the selected row information by implementing this code, http://datatables.net/forums/discussion/582/user-selectable-rows-multiple-rows-with-server-side-processing/p1

    However, there are a few problems with the behavior from this code:

    1, It’s server-side processing which I don’t need. I’m using MS SQL and the sorting/filtering doesn’t work when set as server-side. Plus I’m working with a very small dataset.

    2. Though I can capture the information I want from the selected rows, I’m not sure how to post those values back to the PHP script.

    Thanks,
    Blake
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    1. when using bServerProcessing, you need your server side script to perform searching, sorting, and pagination. If you want to avoid that, you can have your MS SQL script generate JSON and use AjaxSource with bServerProcessing false.. this way the client does the searching, sorting, and pagination

    2. to post values back to the server, you will make an HTTP call on the client side and will need a script on the server side to receive the call and update the server.
    I wrote to someone else this morning about it, read the $.ajax() call here: http://datatables.net/forums/discussion/6105/is-there-a-way-to-use-bserverside-true-along-with-fnadddata#Item_2

    on the server side, read in the $_POST values (you probably want to send an ID and VALUE pair for every row) and compose SQL to update those rows.
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    fbas,

    I've managed to get it working to the point that I'm using local processing and I can retrieve the column information I need after I click a button after selecting the rows. I can send the correct data to an alert box (comma delimited). I have the $.ajax settings in place, but nothing is posted to the server in $_POST and I'm thinking the $.ajax needs to somehow be tied to the submit button click event? Here is my DT code...

    [code]
    var oTable;
    var selected = new Array();

    $(document).ready(function() {
    $('#form').submit( function() {
    alert (selected);
    return false;
    } );

    /* Init the table */
    oTable = $("#example").dataTable({
    "bProcessing": true,
    "sAjaxSource": "GetPrjData.php",
    "fnServerData": function ( sSource, aoData, fnCallback ) {
    $.ajax( {
    "dataType": 'json',
    "type": "POST",
    "url": sSource,
    "data": aoData,
    "success": fnCallback
    } );
    },

    "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
    var iPos = oTable.fnGetPosition( nRow );
    if ( jQuery.inArray(aData[0], selected) != -1 )
    {
    $(nRow).addClass('row_selected');
    }
    if ( iPos != null )
    {
    var aData = oTable.fnGetData( iPos );
    if ( jQuery.inArray(aData[0], selected) != -1 )
    {
    $(this).addClass('row_selected');
    }
    }

    $(nRow).click( function () {
    var iPos = oTable.fnGetPosition( nRow );
    var aData = oTable.fnGetData( iPos );
    var iId = aData[0];
    if ( jQuery.inArray(iId, selected) == -1 )
    {
    selected[selected.length++] = iId;
    }
    else
    {
    selected = jQuery.grep(selected, function(value) {
    return value != iId;
    } );
    }

    $(nRow).toggleClass('row_selected');
    });
    return nRow;
    }
    });

    });
    [/code]

    And here is my HTML.

    [code]







    Project
    User
    Desc
    Status
    Date Updated
    Time Updated




    Loading data from server








    [/code]


    Thanks,
    Blake
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    edited August 2011
    add an id attribute to your

    then you can add your $.ajax() to the handler for that button

    [code]
    // using
    $('#submit').click( function () {
    // put your $.ajax call to update server here.
    });
    [/code]
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    fbas,

    I’ve tried what you suggested but nothing is posted back to PHP when the .ajax call is in the click handler, not even for static data. The same code below however, does post back correctly when used in conjunction with the "fnServerData" within the table init (so I know the ajax call is correct). Any chance you or someone could provide the code on getting it to work within the click handler?

    [code]
    $('#submit').click( function () {
    var items = [];

    items.push( { "name": "My Name", "value": "My Value" })

    $.ajax({
    type: "POST",
    url: "GetPrjData.php",
    dataType: 'json',
    data: items,
    success: fnCallback
    });
    [/code]


    Thanks,
    Blake
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    [code]


    $('#submit').click( function () {
    sSelected = selected.join(','); // join elements in the "selected" array into a single string

    $.ajax({
    type: "POST",
    url: "GetPrjData.php",
    dataType: 'json',
    data: {"selected": sSelected },
    success: function(data, textStatus, jqXHR) {
    console.log(data, textStatus); // I don't know what you want to do with any returned data, so I'll just write it to console.log() .. note: IE doesn't support console object
    }
    });

    [/code]

    this should send a request to GetPrjData.php with POST value selected=id1,id2,id3,id4 or however your selected array elements look. so your server side script should check for $_POST['selected'] and process that string (probably convert back into an array and update database)

    [code]
    // this is in PHP. adjust to your language of choice.

    // if parameter 'selected' is set, use that value (but sanitize it), else $sSelected is empty string
    $sSelected = isset($_POST['selected']) ? mysql_real_escape_string($_POST['selected']) : "";
    $aSelected = explode(',', $sSelected); // break string into elements delimited by comma

    // create WHERE clause based on the selected rows
    $column = "ID"; // is your column named ID?
    $sWhere = "";
    foreach ($aSelected as $s) {
    if (!$sWhere) $sWhere = " WHERE ";
    else $sWhere .= " OR ";
    $sWhere .= " $column = '$s' ";
    }


    // etc.
    [/code]
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    fbas,

    Thanks for that. However, I get an error in the Firebug console when it tries to post after clicking the submit button. I can see via Firebug that the variable “selected” has the correct comma delimited data. For what it’s worth, if I add the same .ajax call inside the "fnServerData" of the initialized DT, then it posts back.

    Here's my click function after your suggestions.

    [code]
    $(document).ready(function() {

    $('#submit').click( function () {
    sSelected = selected.join(',');

    $.ajax({
    type: "POST",
    url: "GetPrjData.php",
    dataType: 'json',
    data: {"selected": sSelected },
    success: function(data, textStatus, jqXHR) {
    console.log(data, textStatus);
    }
    });
    });
    [/code]


    Thanks,
    Blake
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    depends where you defined "var selected". it might be out of scope

    [code]
    var selected = new Array(); // this will work because selected is available to everyone

    $(document).ready( function () {
    $('#example').dataTable();
    });

    $('#submit').click( function () {
    sSelected = selected.join(',');
    // etc
    }
    [/code]

    vs.
    [code]
    $(document).ready( function () {
    var selected = new Array(); // this will not work with $('#submit').click().. not in scope
    $('#example').dataTable();
    });

    $('#submit').click( function () {
    sSelected = selected.join(',');
    // etc
    }
    [/code]

    --------------------------------------

    and more
    [code]
    $(document).ready( function () {
    var selected = new Array(); // this will work for anything inside this function
    $('#example').dataTable();


    $('#submit').click( function () {
    sSelected = selected.join(',');
    // etc
    }

    });
    [/code]

    vs

    [code]
    $(document).ready( function () {
    var selected = new Array(); // won't work for the $('#submit').click().. it's in a separate scope
    $('#example').dataTable();
    });


    $(document).ready( function () {
    $('#submit').click( function () {
    sSelected = selected.join(',');
    // etc
    }

    });
    [/code]
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    It's like in your first example, so I don't think it's a variable issue. Plus, even when I try to send static data with the :data parameter, instead of the 'select' variable, I get the post error in Firebug as well (when within the click function). I don't get any hard error I just notice the post event is in red in Firebug.

    For example, this removes the variable issue and still fails to post when in the click event, but does post when within the init table's .ajax call.


    [code]
    data: {"selected": "Some Data" } ,
    [/code]


    Here's my latest full code:

    [code]
    var oTable;
    var selected = new Array();

    $(document).ready(function() {

    $('#submit').click( function () {
    sSelected = selected.join(',');
    $.ajax({
    type: "POST",
    url: "GetPrjData.php",
    dataType: 'json',
    data: {"selected": sSelected },
    success: function(data, textStatus, jqXHR) {
    console.log(data, textStatus);
    }
    });
    });

    /* Init the table */
    oTable = $("#example").dataTable({
    "bProcessing": true,
    "sAjaxSource": "GetPrjData.php",

    "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
    var iPos = oTable.fnGetPosition( nRow );
    if ( jQuery.inArray(aData[0], selected) != -1 )
    {
    $(nRow).addClass('row_selected');
    }
    if ( iPos != null )
    {
    var aData = oTable.fnGetData( iPos );
    if ( jQuery.inArray(aData[0], selected) != -1 )
    {
    $(this).addClass('row_selected');
    }
    }

    $(nRow).click( function () {
    var iPos = oTable.fnGetPosition( nRow );
    var aData = oTable.fnGetData( iPos );
    var iId = aData[0];
    if ( jQuery.inArray(iId, selected) == -1 )
    {
    selected[selected.length++] = iId;
    }
    else
    {
    selected = jQuery.grep(selected, function(value) {
    return value != iId;
    } );
    }

    $(nRow).toggleClass('row_selected');
    });
    return nRow;
    }
    });
    });
    [/code]

    I really appreciate all your help!
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    probably my misunderstanding. $.ajax might need the data object to have "name" and "value" members.
    [code]
    data: { "name": "selected", "value": sSelected }
    [/code]
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    Unfortunatley, that did't work either. Here's my FB output if it helps at all.

    http://imageshack.us/photo/my-images/833/firebugout.jpg/
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    so it's posting properly, just not getting proper response? your server script is not behaving.
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    No, it's not posting at all. My server script is dumping $_POST to a text file, which is how I know whether the posted data made it to my PHP script. The $_POST is not updated when .ajax is used with the click function. But this scenario below does populate $_POST (of the exact server script that the click event cannot update). Odd.

    [code]
    oTable = $("#example").dataTable({
    "bProcessing": true,
    "sAjaxSource": "GetPrjData.php",
    "fnServerData": function ( sSource, aoData, fnCallback ) {
    $.ajax({
    "type": "POST",
    "url": "GetPrjData.php",
    "dataType": 'json',
    "data": {"name": "My Name", "value": "My Value" },
    "success": fnCallback
    });
    },
    [/code]
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    I took your code and put it in a file. the POST worked.

    not sure why it's not working on your side.
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    Can you share the exact code you tested including the PHP script?
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    http://www.beg.utexas.edu/_work/dt/bmcdonald/index.htm

    you can view the sources, and I've included the source of the PHP file in the main page

    note my ajax source and the AJAX call are not calling the same file, but the principles are the same.
  • bmcdonaldbmcdonald Posts: 10Questions: 0Answers: 0
    fbas,

    Success! It was the HTML that was the culprit. After looking at your code, I realized that I had a tag and you did not. I removed that, and Bingo!

    University of Texas, huh? Good thing I dind't tell you I'm an Oklahoma Sooner or you might have never helped me!

    You're a HUGE help and and I really appreciate your patience and persistance with this Newbie. Gonna make a donation to DT in your honor my friend.

    Hook 'Em.

    FYI, for any others with the same issue. Here's the faulty code. I just removed the form elements to make it work.

    [code]






    Project
    User
    Desc
    Status
    Date Updated
    Time Updated




    Loading data from server







    [/code]
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    heh. I'm a transplant so the rivalry is lost on me. glad you figured out what was wrong.
This discussion has been closed.