xxSithRagexx xxSithRagexx - 10 days ago 4
JSON Question

Function Scope with Javascript Prototyping

I have been practicing the use of prototype trying to make larger projects easier for me to follow. I am focusing on separating processes, however I seem to be running into what I believe to be a scope issue. When sending information to a

page for
I get an error stating that the function
does not exist. The JSON request is waiting for a response to run a function, however the function does not seem to be accessible. Hoping someone can shed some light on where I am going wrong so that I can get back on track with this project. Thanks in advance!

The client side code:

_wolc.prototype.account = {

createAccount: function () {

var subArr = [];

subArr[0] = document.getElementById("newName").value.toString();
subArr[1] = document.getElementById("newPassword_1").value.toString();
subArr[2] = document.getElementById("newPassword_2").value.toString();
subArr[3] = document.getElementById("newEmail").value.toString();

if (subArr[1] === subArr[2]) {

// Pass the values to the server side function checkUser for validation; return to createAccountConfirm()
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {




} else {

console.log("Passwords don't match");



createAccountConfirm: function (response) {




Server code:


include 'connection_settings.php';

$usr = $_GET['un'];
$psw = $_GET['pw'];
$eml = $_GET['em'];
$tms = date ("Y-m-d H:i:s");

$psw = md5($psw);

$con = mysqli_connect($localhost,$username,$password,$database);

// Check connection
if (!$con) {

die('Could not connect: ' . mysqli_error($con));



$sql="INSERT INTO user_accounts (Account_Name, Join_Date, Last_Date,Account_Password,Account_Email)
VALUES ('".$usr."', '".$tms."', '".$tms."','".$psw."','".$eml."')";

if ($con->query($sql) === TRUE) {

echo json_encode("New record created successfully");

} else {

echo json_encode("Error: New record failed to create");





See How to access the correct `this` / context inside a callback? for the detailed explanation, but basically this in a nested (callback) function does not refer to your _wolc.prototype.account object. You need to save a reference to it in order to use it in the callback:

_wolc.prototype.account = {    
  createAccount: function () {
    // [...]

    // save the reference to `this` to use in the callback:
    var self = this;

    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

         // use `self` instead of `this` in the callback: