Server-side:
$bookmarkarray = array();
if(mysqli_connect_error())
{
echo "failed to connect to the database : %s\n".mysqli_connect_error();
exit();
}
if ($getdata = $dbc->query("select * from bookmark"))
{
while($obj = $getdata->fetch_object())
{
//echo $obj->username. " ".$obj->bm_URL."<br/>";
$temp_bookmark = new bookDB($obj->username,$obj->bm_URL);
$bookmarkarray[] = $temp_bookmark;
}
//convert to json
if (!empty($bookmarkarray)) {
echo json_encode($bookmarkarray);
}
$getdata->close();
$dbc->close();
}
</pre><pre name="code" class="php">class bookDB
{
public $username ="";
public $bm_URL="";
function __construct($_username,$_bmURL)
{
$this->username=$_username;
$this->bm_URL=$_bmURL;
}
}
Client-side:
<script type="text/javascript">
$.ajax({
// The URL for the request
url: "http://localhost:63343/PhpBooks/json_book.php",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
$.each(json,function(idx,value){
$("#list").append("<li>" + value.username + "-" + value.bm_URL + "</li>");
});
})
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
});
</script>
Client-side(POST):
<form id="myForm" action="http://localhost/PhpBooks/json_book.php" method="post">
<p>Name:<input name="name" type="text" id="txtname"/></p>
<input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
var frm = $("#myForm");
frm.submit(function(event){
if($("#txtname").val().length===0){
alert('Please input a name!');
event.preventDefault();
}
else
{
//show indicator:
$(".loadingindicator").css("visibility","visible");
$.ajax({
// The URL for the request
url: frm.attr("action"),
// The data to send (will be converted to a query string)
data: frm.serialize(),
// Whether this is a POST or GET request
type: frm.attr("method"),
// The type of data we expect back
dataType: "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function (json) {
$.each(json, function (idx, value) {
$("#list").append("<li>" + value.username + "-" + value.bm_URL + "</li>");
});
})
.success(function(data){
alert('ok');
})
.fail(function (xhr, status, errorThrown) {
alert("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
})
// Code to run regardless of success or failure;
.always(function (xhr, status) {
alert("The request is complete!");
$(".loadingindicator").css("visibility","hidden");
});
}
event.preventDefault();
});
</script>