Hi all,
I'm doing some tests with ajax and php. The below code works when I load the page, but I would like to call it when I click a button. How can that be done?

index.php:

<script type='text/javascript'>
$.ajax({
   type: "POST",
   url: "test.php",
   data: "name=name&location=location",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });
</script>
<button onclick="???;">Test</button>

test.php:

<?php
$name = $_POST['name'];
$location = $_POST['location'];
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $name);
fwrite($fh, $location);
fclose($fh);
?>

Recommended Answers

All 2 Replies

Put the AJAX command inside a function called startAjax() or whatever, and call this function when the page loads. You can then just type startAjax() within the button's onclick attribute. The javascript section should look like this:

<script type='text/javascript'>
    
    //AJAX function
    function startAjax() {
      $.ajax({
        type: "POST",
        url: "test.php",
        data: "name=name&location=location",
        success: function(msg){
          alert( "Data Saved: " + msg );
        }
      });
    }
    
    //Call AJAX:
    $(document).ready(startAjax);

</script>

And the button:

<button onclick="startAjax();">Test</button>

Hope this helps. :)

Thank you. I was doing the same thing but I had the wrong php file. Dumb little mistake. Now I have it working. Thank you for your help. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.