4

I am creating an array of objects in jQuery.

var selected_tests = $("#selected_tests").find("tr");
jsonLab = [];
$.each(selected_tests, function() {
  jsonLab.push({
    test: ($(this).children()).eq(0).text(),
    amount: ($(this).children()).eq(1).text()
  });
});

I am posting this array to a PHP file by

$('<input type="hidden" name="jsonLab"/>').val(jsonLab).appendTo('#bill_print');
$("#bill_print").submit(); 

In my PHP file

if(isset($_POST['jsonLab']))
{
  $lab = json_decode($_POST['jsonLab'],true);
  foreach ($lab as $key => $value) {
    echo $value["test"] . ", " . $value["amount"] . "<br>";
  }   
}

There seems to be some mistake in the way I am using foreach or maybe it's incorrectly formatted JSON which isn't being decoded by PHP. I dont want to use AJAX for the submission.

4
  • Have you done any logging to see what $_POST['jsonLab'] is or what your $value are? Commented Jul 10, 2018 at 14:48
  • print_r($_POST); Commented Jul 10, 2018 at 14:48
  • 1
    Try stringifying your array before setting it to the hidden field. Commented Jul 10, 2018 at 14:50
  • @TiiJ7 , stringify did the job , Thanks Commented Jul 10, 2018 at 15:06

1 Answer 1

3

The issue is with this call:

.val(jsonLab)

jsonLab is an array of objects held in JS. As such, setting it to the val() of a jQuery object will mean toString() is called on it. The result of that is [object Object]. This is what's sent to your PHP logic, hence the error.

To fix this you need to manually stringify the JSON when you set it to the value of the text field:

$('<input type="hidden" name="jsonLab" />').val(JSON.stringify(jsonLab)).appendTo('#bill_print');

Also note that you can use a single map() call on the #selected_tests tr elements instead of selecting then pushing to an explicitly instantiated array:

var jsonLab = $("#selected_tests tr").map(function() {
  return {
    test: $(this).children().eq(0).text(),
    amount: $(this).children().eq(1).text()
  };
}).get();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate , JSON.stringify solved it , i will take your map suggestion aswell
No problem glad to help.

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.