0

I have an HTML script with a JavaScript function and variable inside. I want to pass this function to a .php script to then call the function in the .php script. I already have a HTML form which passes a couple of other values to the .php script, so it will probably be the easiest way of passing it I just don't know how.

The function adds 1 to a variable which is displayed on the HTML page, only problem is that when I call the .php script it loads a new page and when I return to the page with the variable, nothing has happened, I am not sure but I believe this is because the variable isn't saved?

HTML:

<div class="curVariable">
    Nubmer is: $<span id="curVariable"></span>
</div>

<script type="text/javascript"> 
    //var curVariable= document.getElementById('curVariable').value;
    var curVariable= 1;
    document.getElementById("curVariable").innerHTML = curVariable;
    document.getElementByID("curVariable").value = curVariable;

    function addOne() {
        curVariable= curVariable+ 1 ;
        document.getElementById("curVariable").innerHTML = curVariable;
    }

</script>

<form id="payment-form" action="chargeCard.php" method="POST" name="payment-form">
    <input onkeypress="return isNumberKey(event)" type="text" name="amount" id="amount" />
    <input type="image"  src="CusButton1.png" id="customButton" value="pay" alt="button"/>
</form>

<script type="text/javascript">
    function isNumberKey(evt)
    {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
        return true;
    }
</script>

PHP:

<?php
    echo '<script type="text/javascript"> addOne(); </script>';
?>
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
DevLiv
  • 573
  • 7
  • 19

1 Answers1

0

If you want to submit the number, you can do so in a form field and then reconstruct the page. The nature of HTML is stateless, so nothing is saved except the data in your form.

I think what you might want to do is use AJAX to interact with the PHP script without submitting the page. I have not tested the code, but something like;

$(function(){
    $('#customButton').click(function(e){
        $.get('chargeCard.php','currAmt=' + $('#amount').val,processChange);
        e.preventDefault(); //stop form from being submitted
    }); //end click
}); //end ready

function processChange(result) {
    //process the data returned from the call
}

in your chargeCard.php script, you can manipulate the currAmt query string value which was submitted, then return the new code, value, or whatever, and deal with that in the JavaScript processChange function. The (result) argument contains what you returned.

Hamptonite
  • 109
  • 1
  • 1
  • 8