0

I have the following code:

 var data = $(this).sortable('serialize');
$.ajax({
                    data: {order: data, actionFor: 'main_articles'},
                    type: 'POST',
                    url: 'updateDisplayOrder.php',
                    success: function (msg) { //re-number the rows from 1 to n
                       //code goes here
                    },
                    error: function () {
                        alert("An error occurred");
                    });

And the PHP:

    require_once('../lib/common/db_connect.php');
    $ids = array();
    $actionFor = $_POST['actionFor'];
    foreach ($_POST['order'] as $value) //error here {
    //more code goes here
    }

The problem is that I get this error on the foreach line:

Warning: Invalid argument supplied for foreach()

I noticed that if I change this line:

 data: {order: data, actionFor: 'main_articles'}, 

To

data:data

And in the PHP :

foreach ($_POST['order'] as $value) //error here {

To

foreach ($_POST['item'] as $value)

It Works great. Why? How can I fox it? thanks!

8
  • Your POST parameter will be a string; if that string is actually JSON, you need to parse it to be an array before trying to iterate through it using foreach. Commented Jul 14, 2014 at 15:22
  • What do you get from var_dump($_POST['order']);? Commented Jul 14, 2014 at 15:31
  • @Styphon I got this: 'string(35) "item[]=2&item[]=1&item[]=3&item[]=4"' Commented Jul 14, 2014 at 15:34
  • @NaveTseva We'll there's your answer. It's not an array, it's a string. As Anthony Grist said, you need to parse it into an array first. Commented Jul 14, 2014 at 15:38
  • @Styphon Yes I noticed it now, can you take a look again at the question? I updated it and it seems strange to me that it's a string Commented Jul 14, 2014 at 15:40

1 Answer 1

1

$_POST['order'] contains a string, not an array. You need to parse your string into an array first. Try this:

$order = array();
$stg1 = explode("&", $_POST['order']);
$i = 0;
foreach($stg1 as $keyval) {
    list($key, $val) = explode("=", $keyval);
    $order[$i++] = $val;
}

Then you can do your foreach($order as $value) as you wish.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.