I'm sending an AJAX request with multiple arrays and I can't figure out how to grab the data?
This is what I'm sending:
I'm doing this through a jQuery AJAX POST to a PHP file.. How would one go about grabbing the data from here?
Thank you!
-- EDIT!!
This is the jQuery
var h1 = []
h2 = []
h3 = [],
layout = $( "input[type=radio][name='layout_option']:checked" ).val();
$("ul.widget-order[name='1'] li").each(function() { h1.push($(this).attr('id')); });
$("ul.widget-order[name='2'] li").each(function() { h2.push($(this).attr('id')); });
$("ul.widget-order[name='3'] li").each(function() { h3.push($(this).attr('id')); });
var sendData = JSON.stringify({
ids1: " " + h1 + "",
ids2: " " + h2 + "",
ids3: " " + h3 + ""
});
$.ajax({
type: "POST",
url: "_backend/account/updateWidgets.php",
data: { data: sendData } + '&layout=' + layout,
success: function( data ){
$("#post_reply").html(data);
console.log( { data: sendData } );
)};
)};
To read the JSON encoded data on the PHP side:
<?php
$json = file_get_contents('php://input');
$decodedJSON = json_decode($json);
?>
http://php.net/manual/en/function.json-decode.php
$_POST['data'] contains JSON, so call json_decode().
$data = json_decode($_POST['data'], true);
Now you can access $data['ids1'], $data['ids2'], etc.
There isn't really any good reason to send the data as JSON. You could just put the original object directly in the jQuery data: option. Then you would could access the parameters as $_POST['ids1'], $_POST['ids2'], etc.
$.ajax({
type: "POST",
url: "_backend/account/updateWidgets.php",
data: {
ids1: " " + h1,
ids2: " " + h2,
ids3: " " + h3,
layout: layout
},
success: function(data) {
$("#post_reply").html(data);
console.log({
data: sendData
});
}
});
Assuming that the post request to your Php file is successful you can access it by using the $_POST variable.
If I may, I would recommend changing the way you are making the jQuery request to the following:
var h1 = []
h2 = []
h3 = [],
layout = $( "input[type=radio][name='layout_option']:checked" ).val();
$("ul.widget-order[name='1'] li").each(function() { h1.push($(this).attr('id')); });
$("ul.widget-order[name='2'] li").each(function() { h2.push($(this).attr('id')); });
$("ul.widget-order[name='3'] li").each(function() { h3.push($(this).attr('id')); });
var sendData = JSON.stringify({
ids1: " " + h1 + "",
ids2: " " + h2 + "",
ids3: " " + h3 + ""
});
var sPayload = "data=" + encodeURIComponent(sendData) + "&layout=" + encodeURIComponent(layout);
$.ajax({
type: "POST",
url: "_backend/account/updateWidgets.php",
data: sPayload,
success: function( data ){
$("#post_reply").html(data);
console.log( { data: sendData } );
}
});
There were a few syntax errors in code you posted which I have corrected in the code included in my answer, but most importantly, I have modified your data to being all of one encoding. It seems like you were trying to combine a JSON Object with standard data encoded as application/x-www-form-urlencoded. I have standardized this in the code above so all data is posted as application/x-www-form-urlencoded.
In your PHP, you can then access this as:
<?php
// First, let's get the layout because that's the easiest
$layout = (isset($_POST['layout']) ? $_POST['layout'] : NULL);
// As a note, the isset(...) with ternary operator is just my preferred method for checking missing data when extracting that data from the PHP super-globals.
// Now we'll need to get the JSON portion.
$jData = $_POST['data'];
$data = json_decode($jData, $assoc=true);
echo "ids1 is " . $data['ids1'] . "\n<br>\n";
echo "ids2 is " . $data['ids2'] . "\n<br>\n";
echo "ids3 is " . $data['ids3'] . "\n<br>\n";
?>
Follow this code
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
I think have a mistake between data is property of ajax object and data is property in your post data.
Please post your jquery code.
Related
THE CONTEXT
I'm developing a web app that loads contents dynamycally, retrieving data from a
catalogue of items stored as a MongoDB database in which records of the items and their authors are in two distinct collections of the same database.
Authors ID are stored in the item field creator and refer to the author field #id. Each item can have none,one or many authors.
Item sample
{
"_id" : ObjectId("59f5de430fa594333bb338a6"),
"#id" : "http://minerva.atcult.it/rdf/000000016009",
"creator" : "http://minerva.atcult.it/rdf/47734211-2637-3895-a690-4f33412931ec",
"identifier" : "000000016009",
"issued" : "fine sec. XIV - inizi sec. XV",
"title" : "Quadrans vetus",
"label" : "Quadrans vetus"
}
Author sample
{
"_id" : ObjectId("59f5d8e80fa594333bb1d72c"),
"#id" : "http://minerva.atcult.it/rdf/0007e43e-107f-3d18-b4bc-89f8d430fe59",
"#type" : "foaf:Person",
"name" : "Risse, Wilhelm"
}
WHAT WORKS
I query the database submitting a string in a form, using this PHP script
ITEM PHP SCRIPT
<?php
require 'vendor/autoload.php';
$title=$_GET['item'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->items;
$regex=new MongoDB\BSON\Regex ('^'.$title,'im');
$documentlist=$collection->find(['title'=>$regex],['projection'=>['_id'=>0,'title'=>1,'creator'=>1,'issued'=>1]]);
$items=$documentlist->toArray();
echo (json_encode($items));
?>
called by a Javascript script (new_search.js) using ajax, that has also the responsibility to attach to html document a <li class=item> for every item that matches the query, inserting the JSON fields and putting them in the provided tags ( <li class=item-name>,<li class=auth-name, and the last <li> in div class=item-info for date).
WHAT DOES NOT WORK
My intent is reproduce the pattern to retrieve author names from another collection in the same database, querying it using author field #id from the html tag <li class=auth-name, using a similar php script and a similar ajax call.
I tried to make a nested ajax call (in the one I used to retrieve the items infos) to invoke author_query.php that performs the MongoDB query on the collection of authors.
So, the question is: Is it possible use the $_GET superglobal to get the html tag that contains the author id #id in order to search it in the database?
Otherwise, how can I adjust the code to pass a javascript variable to php (not by user input) that lets me keep the content already loaded on the page?
UPDATES
To make clearer the question, I follow the tips in the comments and I updated my scripts using JSON directly to provide the needed data.
I also perfom a debug on the js code and it's clear that PHP don't provide any response,in fact ajax calls for authors name fails systematically.
I suppose that occurs because PHP don't receive the data dueto the fact I'm not using the correct syntax probably (in js code or in the php with $_GET or in both) to pass the variable author (I also tried data:'author='+author treating the JSON object author has a string). Anyway I don't understand what is the correct form to write the variable to pass using the data field of ajax().
MY SCRIPTS
JS SCRIPT new_search.js
$(document).ready(function () {
$("#submit").on("tap", function () {
var item = document.getElementById("search").value;
var author;
$.ajax({
url: "item_query.php",
type: "GET",
data: 'item=' + item,
dataType: "json",
async:false,
success: function (items) {
for (var i = 0; i < items.length; i++) {
$("#items-list").append(
'<li class="item">' +
'<div class="item-photo-container">' +
'<img src=images/item_126.jpg>' +
"</div><!--end item-photo-container-->" +
'<div class="item-info">' +
'<ul>' +
'<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
'<li class="auth-name">' + items[i].creator+ '</li>' +
'<li>' + items[i].issued + '</li>' +
'</ul>' +
'</div><!--end item-info-->' +
'</li><!--end item-->'
);
}
}
});
$('.item').each(function () {
author = $(this).find('.auth-name').text();
if (author == 'undefined')
$(this).find('.auth-name').text('Unknown');
else if(author.indexOf(',')!=-1) {
author='[{"author":"'+author+'"}]';
author=author.replace(/,/g,'"},{"author":"');
author = JSON.parse(author);
console.log(author);
$.ajax({
url: "author_query.php",
type: "GET",
data: author,
dataType: "json",
processData: false,
success: function (auth_json) {
$(this).find('.auth-name').text('');
var author_text=' ';
for(var i=0;i<auth_json.length;i++)
author_text+=auth_json.name+' ';
$(this).find('.auth-name').text(author_text);
},
error: function () {
console.log('Error 1');
}
});
}
else{
author='{"author":"'+author+"}";
author=JSON.parse(author);
$.ajax({
url: "author_query.php",
type: "GET",
data: author,
dataType: "json",
processData: false,
success: function (auth_json) {
$(this).find('.auth-name').text(auth_json.name);
},
error: function () {
console.log('Error 2');
}
});
}
});
});
});
AUTHOR PHP SCRIPT author_query.php
<?php
require 'vendor/autoload.php';
$auth=$_GET['author'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
if(is_array($auth)){
foreach ($auth as $a){
$document=$collection->findOne(['#id'=>$a],['projection'=>['_id'=>0,'name'=>1]]);
$auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
}
else{
$document=$collection->findOne(['#id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
$auth_json=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
echo (json_encode($auth_json));
?>
"I'm sure that authors array... is not empty and actually contains the authors IDs". You mean the jQuery object $('.item')? I think that it is empty, because it is created too soon.
The first $.ajax call sends an ajax request and sets a handler to add more stuff to the HTML, including elements that will match the CSS selector .item. But the handler doesn't run yet because it's asynchronous. Immediately after this, the object $('.item') is created, but it's empty because the new .item elements haven't been created yet. So no more ajax requests are sent. Some time later, the call to item_query.php returns, and the new HTML stuff is added, including the .item elements. But by now it's too late.
You say the array was not empty. I suspect you checked this by running the CSS selector after doing the search, after the return of the ajax call.
A lot of newbies have problems like this with asynchronous javascript. If you want to use the result of an asynchronous function in another function, you have to call the second function inside the callback function of the first one. (Actually there are more sophisticated ways of combining asynchronous functions together, but this is good enough for now.)
On a side note, you've done this in a slightly strange way where you save data in HTML, and then read the HTML to do some more stuff. I wouldn't use HTML as a storage place - just use variables like you would for most other things.
Try this:
$.ajax({
url: "item_query.php",
...
success: function (items) {
for (var i = 0; i < items.length; i++) {
var author = items[i].creator;
var authors;
// insert code here to generate authors from author.split(',') .
// authors should look something like this: [{author: 'http://minerva.atcult.it/rdf/47734211-2637-3895-a690-4f33412931ec'}] .
$.ajax({
url: "author_query.php",
type: "GET",
data: JSON.stringify(authors),
...
success: function (auth_json) {
...
},
error: function () {
console.log('Error 1');
}
});
$("#items-list").append(
'<li class="item">' +
'<div class="item-photo-container">' +
'<img src=images/item_126.jpg>' +
"</div><!--end item-photo-container-->" +
'<div class="item-info">' +
'<ul>' +
'<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
'<li class="auth-name">' + items[i].creator+ '</li>' +
'<li>' + items[i].issued + '</li>' +
'</ul>' +
'</div><!--end item-info-->' +
'</li><!--end item-->'
);
}
}
});
I make the first call to retrieve the item infos asynchronous and the nested that search for the authors name synchronous. In this way I solved the problem.
For sure it is not the best solution, and it needs a quite long,but acceptable, time (<1 second) to load the content.
JS SCRIPT
$(document).ready(function () {
$("#submit").on("tap", function () {
var item = document.getElementById("search").value;
$.ajax({
url: "item_query.php",
type: "GET",
data: 'item=' + item,
dataType: "json",
success: function (items) {
for (var i = 0; i < items.length; i++) {
var authors_names=' ';
var authors= JSON.stringify(items[i]);
if(authors.indexOf('creator')!=-1){
if(authors.charAt(authors.indexOf('"creator":')+'"creator":'.length)!='[')
authors=authors.substring(authors.indexOf('"creator":"'),authors.indexOf('"',authors.indexOf('"creator":"')+'"creator":"'.length)+1);
else
authors=authors.substring(authors.indexOf('"creator"'),authors.indexOf(']',authors.indexOf('"creator"'))+1);
authors='{'+authors+'}';
//console.log(authors);
$.ajax({
url: "author_query_v3.php",
type: "GET",
data: 'authors='+authors,
dataType:"json",
async:false,
success: function (auth_json) {
authors=[];
authors=auth_json;
var author;
for(var j=0;j<authors.length;j++){
author=JSON.parse(authors[j]);
authors_names+=author.name+" | ";
}
console.log(authors_names);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR+' '+textStatus+ ' '+errorThrown);
}
});
}
else{
authors_names='Unknown';
}
$("#items-list").append(
'<li class="item">' +
'<div class="item-photo-container">' +
'<img src=images/item_126.jpg>' +
"</div><!--end item-photo-container-->" +
'<div class="item-info">' +
'<ul>' +
'<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
'<li class="auth-name">' + authors_names+ '</li>' +
'<li>' + items[i].issued + '</li>' +
'</ul>' +
'</div><!--end item-info-->' +
'</li><!--end item-->'
);
}
}
});
});
});
PHP SCRIPT
<?php
require 'vendor/autoload.php';
$auth=$_GET['authors'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
$auth=json_decode($auth);
$auth=$auth->creator;
if(is_array($auth)) {
foreach ($auth as $a) {
$document = $collection->findOne(['#id' => $a], ['projection' => ['_id' => 0, 'name' => 1]]);
$auth_json[] = (MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
}
else{
$document=$collection->findOne(['#id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
$auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
echo(json_encode($auth_json));
?>
I am getting response in jquery as below. I want to show images from the db through the ajax request.
My controller code :
public function images($id='')
{
$this->load->model('gallery');
$data = this->gallery_model->getimages($this->input->post('id'));
echo json_encode($data);
}
My ajax :
function imageslide(folderid){
$.ajax({
url: "<?php echo site_url() ?>/welcome/images",
type: "POST",
dataType: "json",
data: {id: folderid},
success: function(result) {
if(result){
resultObj = eval (result);
alert(JSON.stringify(resultObj));
}else{
alert("error");
}
}
});
The result which i received in the Network tab is
[{"id":"153","file_name":"DSC00081.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"},{"id":"154","file_name":"DSC00082.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"},{"id":"155","file_name":"DSC00083.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"}]
I do not know how to show image in the browser in the <img> tag. As you can see, I am getting jpeg in the alert window. Kindly help me through.. Thanks in Advance!
You can append the imagen using jQuery, for example with the first index of array:
$('#container').append('<img src="' + result[0].file_name + '" />');
If you want to add each image, you can use forEach loop.
result.forEach(function (image) {
$('#container').append('<img src="' + image.file_name + '" />');
});
Copying from your code
function imageslide(folderid){
$.ajax({
url: "<?php echo site_url() ?>/welcome/images",
type: "POST",
dataType: "json",
data: {id: folderid},
success: function(result) {
if(result){
resultObj = eval (result);
var HTMLbuilder = "";
for(var i = 0; i < resultObj.length; i++){
var imgHtml = "<img src='path-toImage/" + resultObj[i].file_name + "'>";
HTMLbuilder = HTMLbuilder + imgHtml;
}
$("#imgContainer").html(HTMLbuilder);
}else{
alert("error");
}
}
});
Don't forget to have the div with the appropriate ID on the HTML
<div id="imgContainer"></div>
On pure js:
Plunker
result.forEach(img => {
let element = document.createElement('img');
element.width = '100'
element.src = img.path;
parentEl.appendChild(element)
})
You have received JSON object in result. Just loop through it, using
$.each(result, function(key, value){
$('#container').append('<img src=" +value.file_name + " />');
})
It looks like everything has gone fine retrieving the data from the ajax call, but I having trouble to fill the select with the JSON content, it keeps firing this error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
The JS is this
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var $select = $('#newStatus');
$.each(response,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
The JSON looks like this:
[{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
I think you need something like this.
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var json = $.parseJSON(response);
var $select = $('#newStatus');
$.each(json ,function(index, object)
{
$select.append('<option value=' + object.s_id+ '>' + object.s_name+ '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to parse the response to Json.
Then you could use the $.each() function to loop through the data:
var json = $.parseJSON(response);
I get some data using JSON array. I want to append each data in a div. But I don't get what's wrong in that?
controller
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
script
function get_performers(id,exam)
{
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
// alert("haii");
console.log(result);
result = JSON.parse(result);
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
for(var i=0;i<result.student_details.length;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + result.student_details[i]["subject_name"]+ "</span></div> ";
}
jQuery("#subjectNames").append(tab);
}
});
}
Any problem in this?
Try html not append
jQuery("#subjectNames").html(tab);
Also if jQuery("#subjectNames") equal with null in your console this mean that you don't have element with id="subjectNames" in html not id="#subjectNames" or other. May be you use classes then try $(".subjectNames") with . not #
The Loop should work... Seems to be another problem with your result.
var tab= "<div class='col-xs-2 blk-ht'><span class='hd'>Names</span> </div>";
for(var i=0;i<20;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + "test: " + i + "</span></div> ";
}
jQuery("#subjectNames").append(tab);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="subjectNames"><div>
dataType: 'json' in $.ajax options - automaticaly parse your json
and USE JQUERY )))
IN SUCCES AJAX FUNCTION
$.each( result.student_details, function( key, value ) {
alert( key + ": " + value );
});
<?php
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
?>
<script>
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
$.each(response.student_details, function(key,value){
appendHtml(key,value);
});
}
});
function appendHtml(key,value)
{
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
tab = tab+"<div class='col-ds-1'><span class='subjNames'>" +value+ "</span></div> ";
jQuery("#subjectNames").append(tab);
}
</script>
I am trying to parse some JSON and take the elements "startTime" and "endTime" and add them to a list. I am able to receive the JSON successfully, however I am having trouble properly parsing and then looping through to add each instance to the list. Inside of the UL, i would like to create lists for each, like i demo below:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
The HTML where I am trying to insert the LI inside of the UL:
<div data-role="main" class="ui-content" id="headerDate">
<ul data-role="listview" data-inset="true" id="appts">
</ul>
</div>
So basically for each appointment i get back in the JSON, I want to add a new LI with the startTime and endTime.
I am using JQM 1.3.2, and JQUERY 1.8.0.
Thank you
Change this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
Into this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
$.each( json, function( key, value ) {
var agrega = "<li data-role='list-divider'>";
if(key=='startTime')
{
agrega = agrega + value
}
if(key=='endTime')
{
agrega = agrega + ' - ' + value;
}
agrega = agrega + '<span class="ui-li-count"></span></li>';
$('#appts').append(agrega);
});
From your code sample, it seems your problem is that you're trying to look for the startTime property in the wrong place (on this). In your sample, the startTime property should be present on your parsed JSON, so accessing the key there should do the trick:
$('<li data-role="list-divider">' + json.startTime
+ ' - ' + json.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
If the returned JSON is a series of times, then you'll also want to loop through the JSON object as well:
$.each(json, function(key, value) {
if (key === 'startTime') {
// append to the list
}
});
Additional note:
If JSON is what is being returned from the AJAX call, then you shouldn't need to use $.parseJSON on it. JSON objects are JavaScript objects, so you can simply use the returned value and access they keys on it (meaning you can use data.startTime directly instead of parsing it first).
Please find the response below
var ulObject = $("#appts");
var ajaxObject = $.ajax({
type:"POST",
dataType:"json",
url:"" //Provide the URL in the field to be processed.
});
ajaxObject.done(function(msg){
var jsonResponse = $.parseJSON(msg);
var listObjectStart = '<li data-role="list-divider">'
var listObjectEnd = '</li>';
$.each(jsonResponse,function(key,value){
if(key === "startTime")
{
listObjectStart += value;
}
else if(key === "endTime")
{
listObjectStart += '-'+value+'<span class="ui-li-count"></span>';
}
});
listObjectStart += listObjectEnd;
ulObject.append(listObjectStart);
});
Try the following if server send the data back to client in json format.
$.ajax({
url: 'localhost:8080/sample?',
dataType : 'json',
success: function(data){
$("#appts").append('<li data-role="list-divider">' + data.startTime
+ ' - ' + data.endTime + '<span class="ui-li-count"></span></li>');
},
error: function(){
alert('There was an error in communication.');
}
});