0

I am now on a php page that has presented the user with some choices and I have saved the users input in 5 javascript variables:

product_format
product_print
product_paper_weight
product_paper_type
product_quantity

I want to send them to a a calculate.php page that will do the calculation of the price and then include calculate.php on my page and present the user with the price dynamically. I have read send javaScript variable to php variable that I can use:

window.location.href = "calculate.php?name=" + javascriptVariable (and the rest);

And then I could use php get to calculate by querying the database. I also need this to be done continously as soon as the user changes an option I need to recalculate the price and present a new price.

Is this possible? Is there a better approach? Am I thinking right? Should I instead calculate the price by loading the php-sql data into javascript and calculate in javascript instead? Which is quicker and more secure?

The page http://www.reclam.se/trycksaker.php?product_id=1

Community
  • 1
  • 1
Kaki Sami
  • 187
  • 8

2 Answers2

0

This is a perfect application for AJAX. Much easier if you use jQuery, though you can do it in pure Javascript. Essentially, create a Javascript function that takes place when a field is changed (e.g., $('.product').change(function() { }); if you set class="product" on all the relevant input fields) and in that function use $.ajax to post the data to your PHP form.

You can do all the calculations in Javascript. If the data is dependent on database lookups or relatively complex math then AJAX makes more sense. If the calculations are very simple then you can embed the calculations directly in the .change function.

Using window.location.href= will cause a full page load, which does not sound like what you want.

  • All classes are set to "form-control". Can I use that class? I would like to do it using Jquery but where do I start with that? What do I need to read? – Kaki Sami Feb 23 '17 at 16:32
  • The math is complex and I need to get values from database. – Kaki Sami Feb 23 '17 at 16:34
  • Absolutely - any class that is in common with all the relevant fields and NOT in common with too many other fields (because that would result in extra unnecessary AJAX calls) will work. Google "jQuery AJAX tutorial" - W3 Schools comes up top in my search and generally has pretty good information. – manassehkatz-Moving 2 Codidact Feb 23 '17 at 16:35
  • Thanks I will do that! – Kaki Sami Feb 23 '17 at 16:41
0

As we all know this very well that php code runs on server side and javascript on client side. To transfer data between client and server, we need some kind of data transfer protocol and thats where Http comes in. You can send data to php server from client side either by Form or Ajax call with http get or post method.And once data are sent to php server, you can catch those data using php super globals $_GET or $_POST.

ishwor kafley
  • 938
  • 14
  • 32