0

I have a PHP file run.php that is being used to display content, as well as insert / grab data from a MySQL database.

Within that file is a few JavaScript Promise functions that calculate a result, and display it on the page.

.then(function(calc) {
    ....   // various calculations
    result = 10;   // 10 is then displayed on the page
}

The function will end with a single result, for example result = 10 as shown above. That result (10) is displayed on the page. The issue I have is that I need to pass that result 10 from the JavaScript Promise function into my database.

After researching I'm not entirely sure this is possible. The converting the value from JavaScript to PHP, then inserting into a database seems possible, but I'm not so sure it's possible to actually get the result (10 in this case) from that JavaScript function, because Promises are asynchronus and results can't be returned from them (?).

I was wondering whether there's any way to use PHP to grab the result directly from the page (as the result is displayed on the page, as mentioned), then insert it into my database.

Hopefully someone can shed light on whether this is actually possible.

Pebble
  • 47
  • 8
  • You would use AJAX in your `.then()` to send the data back to PHP. – Jay Blanchard Mar 08 '17 at 16:40
  • Your problem is purely sending a value from JavaScript to PHP. The fact you don't have that value until the `then` handler of a promise doesn't make any difference; you just pass the value to PHP when you have the value. – T.J. Crowder Mar 08 '17 at 16:40
  • *"...because Promises are asynchronus and results can't be returned from them."* Promise *resolution* is asynchronous, yes; that doesn't mean you can't return results from a promise resolution, though; just that if you do, it will happen asynchronously. (But you don't need to, if you're just going to send it to PHP.) – T.J. Crowder Mar 08 '17 at 16:41
  • @T.J.Crowder From what I'm reading, passing a value from JS to PHP isn't possible on the same page, there has to be some sort of POST via a form for example? – Pebble Mar 08 '17 at 17:50
  • @Pebble: You pass the value from JavaScript to PHP *using* POST (or GET or web sockets), yes, since of course the one is running on the client browser and the other is running on the web server. (Assuming you're talking about browser-hosted JavaScript.) – T.J. Crowder Mar 08 '17 at 17:58

0 Answers0