Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run PHP code after button click but without refreshing page

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?

like image 527
samyb8 Avatar asked Apr 04 '13 22:04

samyb8


People also ask

Can I call PHP function on button click?

Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.

How do I save and run PHP?

Save and open the file in the browser. Go to File > Save As… and save the file as "helloworld2. php", and open it in your browser by using the address: http://localhost/helloworld2.php. The output is the same as before, but this time the text is in bold.


2 Answers

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>
like image 106
Martin Prikryl Avatar answered Nov 03 '22 20:11

Martin Prikryl


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

like image 35
Peter Rankin Avatar answered Nov 03 '22 20:11

Peter Rankin