繁体   English   中英

如何根据其他表单字段自动从数据库中为输入字段设置值。 使用PHP?

[英]How to set the input field with the value automatically from the database on the basis of other form field. using php?

一旦他们以相同的形式输入电子邮件,我将尝试从数据库中自动填写诸如姓名和地址之类的表单字段。 我能够从该数据库中获取该特定电子邮件的值,但是无法成功将该值放入“名称”和“地址”字段中。 以下是代码示例:

Index.php

<div class="form-group">
   <label>Email*</label>
   <input type="text" name="email" required/>
</div>

<div class="form-group">
    <label>Name</label>
    <?php echo $model->Form->textBoxFor('name',['required'=>'required']); ?>
</div>
<div class="form-group">
    <label>Address</label>
    <?php echo $model->Form->textBoxFor('address',['required'=>'required']); ?>
</div>

在同一文件中,我的jQuery部分如下:

$("input[name=email]" ).on( "focusout", function(){
    // Getting the email value
    var curr_email = $(this).val();
    // Making the request & passing the current email to the request.
    $.post( "/subscribe/getDetails", { email: curr_email}, function( data ) {
        // Updating the fields with their values.
        $("input[name='name']").val( data['name'] );
        $("input[name='address']").val( data['address'] );
    });
});

“getDetails”功能是subscribeController.php。 功能如下:

public function getDetails(){
    $email = $_POST['email'];
    $result= [];
    $details = \Model\User::getList(['where'=>"email = '{$email}'"]);
    if($details){
        $result = ['name' => $details[0]->name, 'address' => $details[0]->address];
    } 
}

我成功地在“数据”中获取了详细信息,但无法在其各自的输入字段中设置该值。 我知道我在jQuery部分中错误地写了一些东西,在那里我将值设置为该字段。 感谢帮助。 提前致谢。

从外观上看,您将在控制器中获得结果,但不会将结果发送出去。

尝试这个:

<?php
public function getDetails(){
    $email = $_POST['email'];
    $result= [];
    $details = \Model\User::getList(['where'=>"email = '{$email}'"]);
    if($details){
        $result = ['name' => $details[0]->name, 'address' => $details[0]->address];
        echo json_encode($result);  // this is the part you're missing
    }
}

暂无
暂无

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

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