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


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