I'm working on making an API call in PhoneGap. I wrote a function and calling it from a button click event, and I'm getting a response too, but I want to know how to display it. I have tried, but it's not working.
function getContactList() {
console.log("Entering getContactList()");
$.ajax({
url: "https://api.androidhive.info/contacts/",
dataType: "json",
cache: false,
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success: function(json) {
console.log("====CONTACTLIST ---->", json);
$(json).find("contacts").each(function() {
var html = '<li>' + $(this).find("name").text() +
' ' + $(this).find("name").text() + '</li>';
$('#contacts').append(html);
});
}
});
}
You're receiving JSON string which is then automatically converted by jQuery to a JavaScript object, so you can interact with it directly and shouldn't convert it to a jQuery object like $(json). Change the code inside your success to this:
for (var i = 0; i < json.contacts.length; i++) {
var c = json.contacts[i];
var html = '<li>' + c.name + ' ' + c.email + '</li>';
$('#contacts').append(html);
}
Note: it seems that there is an error in your code, you're using the find("name") twice. I changed it to name & email, but you can use any property of the contacts that you're getting.
Related
First, I think my title isn't very clear and very representative of what I want to achieve, but I couldn't make it clearer ...
Ok so I have a Leaderboard, created from this ajax call:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var tb = document.getElementById('Leaderboard');
while(tb.rows.length > 1) {
tb.deleteRow(1);
};
var keys = Object.keys(data);
for( key of keys) {
var username = data[key].username;
var score = data[key].score;
var row = $('<tr id = "row' + tb.rows.length + '"><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
if(tb.rows.length > 11){
tb.deleteRow(tb.rows.length -1);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
So as you can see in the Leaderboard, when clicking on a username, it opens a new page with the result of a GET request (/leaderboard/:username). My question is how can I skin this page, or even better load an html file in this page, but while keeping accessible the result of the GET request to use it inside?
That may not be clear, and that's maybe a reason why my title is not really fitting ... But anyway if you have some ideas i'll take them !!
Thanks
I have a .net web api method that when open in the browser it returns a valid XML (http://localhost:49546/api/Products)
<ArrayOfProductModel><ProductModel><Color>Black</Color><DiscontinuedDate i:nil="true"/><ListPrice>1431.5000</ListPrice><ModifiedDate>2008-03-11T10:01:36.827</ModifiedDate><Name>HL Road Frame - Black, 58</Name><ProductCategoryId>18</ProductCategoryId><ProductId>680</ProductId><ProductModelId>6</ProductModelId><ProductNumber>FR-R92B-58</ProductNumber><SellEndDate i:nil="true"/><SellStartDate>2002-06-01T00:00:00</SellStartDate><Size>58</Size><StandardCost>1059.3100</StandardCost><Weight>1016.04</Weight></ProductModel> </ArrayOfProductModel>
When I try to call that method using AJAX the data is being shown as an [object XMLDocument] but the data.responseXML is undefined so I can not process the XML response to show it as a table.
<script type="text/javascript">
$(document).ready(function () {
getProducts();
});
function getProducts()
{
$.ajax({
url: 'http://localhost:49546/api/Products',
method: 'GET',
dataType: 'xml',
//contentType: 'application/xml; charset=utf-8',
success: function (data) {
alert("GetProducts successfully");
showProducts(data);
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
}
function showProducts(data)
{
alert(data);
alert(data.responseXML);
alert(data.responseText);
var i;
var xmlDoc = data.responseXML;
var table = "<tr><th>Nombre</th><th>ListPrice</th></tr>";
var x = xmlDoc.getElementsByTagName("ProductModel");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("ListPrice")[0].childNodes[0].nodeValue +
"</td></tr>";
}
//alert(data);
document.getElementById("prodTable").innerHTML = table;
}
</script>
Please let me know what is missing or wrong
Web API passes back JSON as the default data type. That's what you're getting in {"location":null}
If you want to pass back XML, check out this article: WebAPI to Return XML
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 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.');
}
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am getting a list from C# web method with ajax (code below), the list is returned fine, but after the success method is done, it gives me an error - (Cannot read property 'length' of undefined) in the jquery (screenshot below)
Am I missing something ??
function getMainParentMenus() {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
The method above is called by the below method.
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
// var parentMenus = getMainParentMenus();
getMainParentMenus();
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
};
EDIT :
the data in the alert in the first block of code above is displayed like so
and in the chrome debugger :
Because getMainParentMenus is using AJAX it is asynchronous. Your next line of code after calling getMainParentMenus will be executed before the .success part of your AJAX call, so it will be executed before parentMenuss has been populated.
There are a few ways you can tackle this, one way would be to pass the callback function to getMainParentMenus, something like this:
function getMainParentMenus(myCallback) {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
if (callback && typeof(callback)==="function") {
callback();
}
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
Now you can call it like this:
var html = "<div id='accordian'> ddd";
getMainParentMenus(function() {
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
});
Your code for rendering the menus is being executed immediately after getMainParentMenus(); Javascript does not wait for the ajax call to complete before moving on to the next block. It is operating asynchronously, as others have mentioned in the comments.
Your code has to wait for the ajax call to complete before trying to display the data.
jQuery supports deferred execution and promises, so you can create code that will not execute until other code has completed. This is the preferred way of handling asynchronous operations.
Try this:
function getMainParentMenus() {
var request = $.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
return request;
}
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
getMainParentMenus().success(function (result) {
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
});
}