简体   繁体   中英

Passing javascript variables to php

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 aa 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

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 (eg, $('.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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM