0

I have two Javascript functions that will return values. I have little experience in JS and PHP, so what I was wondering - is how would I append the variables to a hidden field, and get them with PHP so I can perform some arithmetic with it, and return a final value which I can then display.

I can do the last part (calculate the last value, and display it). I was wondering how I could post the variables from the JS function, and get them with PHP saving them to a PHP variable WITHOUT USER INTERACTION - This is the most important part, it needs to be done automatically.

Thanks in advance,

  • 1
    You're looking for AJAX. – SLaks Oct 13 '13 at 22:39
  • Try this, http://stackoverflow.com/questions/2269307/using-jquery-ajax-to-call-a-php-function another good one, http://www.ibm.com/developerworks/library/os-php-jquery-ajax/ – johnny Oct 13 '13 at 22:40
  • Great. AJAX, I've been using it for other functions in my code. But my question persists, how would I pass a value in JS to a PHP Variable? –  Oct 13 '13 at 22:47
  • Safixk, see my answer below. – 1234567 Oct 13 '13 at 22:51

2 Answers2

0

There are multiple solutions to this.

You can insert the value into the query string and reload the page.

function send_to_php(var value) {
    window.location.assign("mypage.php?value=" + value);
}

In PHP, this is then stored in $_GET['value'] and $_REQUEST['value'].

You can also put the value inside a hidden input field in a form and run

document.getElementById('my_form').submit()

If you do not want the page to reload, you should use AJAX: http://www.w3schools.com/ajax/

EDIT:

To run functions in JavaScript without use interaction, just call the function anywhere inside a script, like send_to_php(44);. You can also use setTimeout("send_to_php(44)", 10000) to wait 10 seconds before calling the function.

If you wish the function to be run several times, call setTimeout again at the end of the function.

Atle
  • 1,867
  • 12
  • 10
0

A quick way to do this is to use AJAX (Asynchronous Javascript and XML).

JavaScript

$.post("/myfile.php", {phpvariable: javascriptvariable}, function(data) {
   // Do something after successfully sent.
   // e.g. location.reload();
 });

This will send you a POST variable without any user interaction to the specified PHP file.

myfile.php

<?php
   $javascriptvariable = $_POST['phpvariable'];
?>
1234567
  • 946
  • 6
  • 22