You may want to look at this previous post where I setup a Web Service using JSONP from External Domain – PHP – JQuery
The HTML that calls the Javascript:
<div id="taglist"></div>
<input name="searchTags" id="searchTags" type="text" />
<input type="button" name="searchtags" onclick="getTags()" value="search"/>
<div id="tagresult">
</div> |
<div id="taglist"></div>
<input name="searchTags" id="searchTags" type="text" />
<input type="button" name="searchtags" onclick="getTags()" value="search"/>
<div id="tagresult">
</div>
The JavaScript (JQuery) AJAX Request and Response Processing:
function getTags()
{
var q = $('#searchTags').val();
$.getJSON('ws.php?type=tag&wN=name&wO=like&wV=' + q, function(data) {
var items = [];
var htmlResult = "";
$.each(data, function(key, val) {
//As you can see, you can access the JSON (at the bottom of the page) by doing val.PROPERTYNAME:
htmlResult += "<br />Add : <a href=\"#\" onclick=\"addTag("+ val.id +", '"+ val.getfullname +"'); return false;\">"+ val.getfullname +"</a>";
});
$('#tagresult').html(htmlResult);
});
} |
function getTags()
{
var q = $('#searchTags').val();
$.getJSON('ws.php?type=tag&wN=name&wO=like&wV=' + q, function(data) {
var items = [];
var htmlResult = "";
$.each(data, function(key, val) {
//As you can see, you can access the JSON (at the bottom of the page) by doing val.PROPERTYNAME:
htmlResult += "<br />Add : <a href=\"#\" onclick=\"addTag("+ val.id +", '"+ val.getfullname +"'); return false;\">"+ val.getfullname +"</a>";
});
$('#tagresult').html(htmlResult);
});
}
PHP Code that returns JSON in the PHP file called by the AJAX: (ws.php)
$ta = new TagAccess();
$tarray = $ta->GetTagsWhere(" {$whereName} LIKE '%{$whereVariable}%'");
header('Content-type: application/json');
echo "", json_encode($tarray), ""; |
$ta = new TagAccess();
$tarray = $ta->GetTagsWhere(" {$whereName} LIKE '%{$whereVariable}%'");
header('Content-type: application/json');
echo "", json_encode($tarray), "";
The GetTagsWhere Helper Function:
public function GetTagsWhere($where) {
$retArray;
$sql = "SELECT * FROM tags WHERE {$where}";
// THE PDO Object was created previously
foreach ($this->pdo->query($sql) as $row)
{
$retArray[] = $this->GetTag($row);
}
return $retArray;
} |
public function GetTagsWhere($where) {
$retArray;
$sql = "SELECT * FROM tags WHERE {$where}";
// THE PDO Object was created previously
foreach ($this->pdo->query($sql) as $row)
{
$retArray[] = $this->GetTag($row);
}
return $retArray;
}
JSON Returned:
[{"id":"4","name":"FICTION","parentid":"3","getfullname":"BOOKS > FICTION"},{"id":"5","name":"NON-FICTION","parentid":"3","getfullname":"BOOKS > NON-FICTION"}] |
[{"id":"4","name":"FICTION","parentid":"3","getfullname":"BOOKS > FICTION"},{"id":"5","name":"NON-FICTION","parentid":"3","getfullname":"BOOKS > NON-FICTION"}]