posting data with JQuery on click

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

LVL 1
BRDigital MarketingAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Sam JacobsDirector of Technology Development, IPMCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Zakaria AcharkiAnalyst DeveloperCommented:
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 MarketingAuthor Commented:
thank you both.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.