Jump to content

Call PHP Function


doc1355

Recommended Posts

I have a php page tool.php that has a function named "create_event". 

I want to make a button in a different page (dashboard.php), that when I click on it, it runs the "create_event" function from tool.php and shows the output from the function on dashboard.php page. 

I'm totally new to ajax and jquery and not sure how to do this. I did google this but not much luck. My site is build with WordPress and this is part of custom plugin that I'm making. 

Thank you in advance.

Link to comment
Share on other sites

The basics of AJAX are simple. You send a request to be processed on the server and it sends back a response. When responding to an AJAX request, anything output by the server program (stuff that would normally go to the browser screen) is sent back as the response.

image.png.56a5486eb3fd093d5148d4c8274d703d.png

Here's a simple example (using data from the DB in my tutorial) which accepts a teacher_id, sends it in a request, and recieves back the data for that teacher thne displays it.

<?php
require 'db_inc.php';
$db = pdoConnect('jointute');  // my cuton connection function - use your connection code

//******************** PROCESS AJAX REQUESTS *********************
//
//
if (isset($_GET['ajax'])) {
    if ($_GET['ajax']=='teacher') {
        exit(json_encode(getTeacher($db, $_GET['tid'])));
    }
    
    else {
        exit('INVALID');
    }
} 

//
//  Functions
//
function getTeacher($db, $id) {
    $res = $db->prepare("SELECT t.fname
                              , t.lname
                              , d.deptname as dept
                         FROM teacher t
                              JOIN department d USING (dept_id)
                         WHERE teacherid = ?
                        ");
    $res->execute([ $_GET['tid'] ]);
    $row = $res->fetch();
    if ($row) {
        return $row;
    }
    else return ['fname'=>'NOT FOUND', 'lname'=>'', 'dept'=>''] ;
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Example</title>
<meta charset='utf-8'>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type='text/javascript'>
    $().ready( function() {
        
        $("#find").click( function() {
            var tid = $("#tid").val()
            $.get(
                "",                                                // specify processing file on server (in this case it's same file)
                {"ajax":"teacher", "tid":tid},                     // data to send in request
                function(resp) {                                   // handle the response
                    $.each(resp, function(k,v) {
                        $("#"+k).val(v)
                    })
                },                                                  
                "JSON"                                              // response type
            )
        })
    })
</script>
<style type='text/css'>
    body {
        font-family: calibri, sans-serif;
        font-size: 12pt;
    }
    div {
        margin: 16px;
        padding: 8px;
        border: 1px solid gray;
    }
    label {
        display: inline-block;
        background-color: black;
        color: white;
        width: 120px;
        padding: 8px;
        margin: 1px 8px;;
    }
</style>
</head>
<body>
    <div>
        <label>Teacher ID (1-20)</label> 
        <input type='number' id='tid' value='0'>
        <button id='find'>Find</button>
    </div>
    <div>
        <label>First name</label><input type='text' id='fname' value='' readonly><br>
        <label>Last name</label><input type='text' id='lname' value='' readonly><br>
        <label>Department</label><input type='text' id='dept' value='' readonly>
    </div>
</body>
</html>

 

Edited by Barand
  • Thanks 1
Link to comment
Share on other sites

For completeness, I should state that an alternative method to the above is to use fetch()

Here is an alternative script section using fetch instead of $.get()

<script type='text/javascript'>

   $().ready( function() {
        
        $("#find").click( function() {
            var tid = $("#tid").val()
            
            fetch('?ajax=teacher&tid='+tid)
            .then(response => response.json())
            .then(data => handleOutput(data))
        })
    })
    
    function handleOutput(resp)
    {
        $.each(resp, function(k,v) {
                        $("#"+k).val(v)
                    })
    }
</script>

 

Edited by Barand
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.