php - Get/fetch data from database without refresh the page -
hi i'd please. i'm learning ajax , json don't have experience on it.
i have followed tutorial in order fetch data without page refresh, i'm having concerns on it.
the script works fine, problem found if hit refresh takes lot of time (about 5-10 seconds)to load content again. in firebug can see in console continiously binding it's sending requests time. here's code html
<div class="ajax_results"> <ul id="results"></ul> </div>
php script
$query = "select `img_id`, `image_name`, `title` `images` order `img_id` desc limit 5 "; $run = mysqli_query($connection, $query) or die(mysqli_error($connection)); $json = array(); while ($row = mysqli_fetch_array($run, mysqli_assoc)) { array_push($json, array('image_name' => $row['image_name'], 'title' => $row['title'])); } echo json_encode(array("json" => $json));
and js
$(document).ready(function() { refresh(); }); function refresh() { settimeout(function() { update_content(); refresh(); }, 200); } function update_content() { $.getjson("fetch_data.php", function(data) { $("ul#results").empty(); $.each(data.json, function() { $("ul#results").append("<li><img src=\"img/uploads/"+this['image_name']+"\" /><br />"+this['title']+"</li>"); }); }); }
is problem?? can improve somehow code?? appreciated
to give feedback. if $.getjson directly placed in $(document).ready(function() content loads more quickly, if updates occured eg in title won't show without refreshing page. want achieve load content , if changes happened show them without refreshing page.
here's approach issue
$(function() { update_content(); }); function update_content() { $.getjson("fetch_data.php", function(data) { $("ul#results").empty(); $.each(data.json, function() { $("ul#results").append("<li><img src=\"img/uploads/"+this['image_name']+"\" /><br />"+this['title']+"</li>"); }); settimeout(function(){ update_content(); }, 1000); }); }
here i've moved settimeout call update_content() function, , increased timeout give browser bit more breathing room, wouldn't call every second it's example, i'd go 10 seconds or longer.
if don't want fire off repeatedly remove entire settimeout block.
$(function() { update_content(); }); function update_content() { $.getjson("fetch_data.php", function(data) { $("ul#results").empty(); $.each(data.json, function() { $("ul#results").append("<li><img src=\"img/uploads/"+this['image_name']+"\" /><br />"+this['title']+"</li>"); }); }); }
Comments
Post a Comment