ian
ian

Reputation: 12345

accessing speicific array elements with jquery

If my PHP returns a array with 6 elements how would I access each of them specifically in jquery?

For example I want to create:

var itemOne = value of first array element; var itemTwo = value of second array element; ...

$.get('ajax/employee_menu.php', { job: $('#job').val() },      
        function(data) 
        {
            //i want to put each value from 'data' into variables here.
         });

Upvotes: 0

Views: 283

Answers (1)

Tom Haigh
Tom Haigh

Reputation: 57845

Assuming you already have a javascript array, you can access array indexes in the same way as you would in PHP:

var itemOne = arrayFromPHP[0];
var itemTwo = arrayFromPHP[1];

If you don't have a javascript array, you could use json_encode() to convert a PHP array to javascript:

var arrayFromPHP = <?php echo json_encode($array); ?>;
var itemOne = arrayFromPHP[0];

or you could make an AJAX request (example using jQuery):

PHP:

<?php
echo json_encode(
    array( 'item1', 'item2', 'item3' )
);

Javascript:

$.getJSON(url, function(data) {
    var itemOne = data[0];
});

Upvotes: 2

Related Questions