sinak sinak - 3 years ago 94
jQuery Question

fetch from database in ajax

im my script i want to read from ajax.php and show them and in my ajax.php i want to fetch from database . my problem is fetching from database doesnt work!

echo
'<?php while ($row = mysqli_fetch_array($products)):?>
<div class="item-in-cart clearfix">
<div class="image">
<img src="images/<?php echo $row['id'] ?>" width="124" height="124" alt="cart item" />
</div>
<div class="desc">
<strong>
<a href="product.html">s</a>
</strong>
<span class="light-clr qty">
<a href="#" class="icon-remove-sign" title="Remove Item"></a>
</span>
</div>
<div class="price">
<strong></strong>
</div>
</div>';
<?php endwhile;?>


$(document).ready(function(){
$(".addCart").click(function(){
var id = $(this).val();
$.ajax({
type:'post',
url:'ajax.php',
data :{
id : 'id',
},
success : function (response) {
$('#cart').html(response);
}
});

});
});

Answer Source

On the loop of return of your AJAX, put all the result in one concatenated string inside a variable. then echo that variable serve as return in ajax.

make sure that there is an tags with an ID "cart"

ajax.php

<?php
$return = "";
while($row = mysqli_fetch_assoc($products)):
$id = $row['id'];
$return .= "<div class='item-in-cart clearfix'>
    <div class='image'>
        <img src='images/$id' width='124' height='124' alt='cart item' />
    </div>
    <div class='desc'>
        <strong>
            <a href='product.html'>s</a>
        </strong>
        <span class='light-clr qty'>
            <a href='#' class='icon-remove-sign' title='Remove Item'></a>
        </span>
    </div>
    <div class='price'>
        <strong></strong>
    </div>
</div>";
endwhile;

echo $return;
?>

then the lump of HTML data will be push and insert inside the cart ID tags, but also upon calling the ajax, or before it get insert, empty the cart id first

$('#cart').html('');
$('#cart').html(response);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download