phpjqueryajaxtablednd

losing first data element jquery ajax call


I am having a problem that I cannot figure out.

I am using the tableDND jQuery add in, which allows me to drag and drop rows of a table. I want to send those rows to the server and have them uploaded to a mySQL database.

My code is below, basically when I get to the PHP the first element of the batting variable is gone. Any ideas?

So I have the following javascript:

$('#order').tableDnD({
        onDrop: function(table, row) {

            var batting = $.tableDnD.serialize();
            var id = <?php echo $id;?>;

            $.ajax({
                type: 'POST',
                url: 'update_batting.php',
                data: '{ "batting":' + batting + ', "id":'+ id +' }',
                dataType: 'json',
            });

        }
    });

and the following php:

<?php

$batting = json_encode($_POST['order']);

$query = "INSERT INTO test (t) VALUES ('$batting')";
mysql_query($query);

?>

Solution

  • Ok so this is my crude guess at this one since I have to go soon...

    I think since "data" is converted to a query string it is being misread. I think your post is probably reading this:

    $_POST['batting'] = 'order[]=110209';
    $_POST['order'] = 'order[]=100245&order[]=100007&order[]=100296&order[]=10‌​0213&order[]=100071&order[]=100125&order[]=110206&order[]=110205&order[]=100152&o‌​rder[]=100247&order[]=100329&order[]=100299&order[]=100243';
    $_POST['id'] = '662852670';
    

    Because the first occurrence of the ampersand is terminating your variable.

    It might seem silly, but you can probably escape this whole problem by surrounding "batting" with double quotes. Effectively containing it as a string.

    data: '{ "batting":"' + batting + '", "id":'+ id +' }',
    

    This would change your expected $_POST['order'] variable to "$_POST['batting'] However, your data object should be contained like I originally mentioned in the comment above.

    data: {order: '"' + batting + '"', id:id},
    

    Instead of sending it as a string with no key as in your sample code.

    Try var_dump($_POST) in php to see all values you're getting... just out of curiosity.

    **Sorry for all the edits. I'm being distracted constantly at work...