简体   繁体   中英

Pass variable from controller to javascript using PHP(Codeigniter)

I have registration module and I already done so far the validation of all fields(fields are: name, email, username and password),check if the email and username is already existing.

And trying to add a suggestion if the username is already existing. I am done in adding a prefix in the username but having a problem to pass the variable to javascript and display it in my view

This is my Controller

$get_username = clean_data($_POST['username']);
$where = array(
"username"  => $get_username
);

$check_username = $this->Crud_model->count_result('username','users',$where);
if($check_username > 0)
{
    $fetch_username = $this->Crud_model->user_exists('users',$where);

    $last_username = strrev((int)strrev($fetch_username));  // returns last numeric value of username
    if($last_username){
    $count = count($last_username);//counts number of digit
    $str = substr($username, 0, -($count));;// subtract numeric value from last of username
}
$newstr = $last_username+1;

$username= $get_username.$newstr;
echo json_encode("existing");
// echo "var username = ". json_encode($username).";";

}
else
{
    $insert_user = array(
    'first_name'                => clean_data(ucwords($_POST['first_name'])),
    'last_name'                 => clean_data(ucwords($_POST['last_name'])),
    'profile_picture'           => "profile-picture.jpg",
    'username'                  => $get_username,
    'email'                     => $_POST['email'],
    'password'                  => hash_password($_POST['password']),
    'status'                    => 1,
    );

    $this->Crud_model->insert('users',$insert_user);


    echo json_encode("success");
}

this is My javascript with ajax

$(document).ready(function(){
  $("#registration-form").on('submit',function(e){
    $.ajax({
      url: base_url+"formsubmit/new_form_submit",
      type: "POST",
      data: $(this).serialize(),
      success:function(data)
      {
        var result = JSON.parse(data);
        if(result === "success")
        {
          $("h5").html("");
          success_message("#success-message-new-account","Create Successful!");
          window.setTimeout(function(){location.href=base_url},2000);
        }
        else if(result === "existing")
        {
          $("h5").html("");
          success_message("#existing-message-account","You may use!".$username);
          // window.setTimeout(function(){location.href=base_url},2000);
        }
        else{
          $("#first_name_error").html(result.first_name_error);
          $("#last_name_error").html(result.last_name_error);
          $("#username_error").html(result.username_error);
          $("#email_error").html(result.email_error);
          $("#password_error").html(result.password_error);
        }
      },
      error: function(data) {
        alert('error');
      }
    })
    e.preventDefault();
  })
})

This is my My View

<div id="existing-message-account"></div>
<div class="wrap-input100 validate-input">

    <input class="input100" type="text" name="first_name" id="first_name">

    <span class="label-input100">First</span>

</div>

<div class="wrap-input100 validate-input">

    <input class="input100" type="text" name="last_name" id="last_name">

    <span class="label-input100">Last</span>

</div>

After the user fill up the registration form. It will be process in my javascript, now it will be check if the username registered is already existing or not. if it is not then it will be save in my table. If it is existing then it will add a number prefix.

Example

In my table users. I have existing username abcd, if the user register abcd then there would be a message "Username is already taken, you may use abcd1"

Question: How do I pass the variable $username into my javascript?

NOTE: I tried this approach, changing echo json_encode("existing"); into this echo json_encode($username). My javascript else if(result === $username)... The message will not work anymore.

Hope this will help you :

For the existing status record do like this :

$data['username'] = $username;
$data['status'] = 'existing';
echo json_encode($data);
exit;

For the success status record return like this

$data['username'] = $username;
$data['status'] = 'success';
echo json_encode($data);
exit;

Your ajax success part should have code like this :

  var result = JSON.parse(data);
  if(result.status === "success")
  {
    $("h5").html("");
    success_message("#success-message-new-account","Create Successful!");
    window.setTimeout(function(){location.href=base_url},2000);
  }
  else if(result.status === "existing")
  {
    $("h5").html("");
    success_message("#existing-message-account","You may use!" + result.username);
    // window.setTimeout(function(){location.href=base_url},2000);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM