alfajango / jquery-dynatable

A more-fun, semantic, alternative to datatables
http://www.dynatable.com
Other
2.78k stars 363 forks source link

Passing variables through AJAX #290

Open BigfootNick opened 6 years ago

BigfootNick commented 6 years ago

I've got a table:

<table class="table table-hover" id="beta">
    <thead>
        <tr>
            <th>Id</th>
            <th>Model</th>
            <th>AssetTag</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>A</td>
            <td>B</td>
        </tr>
    </tbody>
</table>

that is initialized with this DynaTable code:

<script>
    $(document).ready(function() {
        $('#beta').dynatable({
            dataset: {
                ajax: true,
                ajaxOnLoad: true,
                ajaxUrl: 'load-assets.php',
                records: "records",
                }
        });
    });
</script>

This pulls some JSON data from a SQL query.

<?php
    /*$newCategory = $_POST['newCategory'];*/
    $newCategory = "desktop";
    **SQL Query**
    $json = array();
    while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_NUMERIC ))
    {    
        array_push($json, array('id'=>$row[0],'Model'=>$row[3],'AssetTag'=>$row[4]));
    }
    $json_data = array(
        "records" => $json,
        "queryRecordCount"=>13,
        "totalRecordCount"=>13
    );
    echo json_encode($json_data);
?>

This works (which was a RELIEF after spending a whole day trying to get DataTables to work...) but only if I define my '$newCategory' variable from within this Ajax file. If I try to pass it from jQuery I get an error: Notice: Undefined index: newCategory in C:\wamp\www\bootstrap\load-assets.php

I've tried putting newCategory: "desktop" all over the dynatable function, but I can't get it to pass-through.

Also, though it pulls data when I hard-code in that variable value - I'm only requesting three columns: Id, Model, AssetTag, and I get four columns in the resulting table, three of which are filled with 'undefined' Edit: I figured out why I had 4 columns - now I have three, with two that are filled by 'undefined'

Any thoughts on how I can resolve those?

BigfootNick commented 6 years ago

Never mind about the 'undefined' columns... I changed my query from

while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_NUMERIC ))
    {    
        //array_push($json, array($row[0],$row[3],$row[4]));
        array_push($json, array('id'=>$row[0],'Model'=>$row[3],'AssetTag'=>$row[4]));

    }

to this:

while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_NUMERIC ))
    {    
        //array_push($json, array($row[0],$row[3],$row[4]));
        array_push($json, array('id'=>$row[0],'model'=>$row[3],'assetTag'=>$row[4]));

    }

I have no idea why that worked, but it did. Still, how do I pass a variable? I want to input the variable into my SQL query.