posting data with JQuery on click

BR
BR used Ask the Experts™
on
Dear Experts,

I use below function to post the data, it works perfectly fine.

however, it posts the data as soon as the page is ready, but I want to post the data if my button is clicked.

how can I do that?

thank you

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
       $.post("print.php",
        {
          bayikodu: "buraya",
          tutanak: "3"
        });        
});
</script>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Director of Technology Development, IPM
Commented:
Take your post out of the document ready function, and put it into the onclick handler for the button. Here's an example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript">

function postData() {
       $.post("print.php",
        {
          bayikodu: "buraya",
          tutanak: "3"
        });        
}
</script>

 <body >
<input id='btn' type='button' value='Click Me!'>
 </body>

<script language="javascript">
$("#btn").click(function(){ postData(); });
</script>

Open in new window

Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018
Commented:
First of all, put your post logic inside a function so you can reuse it as you want.

Then you need to attach a click event to your button and attach the postData() method you want to trigger to it like :

HTML :

<button id='my-btn' type='button'>Post the data</button>

Open in new window


JS :

<script>
$(document).ready(function(){
       $("#my-btn").on('click', postData);
});

function postData() {
     $.post("print.php", {
            bayikodu: "buraya",
            tutanak: "3"
     });        
}
</script>

Open in new window

BRDigital Marketing

Author

Commented:
thank you both.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial