javascript - Ajax jquery fetching -
i wondering how go incorporating ajax php code make content load dynamically.
currently this. first user selects category:
<li><a href='?genre=sport'>sport</a></li>
which in turn triggers part of include.php file:
if(isset($_get['genre'])) { $genre=$_get['genre']; } $result=mysqli_prepare($connection,'select * songs genre=?'); mysqli_stmt_bind_param($result,'s',$genre); mysqli_stmt_execute($result); mysqli_stmt_bind_result($result,$id,$title,$artist);
eventually leading rendering result in sort of html scheme:
while(mysqli_stmt_fetch($result)) { echo $id; echo $title, echo $artist; }
i understand send json data on $.ajax , retrieve , run through mysqli on server. know best recourse data html , how place in sort of repeating structure. cant seem head around it. thanks.
if not use pure ajax, may see xajax. can use following code simulate case;
<?php include './path/to/xajax.inc.php'; $xajax = new xajax(); $xajax->register(xajax_function, 'getgenre'); $xajax->processrequest(); function getgenre($a, $b) { $response = new xajaxresponse(); // db code here $response->assign('result', 'innerhtml', $result); return $response; }
html:
<li><a href='?genre=sport' onclick="getgenre('sport')">sport</a></li> <div id="result"></div>
simply, js , php functions synchronized.
however, suggest use jquery case
edit:
if want do normal ajax, can suggest use jquery template.
on php side;
<?php if(isset($_get['genre'])) { $genre=$_get['genre']; } $result=mysqli_prepare($connection,'select * songs genre=?'); mysqli_stmt_bind_param($result,'s',$genre); mysqli_stmt_execute($result); mysqli_stmt_bind_result($result,$id,$title,$artist); #arr = array(); while ( mysqli_stmt_fetch($result) ) { $arr[] = $id; } return json_encode($arr);
ok, have returned json, let's render on js side; let html below
<ul id="result"><ul>
and javascript
$("a").on("click", function() { $.getjson( "your.php" + $(this).attr("href"), function( data ) { var template = "<li><b>${id}</b> <b>${title}</b> <b>${artist}</b></li>"; $.template( "yourtemplate", template ); $.tmpl( "yourtemplate", data ) .appendto( "#result" ); }); });
for more detail jquery template, refer here
Comments
Post a Comment