Question

I'm trying to send an array to PHP from JS.

JS:

var json = JSON.stringify(extraFields);
url += "&json="+json;

PHP:

$json = json_decode($_GET['json'], true);

foreach($json as $K=>$V){
    echo "json".$K . "=" . $V ."; ";
}

Assume extraFields is a valid array in this format:

extraFields['key1'] = 'val1';
extraFields['key2'] = 'val2';
extraFields['key3'] = 'val3';

The PHP error I'm getting is invalid argument for Foreach

When I loop through the $_GET values and just echo them, PHP shows empty brackets for $_GET['json'] so it's recognizing it as json..

What am I doing wrong?

Answer to TJ's comment

var extraFields = new Array();
                var countFields = THIS.$_FIELDS.length;
                var Row = new Array();
                while(countFields--){
                    var name = THIS.$_FIELDS[countFields]['name'];
                    var id = THIS.$_FIELDS[countFields]['id'];
                    var elemVal = getElmVal(id);
                    extraFields[name] = elemVal;
                    window.alert(name +"="+ elemVal);
                }
Was it helpful?

Solution

Two things:

  1. You can't just dump JSON on the end of a URL and expect it to go through to the server correctly.

    At the very least, you have to URI-encode it:

    url += "&json="+encodeURIComponent(json);
    
  2. The way you're using extraFields in your code snippet, it is not being used as an array. If you've created it as an array, those keys will not be serialized. The way you're using it, the correct way to create extraFields is:

    extraFields = {}; // NOT `= []` and NOT `= new Array()`
    

    That's an object, not an array. (Don't let the PHP term "associative array" fool you; that term is fairly PHP-specific and not related to the term "array" in the general sense. If you want arbitrary name/value pairs in JavaScript code, the term is "object" [or sometimes "map" or "dictionary", but they're objects].)

    If you add non-index properties to an array, JSON.serialize will ignore them (leave them out). Only use arrays ([]) with JSON for numerically-indexed data. Using objects ({}) for name/value pairs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top