0

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>");
?>
8
  • 1
    Looks like you're seeing the output of var_dump(). Show us the full PHP code (the relevant part). Commented Mar 11, 2014 at 12:38
  • @AmalMurali I've added my code. Commented Mar 11, 2014 at 12:47
  • remove the var_dump()s Commented Mar 11, 2014 at 12:48
  • @ekhaled Ok, but now how am I supposed to see the result? Commented Mar 11, 2014 at 12:49
  • does the browser console show a json object if you run console.log(_leafs); after the variable assignment? Commented Mar 11, 2014 at 12:52

4 Answers 4

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

1 Comment

Not sure why the = was missing, but I've added it now. No changes though.
0

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.');
    });

1 Comment

This causes the custom error "Error calling XML script".
0

Did you try this?

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

2 Comments

This gives me exactly the same result.
Make array like this and parse it to $.get() var _leafs = { 0: true, 1: false }; Or else as your question, you can apply $.ajax() rather using $.get

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.