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);
?>

Dani AI

Generated

A clean way to trigger the request on click is to bind a handler with jQuery (no inline onclick). Give your button an id and attach the event once the DOM is ready. Send a data object (easier to maintain) and handle both success and error states.

<button id="testBtn" type="button">Test</button>
<script>
$(function () {
  $('#testBtn').on('click', function () {
    $.ajax({
      method: 'POST',
      url: 'test.php',
      dataType: 'json',
      data: { name: 'name', location: 'location' }
    })
    .done(function (resp) { alert('Data saved: ' + resp.message); })
    .fail(function (jqXHR, textStatus) { alert('Request failed: ' + textStatus); });
  });
});
</script>

On the PHP side, return JSON and use safer I/O. LOCK_EX prevents concurrent writes; use an absolute path and ensure the file is writable by the web server user.

<?php
header('Content-Type: application/json');
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING) ?? '';
$location = filter_input(INPUT_POST, 'location', FILTER_SANITIZE_STRING) ?? '';
$ok = file_put_contents(__DIR__ . '/test.txt', $name . $location, LOCK_EX);
echo json_encode(['message' => $ok !== false ? 'ok' : 'error']);

See the jQuery docs for $.ajax and event binding with on. PHP references: filter_input and file_put_contents. Note: if the button is inside a form, keep type="button" to avoid unintended form submits.

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.