-1

I am trying to pass JS variable[array] to PHP. My idea is that javascript will print the array as a string with innerHTML to a div

document.getElementById("id").innerHTML = variable;

and if when I click on a POST button, PHP will collect it, but all of my attempts failed... :( Can someone help me, please? Is it even possible? Are there any better or working ways how to pass a variable to PHP from JS? I would rather avoid using AJAX and other stuff

Atom
  • 5
  • 1
  • 5
  • Dear Atom, PHP is executed on server side and JS is executed on client side. So there is no you pass variable from JS --> PHP. If you want to pass something to PHP then you need to invoke php apis. – Ashwin N Bhanushali Oct 07 '17 at 11:35
  • yes... i know .. but the php will ask for the variable only after it is created(by clicking to the button... ) it could transfer me to other side, it doesn't matter, i only need to save the variable... – Atom Oct 07 '17 at 11:38
  • Ajax is the only way to get data from PHP to js else you can try JSON encoder in PHP to transfer PHP JSON data to js. – Rajendran Nadar Oct 07 '17 at 12:41

1 Answers1

1

One method I used in the past was to create a hidden form and set the value of each input with JavaScript or jQuery. Then on submit it will send the data to the PHP script.

EDIT: Here's the gist of it:

The hidden input:

<input type="hidden" id="hiddenInput" value="">

Set the value with javascript:

document.getElementById('hiddenInput').value = 'value';

or set it with jQuery:

$("#hiddenInput").val('value');

Then send to PHP with submit button.

Zach A
  • 51
  • 1
  • 6
  • Not on hand, but this SO answer goes over it: https://stackoverflow.com/questions/5700471/set-value-of-input-using-javascript-function – Zach A Oct 07 '17 at 12:13
  • This actually works! :D You are a hero mr. Zach A...!! Thanks a lot!! :D :D – Atom Oct 07 '17 at 13:22