0

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

1
  • 1
    you will need to encode your array into json format, then decode that json from the client side and parse you decoded array from javascript; Commented Mar 10, 2017 at 15:29

3 Answers 3

2

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

4 Comments

I tried the same code but I'm getting the following error. Uncaught SyntaxError: Unexpected end of JSON input(…)
this means that your json is invalid , check the validity of it
Im getting the json encoded value asthis in php file.{"59":"Sree","53":"Smith"} on passing the same to js im getting that error
and update this code : value="<?php echo json_encode($php_array); ?>" by value='<?php echo json_encode($php_array); ?>'
1

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.