2

I am a JS/PHP newbie and I do not know how to unravel the following problem;

First of all, the code

PHP code:

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 code:

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');
});

Draft of HTML code:

 <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>

Like in the following images, if I click on label 'edit', the username label becomes an editable textarea. After the change, the label is updated, and the db too, through a PHP function (updateUsername).

enter image description here

enter image description here

The logic around textarea and label is handled by the JS code, while the call to the DB should be acted by the PHP code, but I do not know how to call the PHP function from the Javascript file, and I do not even know if this is the best approach, or at least a sensible approach.

Thank you

3
  • Check out AJAX - you need to send a network request back to your server to execute that Commented Jun 26, 2014 at 19:03
  • 3
    Props to you for putting a lot of effort into the question, even if the answer is trivial :) Commented Jun 26, 2014 at 19:05
  • did you write the class ? ... smooth ) Commented Jun 26, 2014 at 21:53

2 Answers 2

1

Take a look at http://api.jquery.com/jquery.ajax/ AJAX was made todo exactly what you are asking - allow the client to run server side code.

Also, your updateUsername method is binding a string and an integer, but looks like you are passing in two strings.

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

should be...

$statement -> bind_param('ss', $oldusername, $newusername);
Sign up to request clarification or add additional context in comments.

Comments

0

I have found an answer to my question, so thanks to all of you who had suggestions about the use of AJAX. I do not know if my solution is the best approach, but I have already tested it successfully!

As usual, first the code:

PHP code (db.php file):

$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;
    }
}

A draft of the HTML code:

$(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!');
        }
    });
});

The db call into the PHP function:

  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;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.