Run the PHP code after clicking the button, but without refreshing the page

I have a form in HTML to apply a Discount Coupon to the current shopping cart. I would like the user to just press APPLY (after entering the coupon code) and then not refresh the page to run some PHP code, so it calculates the corresponding discount.

Here is my form:

<form action=""> <input type="text" name="couponCode"> <input type="submit" value="Apply"> </form> 

PHP to run:

 if (isset($_REQUEST['couponCode']) && $_REQUEST['couponCode']!='') { $couponCode = $_REQUEST['couponCode']; if ($couponCode == "TEST1") { $discount=0.2; } } 

How to do this using javascript?

+4
source share
4 answers

You need to use the onsubmit event of the form or the onclick event of the button.

In the event handler, you collect the URL and "get" it. For instance:

 <script type="text/JavaScript"> function submitCouponCode() { var textbox = document.getElementById("couponCode"); var url = "https://www.example.com/script.php?couponCode=" + encodeURIComponent(textbox.value); // get the URL http = new XMLHttpRequest(); http.open("GET", url, true); http.send(null); // prevent form from submitting return false; } </script> <form action="" onsubmit="return submitCouponCode();"> <input type="text" id="couponCode"> <input type="submit" value="Apply"> </form> 
+6
source

Use jQuery AJAX . When finished, refresh your page as needed.

+1
source

You can use jQuery to create AJAX after your PHP script, and then use JS to modify the contents of the calling page.

http://api.jquery.com/jQuery.post/

+1
source

It is simple with jQuery. You just need to use the correct tag. If you use the tag "a", the page will refresh.

 <button id="MyButton">Click Me!</button> <script> $("#MyButton").click( function(){ $.post("somefile.php"); }); </script> 
0
source

All Articles