1

I've looked at several other suggestions on this issue but for some reason my data is not being posted. Here is the relevant section of my code:

<input type="button" id="map_submit" value="Map Selection" />
<?php var_dump($_POST); ?>  // display the posted variables

and

<script type="text/javascript">
    $(document).ready(function(){
        $('#map_submit').click(function(){

            /*  this part is from the slickgrid plugin, in which
             *  selectedData is an array that I want to post to the page
             *  and read via php
             */
            var selectedData = [], selectedIndexes;
            selectedIndexes = grid.getSelectedRows();
            jQuery.each(selectedIndexes, function (index, value) {
                 selectedData.push(grid.getData()[value]);
            });

            $.post("mapper.php", {dataArray: selectedData});
        });
    });
</script>

From what I've seen from other questions, $.post should work. But, when I click the button, nothing is shown from the var_dump. As a sanity check, if I add this to the javascript:

for (var i = 0; i < selectedData.length; i++) {
     document.write(selectedData[i].questionID + "<br />");
}

it will print the questionID values I selected in the grid (of course to a newly blank page).

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
Aaron
  • 1,693
  • 4
  • 26
  • 40
  • possible duplicate of [Pass Javascript Array -> PHP](http://stackoverflow.com/questions/5035547/pass-javascript-array-php) – Diodeus - James MacFarlane Jun 21 '12 at 14:29
  • 1
    What shows up if you console.log(selectedData); before the .post? – somedev Jun 21 '12 at 14:29
  • 2
    Wait, are these pieces of code in the same file? If they are then it appears you're expecting a piece of PHP to run client side. It doesn't work that way. You need a callback on `$.post` to do something with the returned data. – Cfreak Jun 21 '12 at 14:31
  • Yep, show us the file structure and where is var_dump()... – Cranio Jun 21 '12 at 14:33
  • Use JSON to encode your JS data in strings, and then use `json_decode` function in PHP to decode it into php objects. – Hrishikesh Jun 21 '12 at 14:37
  • Ah, I see. Yes, they are in the same page. I think I just confused how php and jquery treats posts. Basically I have a datagrid (slickgrid) that I want to reload the data (with php) from after I click the button (using javascript to get the selected values to update) – Aaron Jun 21 '12 at 14:38
  • @Hrishikesh: Why use JSON when you can just send it as POST data? – gen_Eric Jun 21 '12 at 14:40
  • So, I should send the post to a second page? Seems redundant if I want to keep the same interface. Also, console.log just shows the selectedData object with it's fields as expected. – Aaron Jun 21 '12 at 14:41
  • Rocket, Mainly because POST is just a string, JSON is widely used and has functions in pretty much all languages to covert to-and-from objects. So you can have JS arrays in one place, work with it, export JSON data, and in PHP file, simply convert them as PHP arrays, without having to bother about syntax and such formatting. – Hrishikesh Jun 21 '12 at 14:42
  • @Hrishikesh: You don't need to use JSON to use PHP's POST. If you post a JS object (or array) to PHP, it'll be converted correctly for you. Query strings are the way to go here. – gen_Eric Jun 21 '12 at 14:44
  • What does `mapper.php` look like? – gen_Eric Jun 21 '12 at 14:46
  • Here is my php page: http://pastebin.com/KsxCMwCE – Aaron Jun 21 '12 at 14:51
  • The php part just reads data from a database and populates that into the slickgrid jquery plugin (allows you to select rows with checkboxes). I want to click the button and have php read which rows were selected. – Aaron Jun 21 '12 at 14:52
  • The reason I need php to read that is because I need to update the database based on those selected. – Aaron Jun 21 '12 at 14:59

2 Answers2

2
$.post("mapper.php", {dataArray: selectedData});

This line is fine. I don't know why everyone is suggesting JSON, because that's unnecessary here. You can just POST objects/arrays normally without using JSON.

Note: this will not reload the page. It will POST to mapper.php via AJAX, so aren't going to see anything anywhere on the page. You'd need to look in your dev tools to see what the AJAX call returned.

Or, you can check the data the POST returns.

$.post("mapper.php", {dataArray: selectedData}, function(data){
    console.log(data); // check your console, you should see some output
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Ah, yes. The console has the whole html page printed. So, basically, I cannot send an array from jquery to php in the same page right? – Aaron Jun 21 '12 at 14:57
  • 1
    @Aaron: PHP runs on the server. It outputs the HTML page which is rendered by your browser. Once the page is in your browser, PHP is done running. So, you need to load a new page to send the POST data to. Since you're using AJAX, I suggest making a new PHP page, POSTing the data there, then returning data to your page. – gen_Eric Jun 21 '12 at 14:58
  • Ok, so can I just put all my database connection code into a separate PHP page, so when it POSTs it updates the database (when selectedData is set), gets the new results, and then jquery will have to take that result and update the grid? – Aaron Jun 21 '12 at 15:06
  • A quick follow-up question: I cannot read the array in php. I put the connection code into mapconnect.php. I also have the line if (isset($_POST['dataArray']) but it doesn't return true when jquery posts to that page. Any thoughts? – Aaron Jun 21 '12 at 17:40
  • @Aaron: Try to `var_dump($_POST)`. I assume `selectedData` actually contains something. `console.log(selectedData)`. – gen_Eric Jun 21 '12 at 17:58
  • var_dump shows array(2) { ["isbn_select"]=> string(13) "0-02-825178-4" ["isbn_submit"]=> string(6) "Update" }. But these variables are set when I initially choose which data (isbn) to load into the grid via a dropbox and button (with a php self post). My problem is after that, I click the button for jquery to post and mapconnect.php doesn't receive anything it seems – Aaron Jun 21 '12 at 18:17
  • selectedData does contain something. Console shows a list of objects and their fields – Aaron Jun 21 '12 at 18:18
  • In my main page, mapper.php, I have . Could this be affecting the post call with jquery? – Aaron Jun 21 '12 at 18:19
  • @Aaron: That shouldn't matter. When you see the page in the browser, PHP is done running. When you make the AJAX call, the PHP is ran again. – gen_Eric Jun 21 '12 at 20:25
  • Yes, that makes sense. Thanks for all your help. Well, I ended up doing a slightly different implementation in the end because I couldn't get php to read the array POSTed from jquery. So, I had jquery write a form to a div containing a button and the array as a hidden field using .html. That button then posts to PHP_SELF in the usual manner and I can read the array. For my case, this work around is ok, but I'm still curious as to why I couldn't get it to work directly. – Aaron Jun 21 '12 at 20:44
  • I'm not sure. Maybe something in your page is editing `$_POST`? Not sure. – gen_Eric Jun 21 '12 at 20:53
1

You'll have to serialize the object pre-post and then deserialize on the server (presumably in PHP) before you can use it.

Example below (requires json2.js):

<script type="text/javascript">
    $(document).ready(function(){
        $('#map_submit').click(function(){

            /*  this part is from the slickgrid plugin, in which
             *  selectedData is an array that I want to post to the page
             *  and read via php
             */
            var selectedData = [], selectedIndexes;
            selectedIndexes = grid.getSelectedRows();
            jQuery.each(selectedIndexes, function (index, value) {
                 selectedData.push(grid.getData()[value]);
            });

            $.post("mapper.php", JSON.stringify({dataArray: selectedData}));
        });
    });
</script>

<input type="button" id="map_submit" value="Map Selection" />
<?php var_dump(json_decode($_POST, true)); ?>  // display the posted variables
pete
  • 24,141
  • 4
  • 37
  • 51
  • Why do you need to `JSON.stringify`? What's wrong with just using the normal POST data? Plus I'm not sure `json_decode($_POST, true)` would even work. You'd need to read the raw POST data. `json_decode(file_get_contents('php://input'), true)` – gen_Eric Jun 21 '12 at 14:42
  • I'm also not sure if `$.post` will let you send a JSON string like that. – gen_Eric Jun 21 '12 at 14:55
  • @Rocket: JSON.stringify is to serialize the JavaScript object to a JSON-encoded string which can then be posted to the server. While jQuery has a `$.parseJSON` function, for some reason the jQuery development team has neglected to include a `stringify` function. `json_decode($_POST, true)` is from an example at http://php.net/manual/en/function.json-decode.php showing how to take a JSON-encoded string and deserialize it server-side. – pete Jun 21 '12 at 15:02
  • JSON is still the wrong tool here. Why don't you just send the data to POST using the *normal* post array (query strings)? `$.post("mapper.php", {dataArray: selectedData});` Plus `json_decode($_POST, true)` still isn't right. `$_POST` will always be an array. – gen_Eric Jun 21 '12 at 15:11