from php array to javascript (beginner)

elazard

so basically I'm looking into javascript and jquery because it looks like I could use it in my projects.

Today I tried to get a bit more into it : I have a database filed with articles id, Ean codes, brands and references. What I would like to do is : you type the article number in one input and it fills the 3 others.

I looked around a bit and frankensteined my very first own code. and it works for the most of it. What I can't figure out is how to fill const values with the data from the array I get from my database instead of the arrays I set up myself. I tried several things but yeah I lack the basics so I guess it will be trivial for you guys

Thanks in advance for your help!

    <?php

$sql = "SELECT * FROM prescreen_articles";
$result = mysqli_query($conn, $sql);

while ($articles = mysqli_fetch_array($result)){

    $temp_articles[] = array(
        "narticle" => $articles['article_number'],
        "ean" => $articles['EAN'],
        "brand" => $articles['brand'],
        "ref" => $articles['ref']
    ); 
}

?>



<input name="artible" id="article" type="text">
<input name="ean" id="ean" type="text" disabled>
<input name="brand" id="brand" type="text" disabled>
<input name="ref" id="ref" type="text" disabled>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script>
    jQuery(document).ready(function() {

        const $main = $('#article');
        const $ean = $('#ean');
        const $brand = $('#brand');
        const $ref = $('#ref');

        var id;
        var array_articles = <?php echo json_encode($temp_article); ?>;

        const values = {
          article: ['2222222', '9999999', '1111111'],
          ean: ['1', '2', '3'],
          brand: ['samsung', 'apple', 'huawei'],
          ref: ['S10', 'xr', 'P30'],

        };

        $main.on('keyup', function () {

            if($main.is(':empty') || $main.lenght < 7){
                ean.value = '';
                brand.value = '';
                ref.value = '';
            }

            if (jQuery.inArray(this.value , values.article) !== -1) {
                id = jQuery.inArray(this.value ,values.article);
                ean.value = values.ean[id];
                brand.value = values.brand[id];
                ref.value = values.ref[id];
            }
        });
    });     
  </script>
Ahmed

[PHP] array -> JSON

json_encode(your_array);


[JS] JSON -> JS Object

JSON.parse(your_json);

Hope that will work for you. If you have further problem, please let me know in the comment

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related