0

Im trying to do something experimental. i would want to search product in MySQL database by product name and retrieve price in 'price input', sell price in 'sellprice input'. example picture

Everything is ok, except retrieve fetch.php array as javascript variable to get price and sellprice input value. i tried to use json_encode in php file to get php array in javascript, still dosen't working. I don't have much knowledge about javascript. Probably I didn't coded properly thats why javascript not getting php array. Any kind of help would be appreciated. Thanks :)

index.htm

<html>
        <head>
            <script src="js/jquery.js"></script>
        </head>
        <body>
            <div class="productdetail">
                <table class="productdetail">
                    <th>Product</th>
                    <th>Price</th>
                    <th>Sell price</th>
                    <tr>
                        <td><input class='product' type='text' name='product' /></td>
                        <td><input class='price' type='text' name='price' /></td>
                        <td><input type='text' class='sellprice' name=''/></td>
                    </tr>
                </table>
    <div id="result"></div>
        </body>

    </html>
    <script>
    $(function(){

            $('.productdetail').delegate('.product,.price,.sellprice','keyup',function(){
                var tr = $(this).parent().parent().parent();
                var product = tr.find('.product').val();
                if(product != '')  
               {  
                    $.ajax({  
                         url:"fetch.php",  
                         method:"post",  
                         data:{product:product},  
                         dataType:"text",  
                         success:function(data)  
                         {  
                    console.log(price);
                    var price = jQuery.parseJSON(price);

                    console.log(sellprice);
                    var sellprice = jQuery.parseJSON(sellprice);

                    //var price = "test price";
                    //var sellprice = "test sell price";

                     tr.find('.price').val(price);
                     tr.find('.sellprice').val(sellprice);

                    $('#result').html(data);  
                         }  
                    });  
               } 

            }); 
        });     
    </script>

fetch.php

<?php

$product = strtolower($_POST["product"]);

require_once ('db.php');
$sql = "SELECT * FROM tbproduct WHERE product LIKE '$product'";

$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {        {


            $array = array(
                'price' => $row["price"],
                'sellprice' => $row["sellprice"],
                );
                echo json_encode($array);
        }

    }
} else {
    echo 'Data Not Found';
}

?>
5
  • if you use dataType: 'json' on the ajax, you don't need to use JSON.Parse Commented Dec 11, 2016 at 17:57
  • 1
    Part of the issue is that you are echoing multple json_encode results. Properly formatted json will require you to do that only once at the end. Json is expected to have a single parent node at the very top, be it an array or object containing all the children. Also as a side note, your sql is not using prepared statements and is taking the input directly from the request, which opens you up to sql injection attacks. That's bad, m'kay! Commented Dec 11, 2016 at 18:00
  • Unless I'm misreading that and the product is unique in the db, in which case it maybe should be an if rather than a while conditional. And your success method for your ajax is doing nothing with the returned data passed into it, which would be the result. If it is not parsed automatically, then you can parse it to get what you need. Just console.log(data) to see what you got there. Commented Dec 11, 2016 at 18:07
  • can i have example please? @Phiter Fernandes Commented Dec 11, 2016 at 23:58
  • is it possible to show me an example @Taplar Commented Dec 11, 2016 at 23:59

2 Answers 2

1

i got it. Working now :)

$(function(){

        $('.productdetail').delegate('.product,.price,.sellprice','keyup',function(){
            var tr = $(this).parent().parent().parent();
            var product = tr.find('.product').val();
            if(product != '')  
           {  
                $.ajax({  
                     url:"fetch.php",  
                     method:"post",  
                     data:{product:product},  
                     //dataType:"json",  
                     success:function(data)  
                     {  

                    var getarray = jQuery.parseJSON(data);
                    var price = getarray.price;
                    var sellprice = getarray.sellprice;

                 tr.find('.price').val(price);
                 tr.find('.sellprice').val(sellprice);

                //$('#result').html(data);  
                }

                });  
           } 

        }); 
    });
Sign up to request clarification or add additional context in comments.

Comments

0

Try to replace the price argument in ajax with data eg

$.ajax({  
                         url:"fetch.php",  
                         method:"post",  
                         data:{product:product},  
                         dataType:"text",  
                         success:function(data)  
                         {  
                    console.log(data);
                    var price = jQuery.parseJSON(data);
Then console the data I think that the two arrays that you want is the data[0] and data[1]

2 Comments

Can you show me the console output?With data then data[0] and the data[1]
"""$array = array( 'price' => $row["price"], 'sellprice' => $row["sellprice"], ); echo json_encode($array);""" output: {"price":"900","sellprice":"1000"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.