5

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

Here is my form:

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

PHP to be run:

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

How would this be done using javascript?

samyb8
  • 2,560
  • 10
  • 40
  • 68
  • 3
    1. you want to hear about ajax; 2. you want to hear about not nesting `if` blocks. – moonwave99 Apr 04 '13 at 22:06
  • 2
    @moonwave99 What's the problem with nested if blocks? – XCS Apr 04 '13 at 22:09
  • @Cristy they are smell for using boolean operators / splitting huge methods in reusable submethods / going for convention over configuration, and so. Sometimes they are needed, but this is the case where they are clearly not. – moonwave99 Apr 04 '13 at 22:12

4 Answers4

7

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

In the event handler, you assemble a URL and "get" it. For example:

<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>
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
2

Use jQuery AJAX. When it's complete, refresh your page as needed.

Peter Rankin
  • 713
  • 1
  • 6
  • 29
2

You can use Jquery to do an AJAX post you your PHP script, and then use JS to change the contents of the calling page.

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

d g
  • 1,594
  • 13
  • 13
1

It's simple with jQuery. You just have to use the right tag. If you use an "a" tag the page will refresh.

<button id="MyButton">Click Me!</button>

<script>
  $("#MyButton").click( function(){
    $.post("somefile.php");
  });
</script>
Matthew
  • 131
  • 1
  • 3