-2

Here is my frontend code:

<div>
     <form id="someForm" action="myAPI" method="post">
          <input type="text" name="arr" style="display:none" id="arr">
          <button type="submit" name="submit">Submit</button>
     </form>
</div>

Here is the array assignment part of my jquery code

$(function() {
    var finalArray = {
       "a":1,
       "b":2,
       "c":3
    };

    finalArray = JSON.stringify(finalArray);

    $('#arr').val(finalArray);
}

Now, when I handle the submitted finalArray from php backend, it detects the array as a string. I want to convert it back to array, so that I can parse.

Having [] in the input field will not work for me as the finalArray is a dynamic associative array.

What am I missing here?

I have already used json_decode, not working for me. It seems like whenever I assign the object in input value, it automatically gets converted as string.

Scarecrow
  • 66
  • 6

2 Answers2

0

You can use the PHP function json_decode to parse an array to a JSON array. You could also use a function to check if the array is valid, like in this question: Fastest way to check if a string is JSON in PHP?

Tim
  • 551
  • 3
  • 23
  • Could you post the string that you receive in your backend? json_decode should work, so it's you're probably not receiving a valid JSON string when you submit. – Tim Oct 28 '19 at 11:54
0

You can use PHP function json_decode.

$array = json_decode($_POST['data'], true);
armandex
  • 1
  • 1