简体   繁体   中英

Send php request onclick via ajax

I know this question have been asked alot but none of the answer are related to my case ,I have a button ,onclick it should call a javascript function send it a php variable,and ajax would call a php file via post and send that vriable and the php file updates my table

so here is the onclick event first

<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>

it should send a variable called $id to the javascript function

<script type="text/javascript">
    function incrementclicks(id) {
        $.ajax({
            url: "increment.php",
            data: "id=" + id,
            type: "POST"
        });
    }
</script>

and the php file increment.php (I'm 100% sure it connects to the server just fine )

<?php
     require_once 'dbconnect.php';
     $db_handle = new DBController();
     $id=$_POST["id"];
     $q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
     $result = mysql_query($q);
?>

it doesn't increment, I don't understand what did i do wrong here

First of all you can debug your code on the php by doing

echo $id;
exit();

My quess is that your are missing something there..

Use this method of ajax to check the issue.And if error found check in console for the issue

$.ajax({
                url: "increment.php",
                type: "post", //send it through post method
                data: {
                    id:id
                },
                success: function (response) {
                    alert("success");
                },
                error: function (xhr) {
                    //Do Something to handle error
                    alert("some error found");
                }
            });

NB:Try to add type="button" to your button for not to reload

<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>

I just want to answer this if anyone have future problems like this

The problem is I forgot to add script src at the beginning

  <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>

after adding this my code worked just fine :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM