简体   繁体   English

使用PHP(Codeigniter)将变量从控制器传递到javascript

[英]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 我在用户名中添加了前缀,但是在将变量传递给javascript并在我的视图中显示时遇到了问题

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 这是我的Ajax JavaScript

$(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. 这将在我的JavaScript中处理,现在将检查注册的用户名是否已存在。 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? 问题:如何将变量$ username传递到我的JavaScript中?

NOTE: I tried this approach, changing echo json_encode("existing"); 注意:我尝试过这种方法,更改echo json_encode(“ existing”); into this echo json_encode($username). 进入此回显json_encode($ username)。 My javascript else if(result === $username)... The message will not work anymore. 我的javascript else if(result === $ username)...该消息将不再起作用。

Hope this will help you : 希望这个能对您有所帮助 :

For the existing status record do like this : 对于existing状态记录,请执行以下操作:

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

For the success status record return like this 对于success状态记录,返回如下所示

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

Your ajax success part should have code like this : 您的ajax success部分应具有以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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