How to call a PHP function that returns a string using jQuery or Javascript?

Asked

Viewed 109 times

2

I have a PHP file that returns the amount of user registered in a Mysql database. I was wondering if there is a way to put this number inside a div using jQuery or Javascript without having to put PHP inside HTML.

getinfo.php

<?php
function getaccounttotal() {
    try
    {
        $dbh = new PDO('mysql:host=localhost;dbname=database;charset=utf8', '', '');
        $sth = $dbh->prepare("SELECT COUNT(*) FROM `database`.`accouunts`;");
        $sth->execute();
        $result = $sth->fetchColumn();

        // The script will automatically free the result and close the MySQL
        // connection when it exits, but let's just do it anyways
        $dbh = null;

        return $result;
    }
    catch (PDOException $e)
    {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
}
?>

index.html

<!DOCTYPE html>
<html lang="ja" dir="ltr">

<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="css/loginStyle.css">
    <script src="js/lib/jquery-3.4.1.min.js"></script>
</head>

<body>
    <p>Usuários cadastrados<p id="accountnumber"></p></p>

    <script type="text/javascript">
    </script>
</body>

</html>
  • with ajax, then you manipulate the DOM according to the return

1 answer

3


You can use the method .load() jQuery:

$(seletor).load(url);

Where:

  • Selector: element to which the result of the request will be sent.

  • url: page to be requested.

In your case I’d be:

$("#accountnumber").load("getinfo.php");

And in PHP you make a echo of function:

<?
function getaccounttotal(){
   // código
}

echo getaccounttotal(); // envia o retorno da função para o AJAX
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.