Reputation: 68
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';
}
?>
Upvotes: 0
Views: 10801
Reputation: 68
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);
}
});
}
});
});
Upvotes: 1
Reputation: 740
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);
Upvotes: 0