如何使用 AJAX 在页面中调用 PHP 函数

How to call a PHP function within a page using AJAX

本文关键字:调用 PHP 函数 何使用 AJAX      更新时间:2023-09-26

我写了一个php函数,如果PHP页面独立调用它,它可以完美地完成工作。 但我想将这个函数集成到程序中,并希望在单击按钮时调用它。我的PHP函数是

function adddata($mobile){
    // outside of this function, another database is already selected to perform different
    //tasks with program's original database, These constants are defined only within this
    //this function to communicate another database present at the same host
    define ("HOSTNAME","localhost");
    define ("USERNAME","root");
    define ("PWD","");
    define ("DBNAME","budgetbot");
    // link to mysql server
    if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
        die ("Cannot connect to mysql server" . mysql_error() );
    }
    // selecting the database
    if (!mysql_select_db(DBNAME)) {
        die ("Cannot select database" . mysql_error() );
    }
    //inserting phone number into database
    $query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
    if(!mysql_query($query)){
       die( mysql_error() );
    }
    // wait for 2 seconds after adding the data into the database
    sleep(2);
    $query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
    $result = mysql_query($query) or die( mysql_error() );
    // if more than one records found for the same phone number
    if(mysql_num_rows($result) > 1){
        while($row = mysql_fetch_assoc($result)){
            $data[] = $row['response'];
        }
        // return an array of names for the same phone numbers
        return $data;
    }else{
        // if only one record found
        $row = mysql_fetch_assoc($result);
        $response = $row['response'];
        return $response;
    }
    // end of function
}

HTML 代码编写为

<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
    <input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
    <button id="verify" class="btn btn-primary">Verify</button>
    <button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>

我想调用这个函数并通过 ajax/jquery 将返回值分配给 javascript 变量。我这样做的代码是...

<script type="text/javascript" language="javascript">
    $('#verify').click(function(){
        var value = $( ".serial_item" ).val();
        //I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work            
        $.ajax({
            url  : "add_data.php&f="+value,
            type : "GET"
            success: function(data){
                document.getElementById("cname").innerHTML = data;
            }
        });  
    });
</script>

我想分享一下,上面的javascript代码被放置在documnet.ready(){}之外范围任何帮助将不胜感激。谢谢

因为您的<button>元素没有type="button"属性,所以它们应该使用正常的 POST 请求提交表单。

您应该在按钮上使用type="button"属性,或者使用event.preventDefault()阻止默认表单提交:

$('#verify').click(function(event){
    event.preventDefault();
    var value = $( ".serial_item" ).val();           
    $.ajax({
        // there's a typo, should use '?' instead of '&':
        url  : "add_data.php?f="+value,
        type : "GET",
        success: function(data){
            $("#cname").html(data);
        }
    });  
});

[编辑] 然后在add_data.php中(如果您在同一页面调用 AJAX,请将此代码放在顶部,以便在此之前不会呈现 HTML):

if(isset($_GET['f'])){
    // call your function:
    $result = adddata(trim($_GET['f']));
    // if returned value is an array, implode it:
    echo is_array($result) ? implode(', ', $result) : $result;
    // if this is on the same page use exit instead of echo:
    // exit(is_array($result) ? implode(', ', $result) : $result);
}

确保对 $query 上的值进行转义。