user4558489
user4558489

Reputation:

call php script on click of button through ajax

I have a button, on its click i wish to run ajax that will call php script result and display data under a particular div. however its not working this way and when i checked the console no value is getting passed to ajax.

can anyone plz correct the code

<script>

$(document).ready(function(){
    $('#generate').change(function(){

        var generateid = $('#generate').val();
        console.log($('#generate'))
        if(generateid != 0)
        {

            $.ajax({
                type:'post',
                url:'a_generatecoupon.php',
                data:{id:generateid},
                cache:false,
                success: function(returndata){
                    $('#coupon_detail').html(returndata);
                    console.log(returndata)
                }
            });

        }
    })
})
</script>

<div class="form-group">
    <label class="control-label col-md-3"> Coupon Code</label>
    <div class="col-md-3">
        <div type="submit" class="btn green" id="generate">Generate</div>
    </div>
</div>

<div id="coupon_detail">

</div>

a_generatecoupon.php code

<?php
function getRandomCode(){
    $an = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-)(.:,;";
    $su = strlen($an) - 1;
    return substr($an, rand(0, $su), 1) .
            substr($an, rand(0, $su), 1) .
            substr($an, rand(0, $su), 1) .
            substr($an, rand(0, $su), 1) .
            substr($an, rand(0, $su), 1) .
            substr($an, rand(0, $su), 1);
}

?>  

<label class="control-label col-md-3"> Coupon Code</label>
<div class="col-md-3">
    <?php echo getRandomCode(); ?>
</div>

Upvotes: 2

Views: 1195

Answers (1)

Qaisar Satti
Qaisar Satti

Reputation: 2762

i changed the change to click event now you script is working. add the button too..

<script>

    $(document).ready(function(){
        $('#generate').click(function(){

            var generateid = $('#generate').val();
            console.log($('#generate'))
            if(generateid != 0)
            {

                $.ajax({
                    type:'post',
                    url:'a_generatecoupon.php',
                    data:{id:generateid},
                    cache:false,
                    success: function(returndata){
                        $('#coupon_detail').html(returndata);
                        console.log(returndata)
                    }
                });

            }
        })
    })
    </script>

    <div class="form-group">
        <label class="control-label col-md-3"> Coupon Code</label>
        <div class="col-md-3">
            <input type="submit" class="btn green" value="Generate" id="generate">
        </div>
    </div>

    <div id="coupon_detail">

    </div>

Upvotes: 1

Related Questions