PHP button onclick

Last Updated On Tuesday 5th Oct 2021

php button onclick

You can achieve this by using Ajax.While

  • Button clicks are clientSide Rendering * PHP executed in server side Rendering
	$('.button').click(function() {
  $.ajax({
    type: "POST",
    url: "name.php",
    data: { id : 11 , title : "The Title of the Post with the id 11" }
  }).done(function( msg ) {
    alert( "Data Saved: " + msg );
  });
});
	

With Your PHP File

	<?php
    function abc($name){
        // Your code here
    }
?>
	

php button function

  • Make Sure also use JS preventDefault to prevent form from submitting.
	<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
	
	$(document).ready(function(){
    $('.button').click(function(){
        var clickBtnValue = $(this).val();
        var ajaxurl = 'file.php',
        data =  { 'action': clickBtnValue };
        $.post(ajaxurl, data, function (response) {
            alert("Done");
        });
    });
});
	
	<?php
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'insert':
                insert();
                break;
            case 'select':
                select();
                break;
        }
    }

    function select() {
        echo "Select Func";
        exit;
    }

    function insert() {
        echo "Insert Func";
        exit;
    }
?>