0

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);
?>
2
Contributors
2
Replies
15
Views
5 Years
Discussion Span
Last Post by cip6791
0

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. :)

0

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. :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.