3

Possible Duplicate:
send arrays of data from php to javascript

I'm sending an Array with ajax to a php file. The Array is a list of names which should be stored in a database. In order to doublecheck this, I tried to echo the sql_query created in the php file. But the response is always

Invalid argument supplied for foreach()...

So I searched SO for some solutions, and often the answer was something like "your 'Array' is not an Array". So I echoed the Array submitted to the php, which returns all passed names on one line (what I think means that the Array arrives in the php-file).

So here's my JS...

var tourneyData = {
    tName : tourneyName,
    tNum : number,
    tNames : names, // this is an array
    tInt : international,
    tLig : liga,
    tStars : stars
};

$.ajax({
    type: "POST",
    url: "php/storeTourney.php",
    data: tourneyData,
    datatype: "json",
    success: function(response){
        alert("response " + response);
    }
});

... and PHP code

$tName = $_POST['tName'];
$tNum = $_POST['tNum'];
$tNames = $_POST['tNames'];
$tInt = $_POST['tInt'];
$tLig = $_POST['tLig'];

$insert = "";
foreach($tNames as $d){ // line pointed in the error message
    $insert += "INSERT INTO NAMES VALUES('test', '".$d."');";
}

echo $insert;

I do not exactly understand what's wrong in the code. What could possibly be wrong in the foreach()-statement, if $tNames obviously is an Array?

Community
  • 1
  • 1
Valentino Ru
  • 4,964
  • 12
  • 43
  • 78
  • Are you sure that it is an array? Have you `var_dump` it to verify that is the case? You won't get the error if it is an array. – Joseph at SwiftOtter Jan 01 '13 at 22:09
  • $tNames = (array)$_POST['tNames']; – CSᵠ Jan 01 '13 at 22:10
  • I agree with jMax, add some testing data at the top of your PHP file and make sure the logic works out before you send it over with JavaScript – AgnosticDev Jan 01 '13 at 22:10
  • In this case PHP only sees a string formatted as a Javascript array. You have to find a way to convert the js array into a PHP array. – Alexander Christiansson Jan 01 '13 at 22:11
  • The JavaScript is invalid, you haven't included the POST variable name. – Jeffrey Jan 01 '13 at 22:11
  • I'm not sure if javascript arrays translate directly to PHP and are able to be transferred that way, but I could be wrong. It would be really easy just to create hidden form fields with a loop to store each part of the array, though. – SISYN Jan 01 '13 at 22:11
  • dump the variable $tNames to see what it is: `var_dump($tNames)` – Levi Jan 01 '13 at 22:13
  • 1
    This may be a similar duplicate of another question, but it is NOT an exact duplicate of the proposed duplicate. It is the opposite problem, from JS TO PHP, not from PHP to JS. – Levi Jan 02 '13 at 05:45

4 Answers4

2

You need to hint to php that you want to get your data as an array. name tNames as tNames[]

var tourneyData = {
    tName : tourneyName,
    tNum : number,
    'tNames[]' : names, // this is an array
    tInt : international,
    tLig : liga,
    tStars : stars
};

Examples found here: http://api.jquery.com/jQuery.post/

If you are sending more complex objects or n-dimensional arrays, you will want to look into using JSON. you can use {object: JSON.stringify(object)} on the JS side and json_parse($_POST['object']) on the PHP side.

Levi
  • 2,103
  • 14
  • 9
  • This was the only solution that don't throws the error. However, now returning the insert-statement(s) results in the alert "response 0". Now, instead of getting NULL when returning var_dump($tNames), it returns information which says that the variable is an Array. But I just figured out that I'm concatenating the strings in the php file in a wrong way (+=) – Valentino Ru Jan 01 '13 at 22:28
  • Ah yes! don't get your PHP and JS mixed up (concatenate with . vs +). It can be hard sometimes to switch back and forth. I usually put $ signs in my JS... by accident, that is. – Levi Jan 01 '13 at 22:34
  • now the only problem is, that it is recognized as Array in php, but this Array contains only one element. Let's say I have an Array in JS like ['one', 'two', 'three'], in php I got the Array ['onetwothree'], because it returns "insert into names values('test', 'onetwothree'). Sorry about posting a new question... – Valentino Ru Jan 01 '13 at 22:37
  • (This is the response when echoing var_dump(): response array(1){[0]=>string(11) "onetwothree"}) – Valentino Ru Jan 01 '13 at 22:39
  • my only suspicion is your javascript is somehow making tNames a string before you perform the post. Try hardcoding tNames to an array and see what happens. Or if you use firebug or an equivalent, you can check the network tab and make sure the request is sent correctly as an array (should be `tNames[]=one & tNames[]=two & tNames[]=three`) – Levi Jan 01 '13 at 22:45
  • That's it! Very early in the JS-file, there was a tiny error which converted the Array into a String! Thanks very much! – Valentino Ru Jan 01 '13 at 22:53
1

In addition to the request being malformed, you are submitting a javascript array which PHP interprets as a string. Solution copied from another SO thread.

Gareth in Pass Javascript Array -> PHP

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

Community
  • 1
  • 1
0

You're missing the POST variable name in your JavaScript:

(...)

$.ajax({
    type: "POST",
    url: "php/storeTourney.php",
    data: {"data":tourneyData},
    datatype: "json",
    success: function(response){
        alert("response " + response);
    }
});

Now try a var_dump on the POST'ed data:

var_dump($_POST['data']);
Jeffrey
  • 1,239
  • 8
  • 15
  • all you are doing is encapsulating his individual post variables into a single object. – Levi Jan 01 '13 at 22:13
0

As it is you are trying to foreach on a string you would need to convert it to an object using json_decode to iterate over it.

$tNames = json_decode($_POST['tNames']);

see: http://php.net/manual/en/function.json-decode.php

Fraser
  • 15,275
  • 8
  • 53
  • 104