Search code examples
phpajaxfunctionbuttonrefresh

Click on the button to run the php function (without refreshing the page)


I want to make a and b buttons to execute a function without refreshing the page.

The problem is that when I call this function in index.php or another page, the function works as soon as the page is opened. but the page I want to do should have a button and the function should work when I click the button.

How can I do this?

function insta_login() {

    require __DIR__ . '/vendor/autoload.php';

    \InstagramAPI\Instagram::$allowDangerousWebUsageAtMyOwnRisk = true;

    $username = 'xxxxx';
    $password = 'xxxxx';

    $ig = new \InstagramAPI\Instagram();

    try {
        $ig->login($username, $password);
    } catch (\Exception $e){
        echo $e->getMessage();
    }
}

Solution

  • PHP is the hypertext preprocessor, that means it will process the file, execute PHP scripts and send processed response to the client. So the plain PHP code that is not part of any function/class etc. will be always executed even before the page loads. The best option would be to declare the PHP function in a separate file. Then assign a click handler to your button and make it send Ajax request to the PHP. If you are using JQuery, it can be done easily with $.ajax()