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

时间:2015-03-08 10:27:58

标签: javascript php jquery ajax

我编写了一个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(){}之外 范围 任何帮助将非常感激。 感谢

1 个答案:

答案 0 :(得分:1)

由于您的<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上的值。