从Javascript文件中调用PHP代码

时间:2014-06-26 19:03:07

标签: javascript php jquery html

我是 JS / PHP 新手,我不知道如何解决以下问题;

首先,代码

PHP 代码:

class User {

   private $mysqli;

   function __construct($connection) {
       $this -> mysqli = $connection;
   }

   public function updateUsername($oldusername, $newusername) {
       $statement = $this -> mysqli -> prepare('UPDATE user SET username = ? WHERE username = ?');
       $statement -> bind_param('si', $oldusername, $newusername);
       $result = $statement -> execute();

       if (!$this -> mysqli -> commit()) {
           return false; // maybe beacuse an username already exists..
       } return true;
}

Javascript 代码:

var oldusername;

$(document).on("click", "span.editusername", function () {
    var txt = $(".username").text();
    oldusername = txt;
    $(".username").replaceWith("<input class='username' style=\"border: 1px solid rgb(231, 231, 231); padding: 3px 5px; color: rgb(81, 81, 81); \"/>");
    $(".username").val(txt);

    $(this).text('editing..');
    $(this).css('text-decoration', 'none');

    $(".username").focusToEnd();
});

$(document).on("blur", "input.username", function () {
    var newuser = $(this).val();
    $(this).replaceWith("<label class='username'></label>");
    $(".username").text(newuser);

    // Here I want to call the PHP updateUsername function with the two arguments: oldusername, newuser: booleanResult = updateUsername(oldusername, newusername);

    $('.editusername').text('edit');
    $('.editusername').css('text-decoration', 'underline');
});

HTML 代码的草稿:

 <h1 id="user-displayname"><label class="username"><?php
            if($_SESSION["s_username"]) { echo $_SESSION["s_username"]; } ?></label></h1>
 <div class="sub-header-links">
    <span class="editusername">edit</span>
    <a><?php
            if($_SESSION["s_user_id"]) {
                ?>
                    <a href="logout.php" title="Logout">logout
            <?php } ?></a>
 </div>

如下图所示,如果我点击“编辑”标签,则用户名标签将成为可编辑的文本区域。更改之后,标签也会通过PHP函数(updateUsername)更新,db也会更新。

enter image description here

enter image description here

textarea和label周围的逻辑由JS代码处理,而对DB的调用应该由PHP代码执行,但我不知道如何从Javascript文件调用PHP函数,我不知道甚至知道这是最好的方法,还是至少是一种明智的方法。

谢谢

2 个答案:

答案 0 :(得分:1)

看看http://api.jquery.com/jquery.ajax/ 完全按照你的要求制作AJAX - 允许客户端运行服务器端代码。

另外,你的updateUsername方法绑定了一个字符串和一个整数,但看起来你传递了两个字符串。

$statement -> bind_param('si', $oldusername, $newusername);

应该是......

$statement -> bind_param('ss', $oldusername, $newusername);

答案 1 :(得分:0)

我已经找到了我的问题的答案,所以感谢所有有关使用AJAX的建议的人。我不知道我的解决方案是否是最佳方法,但我已经成功测试过了!

像往常一样,首先是代码:

PHP 代码(db.php文件):

$func = $_POST['func'];
if ($func) {  
    switch ($func) {
        case 'updateUsername':              
            $username = $_POST['username'];

            $isValid = $dbuser -> updateUsername($username, $_SESSION['s_user_id']);
            if ($isValid) {
                session_regenerate_id();
                $_SESSION['s_username'] = $username;
                session_write_close();
            }
            break;
        default:
            //function not found, error or something
            break;
    }
}

HTML 代码的草稿:

$(document).on("blur", "input.username", function () {
    var txt = $(this).val();
    $(this).replaceWith("<label class='username'></label>");
    $(".username").text(txt);

    // Call to the db..
    $.ajax({
        url: "db.php",
        type: "POST",
        data: { func: 'updateUsername', username: txt },
        cache: false,
        success: function (response) {
            $('.editusername').text('edit');
            $('.editusername').css('text-decoration', 'underline');
        },
        error: function() {
            alert('error!');
        }
    });
});

db调用 PHP 函数:

  public function updateUsername($username, $userid) {
    $statement = $this -> mysqli -> prepare('UPDATE user SET username = ? WHERE user_id = ?');
    $statement -> bind_param('si', $username, $userid);
    $statement -> execute();
    if (!$this -> mysqli -> commit()) {
        return false; // maybe beacuse an username already exists..
    } return true;
  }