i have a problem about looping throught json output on ajax success. this is my code :
<?php
$product = mysqli_query($con,select * from product LIMIT 3);
while ($dataproduct = mysqli_fetch_assoc($product) {
echo json_encode(array(
"product" => $dataproduct['product']
));
}
?>
$.ajax({
type : "GET",
url : test.php,
dataType : "json",
success : function(data) {
$.each(data, function() {
$.each(this, function(k, v) {
$("ul").html(data.product);
});
});
}
});
<ul>
<li></li>
</ul>
how to make that "ajax success looping . so i can make an output to "ul" element?
what's wrong with my code?
Try following, it should work for you:-
<?php
$product = mysqli_query($con,select * from product LIMIT 3);
$temp = array();
while ($dataproduct = mysqli_fetch_assoc($product) {
$temp[] = $dataproduct['product'];
}
echo json_encode($temp);
?>
$.ajax({
type : "GET",
url : test.php,
dataType : "json",
success : function(data) {
$.each(data, function(k,v) {
$("ul").html(v);
});
});
}
});
<ul>
<li></li>
</ul>
If i'm not totally incorrect, you at first will have to parse the JSON, don't you? Like $.parseJSON(data) and then you may iterate over it.
Also in the outest $.each you do not use key and value, but at least the value will be the one that has further elements as childs.
Why keeping too much processing on end user low power PC. You can generate the output HTML at server side and get the resulted html and put it in your required place in html DOM.
You can change your PHP code to below:
<?php
$html = "";
$product = mysqli_query($con,select * from product LIMIT 3);
while ($dataproduct = mysqli_fetch_assoc($product) {
$html .= '<li>'.$dataproduct['product'].'</li>';
}
echo $html;
?>
Now you can change your JS to below:
$.ajax({
type : "GET",
url : test.php,
dataType : "html",
success : function(data) {
$('ul.product-list').html(data);
}
});
Now your html can be like:
<ul class="product-list">
<!-- Insert Products here -->
</ul>
This code is not tested and is just to give you the idea. Check it at your end and modify it according to your requirements.