Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass php array to jquery function

Tags:

arrays

jquery

php

I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.

what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).

Problem is that i dont know how to pass my php array to the jquery function, any idea ??

this is how i fill the array:

$contador_acompanantes = 0;

foreach ($acompanantes->Persona as $acomp) 
{
  $numero = $acomp->Numero;
  $apellidos = $acomp->Apellidos;
  $nombre = $acomp->Nombre;

  $ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
  $contador_acompanantes++; 
}

got my select object:

<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>Acompañante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>

and this is my code for the jquery function (it is in the same .php page)

<script type="text/javascript">
$(document).ready(function() 
{ 
$('#acompanante_anterior').on('change', function() 
    {

    });
});
</script>
like image 229
Albert Prats Avatar asked May 25 '12 16:05

Albert Prats


2 Answers

var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
    // do your stuff
});
like image 54
mgraph Avatar answered Oct 03 '22 06:10

mgraph


You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/

HTML:

<select><option>---</option><option>Hello</option><option>World</option></select>

<script type="text/javascript">
    var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
    var json = JSON.parse(encoded_json_from_php);
</script>

jQuery:

$(function() {
    $("select").change(function() {
        $(this).unbind("change");
        var val = json[$(this).val()];
        var select = $(this);
        $(this).empty();
        $.each(val, function(i, v) {
            select.append("<option>" + v + "</option>");
        });
    });
});
like image 43
imsky Avatar answered Oct 03 '22 06:10

imsky