954,561 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Call ajax onclick

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);
?>
cip6791
Newbie Poster
11 posts since Oct 2010
Reputation Points: 10
Solved Threads: 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. :)

PlyrJames791
Newbie Poster
12 posts since Feb 2011
Reputation Points: 15
Solved Threads: 3
 

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

cip6791
Newbie Poster
11 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: