user1433479
user1433479

Reputation: 135

PHP to Jquery through json ruins array

I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery. One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).

The problem occurs when I'm trying to put the PHP variable through JQuery. What I have to do this for me is:

var _leafs = <?php echo json_encode($leafs); ?>;

When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.

When I use the above code and alert() the result it's missing the brackets and quotes. Even weirder is when I pass it through like so:

$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {

The result is this:

" string(4) "
" 

Which shows up to be a <br> in my html reader.

Am I missing something when I'm converting it to json?

Additional code:

<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
    // The XML file could not be reached
    echo 'Error loading XML. Please check the URL.';
} else {
    // Get the XML file
    $dom = new DOMDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXpath($dom);

    $paths = [];
    $leafs = [];
    foreach ($xpath->evaluate('//*|//@*') as $node) {
        $isLeaf = !($xpath->evaluate('count(@*|*) > 0', $node));
        $path = '';
        foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
            $path .= '/'.$parent->nodeName;
        }
        $path .= '/'.($node instanceOf DOMAttr ? '@' : '').$node->nodeName;
        if ($isLeaf) {
            $leafs[$path] = TRUE;
        } else {
            $paths[$path] = TRUE;
        }
    }

    $paths = array_keys($paths);
    $leafs = array_keys($leafs);

    echo "Choose a path<br><br>
            <form>
                <select id='field_dropdown'>";
                foreach($paths as $value) {
                    echo "<option value='".$value."'>".$value."</option>";
                }
    echo    "   </select>
                <button id='send_path'>Send path</button>
            </form>
            ";

}
?>

<script>
$(document).ready(function() {
$('#send_path').click(function() {
    var _path = $("#field_dropdown").val();
    // Get the leafs array and send it as a json string to set_fields.php
    var _leafs = <?php echo json_encode($leafs); ?>;
    $.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
        $('#fields').append(data);
    }).error(function() {
        $('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
    });
    return false;
});
});
</script>

And here the code where I want the json array to end up (and then get turned back into a PHP array).

<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }

var_dump($path."<br>");
var_dump($leafs."<br>");
?>

Upvotes: 0

Views: 125

Answers (4)

theLibertine
theLibertine

Reputation: 175

What if you get the array through jquery instead of echoing it?

<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />

and then

var _leafs = $('#hidden-value').val();

Upvotes: 1

Vier
Vier

Reputation: 807

What about adding an = after the lf query parameter when you build the get URI?

$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...

Upvotes: 1

Sadee
Sadee

Reputation: 3180

Did you try this?

var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]

Upvotes: 0

Misters
Misters

Reputation: 1347

Just write 'json' in the last parameter of get method:

   $.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
        $('#fields').append(data);
    },'json')//<-- this
     .error(function() {
        $('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
    });

Upvotes: 0

Related Questions