【问题标题】:Compare user value to database and show result through ajax jquery将用户值与数据库进行比较并通过 ajax jquery 显示结果
【发布时间】:2018-05-09 17:58:03
【问题描述】:

伙计们正在从事我的第一个现场项目,我被困在一个点上,我需要 ajax jquery 方面的帮助。我可以用 PHP 做到这一点,但我想用 ajax 做到这一点。

如果用户在这里输入产品代码,所以我想将此产品代码值比较到我的数据库中,并以我的其他形式显示产品名称,在用户输入值后将打开:

在第一个字段中我想要产品名称:

在我的表格中,您可以看到产品代码和产品名称:

ok so here is my html code in last option when user enter product code

Here is jquery i am sending user data to 8transectiondata.php to compare

And this is php file and i want $data['product_name']; to show

【问题讨论】:

  • 请在此处发布您的代码。我们需要看看你在这方面的尝试
  • @Akintunde - 我没有,因为我可以读懂 OP 的想法。
  • @Zuber - 虽然我很欣赏这种尝试,但在编码图片时不值一千字。我们需要查看您拥有的 html,以及您为此尝试编写的任何代码。
  • 我看到两个潜在的错误。 1. Transection 拼写错误(应该是Transaction)。 2. Ned Stark从不从 Cercei 购买任何东西....

标签: php jquery ajax database


【解决方案1】:

我知道你想做什么,但如果没有具体的代码,我能做的最好的就是给你一个笼统的答案。

当用户填写字段时,您希望将该字段发布到服务器,查找产品并返回一些内容。

基本内容将如下所示。

$(document).ready( function(){

     //rolling timeout
     var timeout;

     $('#field').on('keyup', function(e){

        if(timeout) clearTimeout(timeout);

          timeout = setTimeout( function(){
                 var data = {
                      "field" : $('#field').val()
                 };

                 $.post( '{url}', data, function(response){

                        if(response.debug) console.log(response.debug);

                        if(response.success){
                             //open other form
                             $('{otherFormProductField}').val(response.product);
                        }

                  }); //end post
           },450); //end timeout
     });//end onKeyup
}); //end onReady

然后在 PHP 中,您必须处理请求。从$_POST 数组中拉出field,在数据库中查找。然后构建一个响应数组并将其作为 JSON 发送回客户端。我喜欢在这样的结构中构建响应。

 {
    success : "message",  //or error : "message"
    debug : "",
    item : ""
 }

然后在 PHP 中我会这样做。

  ob_start();

     ..code..

  $response['debug'] = ob_get_clean();

  header("Content-type:application/json");
  echo json_encode($response);

这样,您在开发时仍然可以打印出调试信息(在输出缓冲区调用中),而不必担心它会弄乱 Json 或标头调用。

-note- 使用超时,您在每次按键时重置(滚动超时)。它所做的是在每次释放键时重置先前的超时。这样,它仅在用户退出键入时才发送请求(而不是在每次按键时发送请求)。我发现450 毫秒是最合适的值。不会太长也不会太短。基本上,一旦他们停止输入450ms,它就会触发$.post

【讨论】:

    【解决方案2】:

    这是一个通用的答案。

    JS 文件:

    $(document).ready(function () {
    
        $('#myButtonId').on('click', function () {
    
            var code = $('#myCodeInputId').val();
    
            if (code !== '') { // checking if input is not empty
    
                $.ajax({
                    url: './my/php/file.php', // php file that communicate with your DB
                    method: 'GET', // it could be 'POST' too
                    data: {code: code},
                    // code that will be used to find your product name
                    // you can call it in your php file by "$_GET['code']" if you specified GET method
                    dataType: 'json' // it could be 'text' too in this case
                })
                    .done(function (response) { // on success
                        $('#myProductNameInput').val(response.product_name);
                    })
                    .fail(function (response) { // on error
                        // Handle error
                    });
    
            }
        });
    });
    

    PHP 文件:

    // I assumed you use pdo method to communicate with your DB
    
    try {
        $dbh = new PDO('mysql:dbname=myDbName;host=myHost;charset=utf8', 'myLogin', 'myPassword');
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e) {
        exit('ERROR: ' . $e->getMessage());
    }
    
    $sql = "SELECT `product_name` FROM `products` WHERE `product_code` = :code";
    
    $result = $dbh->prepare($sql);
    $result->bindValue('code', $_GET['code'], PDO::PARAM_INT);
    $result->execute();
    
    if($result->rowCount()) { // if you got a row from your DB
        $row = $result->fetchObject();
        echo json_encode($row, JSON_UNESCAPED_UNICODE); // as we use json method in ajax you've got to output your data this way
        // if we use text method in ajax, we simply echo $row
    }
    else {
        // handle no result case
    }
    

    【讨论】:

    • 哦.. 我需要使用 $ajax() ;功能
    • 是的,当然。确保使用按钮来验证产品代码。如果您不想这样做,请阅读 ArtisticPhoenix 解决方案。
    • 好的,谢谢,我一直在使用 load() 函数。我编辑了我的问题,你可以看到我的代码
    猜你喜欢
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多