Thomas Smyth Thomas Smyth - 28 days ago 17
HTML Question

Showing Javascript variables in a modal

On my website I'm trying to make a modal that informs the user of their username (generated from their forename and surname) and informs the users that they have been added to a moderation que for their account to be approved. I create the account within a php file called with ajax and then use JSON to feedback a integer that informs the javascript if the process was successful and if so what the user's username is. My modal opens fine if the account was created and the information is displayed about the approval process, however I cannot seems to get it to display the section with the username in. Can you try and see where I'm going wrong.

Javascript

var RegisterSuccess = new Array();
var RegisterSuccess = JSON.parse(Feedback);
if (RegisterSuccess[0] == 0){
$('#mdlInfo').html('<p>Your account has been created under the username: "<strong><span id="spnUsername"></span></strong>". You <strong>must</strong> remember this as you will require it to login to your account.</p>');
$('#mdlInfo').html('<p>Your account has also been added to a moderation que. You must wait until a member of staff activates your account!</p>');
$('#spnUsername').html(RegisterSuccess[1]);
$("#mdlRegister").modal("show");


PHP Output code

$Feedback = json_encode(array($RegisterSuccess, $username));

echo $Feedback;

Thanks in advance!

Answer

Why don't you just return a proper json_encoded array from PHP? No need to assign a variable, just do echo json_encode(["success"=>"true","username"=>"$username"]); and in the javascript (no need to assign the RegisterSuccess as array either), just do var returnValue = JSON.parse(Feedback); (you should avoid calling the variable RegisterSuccess - chose a neutral name so you can use it for both success and error without issues. Then just do

$('#mdlInfo').html('<p>Your account has been created under the username: <strong><span id="spnUsername">'+returnValue['username']+'</span></strong>. You <strong>must</strong> remember this as you will require it to login to your account.</p><p>Your account has also been added to a moderation que. You must wait until a member of staff activates your account!</p>');
$("#mdlRegister").modal("show");