Run PHP function on html button click

前端 未结 6 1045
渐次进展
渐次进展 2021-01-31 00:43

I need to run some PHP function when a button is clicked. I know this is not supposed to be php\'s use, rather js should do it, but what my functions are doing in gathering data

6条回答
  •  悲&欢浪女
    2021-01-31 01:29

    A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

    You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

    Depending on the data sent in the POST/GET you can have a switch statement running a different function.

    Specifying Function via GET

    You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.

    So on PHP side you can have something like this:

    
    

    and you can make the simplest get request using the address bar as testing:

    http://127.0.0.1/test.php?runFunction=helloffffdffffd
    

    results in:

    Function not found or wrong input
    
    http://127.0.0.1/test.php?runFunction=hello
    

    results in:

    hello
    

    Sending the Data

    GET Request via JQuery

    See: http://api.jquery.com/jQuery.get/

    $.get("test.cgi", { name: "John"})
    .done(function(data) {
      alert("Data Loaded: " + data);
    });
    

    POST Request via JQuery

    See: http://api.jquery.com/jQuery.post/

    $.post("test.php", { name: "John"} );
    

    GET Request via Javascript location

    See: http://www.javascripter.net/faq/buttonli.htm

    
    

    Reading the Data (PHP)

    See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

    Useful Links

    http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

提交回复
热议问题