weymeels weymeels - 1 month ago 8
Javascript Question

Pass an object from php to javascript

I have a little problem, I need to give an object at JS when clicked on a button, but I don't know how to do it.

Here is my code php

echo '<script>';
echo 'var monObjet = "'.json_encode($product).'";';
echo '<script>';
<button type="button" onclick="ShowModal(monObjet)" class="btn btn-info btn-lg" data-toggle="modal" >Open Modal</button>';


and this is my code JS

function ShowModal(monObjet){

var monObjet = monObjet;
alert(monObjet);

$('#myModal').appendTo("body").modal("show");

// $('#NomProduit').text(monObjet);




};
</script>


Thanks in advance.

Answer

Try this:

echo '<script>';
echo 'var monObjet = '.json_encode($product).';';
echo '</script>';
<button type="button" onclick="ShowModal(monObjet)" class="btn btn-info btn-lg" data-toggle="modal" >Open Modal</button>';

Edit: You had quotes around the json_encode() part, so JS thought it was a string, not an object.

Comments