sreelakshmi
sreelakshmi

Reputation: 274

Pass php array from form to javascript file

I have a php associative array $php_array. Also, I have a form like below in my php file.

<form action="" method="post">
    <p class="submit">
        <input name="submit" class="button-primary" value="Send" type="submit" id="">
        <input type="hidden" name="details" value="' . $php_array . '"/>
    </p>
</form>

I want to pass this array $php_array to a javascript file like

  `details = $("input[name=details]").val();`

The array is in the form

Array(
    [59] => Sree
    [53] => Smith
)

I want to display the names as drop down using javascript on clicking the link 'send'. how can I pass the php array to javascript

Upvotes: 0

Views: 527

Answers (3)

Md Nozibulla Bashar
Md Nozibulla Bashar

Reputation: 675

Simply encode your variable to json using json_encode($php_array) then in the JavaScript side parse it back using JSON.parse()

Upvotes: 0

hassan
hassan

Reputation: 8288

You should encode your php array into json format, then decode it from client side;

<form action="" method="post">
    <p class="submit">
        <input name="submit" class="button-primary" value="Send" type="submit" id="">
        <input type="hidden" name="details" value='<?php echo json_encode($php_array); ?>'/>
    </p>
</form>

and from your javascript file :

var details = JSON && JSON.parse($("input[name=details]").val()) || $.parseJSON($("input[name=details]").val());

Upvotes: 2

Martin Buezas
Martin Buezas

Reputation: 394

It's not clear your end goal, is it posting via XHR (ajax)?

In that case I think using the form to pass the data is not required. You could just encode it to json and grab it on you JS file or block like this:

<script type="text/javascript">
  var details = <?php print(json_encode($php_array)) ?>;

  // using jQuery
  $('form').on('submit', function(e) {
    // use 'details' here as you need
    return false;
  });
</script>

Upvotes: 1

Related Questions