Chud37
Chud37

Reputation: 5007

Accessing javascript array from function

Okay, so in my <head> section i have the following:

<script>
    var userDefaultInfo = '<?=$userInfo;?>';
    var jGets = new Array ();
    <?
    if(isset($_GET)) {
        foreach($_GET as $key => $val)
            echo "jGets[\"$key\"]=\"$val\";\n";
    }
    ?>
</script>

Now In my external .JS file, In the $(document).ready() section I can access userDefaultInfo fine, however, I am trying to access jGets, but not directly from there.

in the external .JS file, outside of $(document).ready(); I have the following function:

var sendGET = function () {
    var data = $(this).val();
    var elementName = $(this).attr("name");
    var url = "zephi.php?p=home/support/admin_support.php&"+elementName+"="+data;
    jQuery.each(jGets, function(i, val) {
           alert(val);
        });
    alert(url);
    window.location = url;
}

When a user changes a box, this function fires and changes the window location using the data. However, I want to add the data in the variable jGets, but I do not seem to be able to reference it at all in there.

Why is this?

Upvotes: 0

Views: 69

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

Perhaps doing either one of the following might work:

echo 'var jGets = '.(isset($_GET) ? preg_replace('/^"|"$/','',json_encode($_GET)) : '{}').';'
//or
echo 'var jGets = JSON.parse('.isset($_GET) ? json_encode($_GET); : '"{}"'.');'

This will produce an object literal, assigning everything you need to jGets, without having to mess about with loops. Since JSON stands for JavaScript Object Notation, it seems only logical/natural to use that to set the variable accordingly. Read more on json_encode here, more on JSON in PHP can be found here

Upvotes: 0

Andreas
Andreas

Reputation: 21881

You're "mis"-using an Array as an Object.

var jGets = {};

Upvotes: 2

Related Questions