JQuery $.ajax Google Books API using phonegap and jQueryMobile - javascript

How can I make this code work, the problem is that I can't seem to be able to acces the data returned, I know that it connects to the server, but for somereason it wont work, for example, I tried extracting the title but nothing appears.
$.ajax({
url : "https://www.googleapis.com/books/v1/volumes?q=harry+potter",
dataType : "jsonp",
async : true,
//if ajax call succeeds perform this action
success : function(result) {
ajax.parseJSONP(result);
},
//if there is an error to the ajax call perform this action
error : function(request, error) {
alert('Network error has occurred please try again!');
}
});
//parseJsonP and add new elements to list-view
var ajax = {
parseJSONP : function(result) {
//iterate each returned item
$.each(result, function(i, row) {
$('#listview_test').append('<li><h3>' + row.volumeInfo.title + '</h3></a></li>');
}); //end iteration of data returned from server and append to the list
$('#listview_test').listview('refresh'); // refresh the list-view so new elements are added to the DOM
}
}
My confusion is on the callback method, in their example Books API has a code like is shown down, but I dont get it this part q=harry+potter&callback=handleResponse, how can I make this while using the $.ajax method. Tried understanding all the pieces but still very confusing?
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
</body>

Try replacing your following code:
$.each(result, function(i, row) {
for this one:
$.each(result.items, function(i, row) {
As per the google example code the data is located in an array called items within the returned object.

Related

Why am I getting a '$' is not defined when running an AJAX query?

Possibly a dumb question, but I have a page where I'm trying to load list data into a customer table to display as a front-end. I'm retrieving this list from a SharePoint list using an AJAX call in a Javascript function, however when I'm using this function my console returns a SCRIPT5009: '$' is not defined error. Previously, I've used an AJAX call successfully using very similar code, but to return a single item from the list using the list ID to search for a specific item, and I've run the query successfully directly from the URL that returns the data I'm after - I'm just not sure what's happening with this one.
function getIncidents(){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$select=Title,Id,Priority,IncidentStart,IncidentStatus,IncidentTitle,UpdateResolution",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
var dResponse = data.d.results;
var results = document.getElementById('Results');
results.innerHTML += "<tr><td>Incident<br>Reference</td><td style='width:20px'></td><td>Priority</td><td style='width:20px;'></td><td>Start Time</td><td style='width:20px'></td><td style='width:170px'>Issue</td><td style='width:20px'></td><td style='width:170px'>Latest Update</td><td style='width:20px'></td></tr>";
for(var obj in dResponse){
results.innerHTML += "<tr style='font-size:10pt'><td>"+dResponse[obj].Title + "</td><td></td><td>" + dResponse[obj].Priority + "</td><td></td><td>" + dResponse[obj].IncidentStart + "</td><td></td><td>" + dResponse[obj].IncidentTitle + "</td><td></td><td>" + dResponse[obj].UpdateResolution + "</td></tr>";
}
}
});
}
Previous example where I have this call working:
function getIncident() {
var listName="Incident List";
var incidentID = $("#incidentReference").val();
if(incidentID!=""){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$filter=Title eq '" + incidentID + "'&$select=Title,Id,SystemOrService,Priority,IncidentStatus,IncidentTitle,UpdateResolution,IncidentStart,ImpactedArea,IncidentEnd",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
if(data.d.results.length>0){
var item=data.d.results[0];
$("#systemImpacted").val(item.SystemOrService);
$("#incidentPriority").val(item.Priority);
$("#incidentState").val(item.IncidentStatus);
$("#incidentTitle").val(item.IncidentTitle);
$("#incidentUpdate").val(item.UpdateResolution);
$("#startTime").val(item.IncidentStart);
$("#impactedAreas").val(item.ImpactedArea.results);
$("#endTime").val(item.IncidentEnd);
updateImpact();
getStartTime();
getEndTime();
actionsFormat();
}
},
error: function (data) {
alert("Incident Reference incorrect or not found");
}
});
}
}
The issue is that jQuery ($) is not yet loaded to the page. If you used it before, this means that loading is already setup, so you don't need to add more references to the jQuery.
In most of the cases, when you working with jQuery, you will subscribe on DOM event ready event and do your code there.
So, all you need is to find the
$(document).ready( ...
statement and insert your code there.
If you want to separate your code from already existed, you may write your own $(document).ready subscription.
If you will not find this $(document).ready function, you can search in html for the reference to the jQuery, and insert your script after it. But, than you need to be sure, that reference doesn't include async or defer attribute.
As mentioned in comments, if you decide to add your own subscription, you also need to place it after jQuery reference, because it will not work, if $ isn't available.

How can I execute a query on success of jQuery

I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});

Calling Javascript Functions In Order

I'm trying to use a button to perform an API Call to Flickr, like so:
$(document).ready(function (){
$('#goButton').click(function (){
makeAPICall();
});
});
This works as expected, but the communication between the client and the Flickr API takes a while to execute, so the page appears like it is hung. I would like to add a "Working Notice" that is displayed immediately on button click to let the user know that their action is processing.
To do this, I added an H1 tag:
<h1 id="notice"></h1>
and a function that changes the inner HTML to display a notice:
function workingNotice() {
document.getElementById("notice").innerHTML="I am getting your results";
}
But when I try to edit the code for the button to something like this:
$(document).ready(function (){
$('#goButton').click(function (){
workingNotice();
makeAPICall();
});
})
The Working Notice is never displayed until the API Call has completed, which defeats the purpose.
I then tried using:
$(document).ready(function (){
$('#goButton').click(function (){
$.when(
workingNotice()
).then(
makeAPICall()
);
});
})
This gives the exact same results, where the Working Notice is not called until the API Call completes. Is there any alternative that I can try to force the order of these functions to comply?
UPDATE/EDIT:
While I found the solution to the initial problem in another answer, I know there's a reasonable chance the delay in the API Call processing is due to some mistake in this function. Here is the code for makeAPICall:
//call Flickr api and look for tags matching user search term
function makeAPICall(){
//get value tag from team 1 search box
var searchTag1 = escape(document.getElementById("searchTag1").value);
//get value tag from team 2 search box
var searchTag2 = escape(document.getElementById("searchTag2").value);
//build api call url with searchTag1
var url1 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag1 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//build api call url with searchTag1
var url2 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag2 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//make call to flickr api
$.when(
$.ajax({
dataType: "json",
url: url1,
async: false,
success : function(callReturn1) {
callData1 = callReturn1;
numResults1 = parseInt(callData1.photos.total);
}
}),
$.ajax({
dataType: "json",
url: url2,
async: false,
success : function(callReturn2) {
callData2 = callReturn2;
numResults2 = parseInt(callData2.photos.total);
}
})
).then(
drawChart()
);
}
Note "callData1", "callData2", "numResults1" & "numResults2" are all global.
If your makeAPICall is not async - call it out of bounds:
workingNotice();
setTimeout(makeAPICall, 1);

Return or structure code so data from ajax call can be used in dynamically populated list

an answer from a previously question I asked here has posed another problem for me, as I am learning more and more about async calls I still can not figure out how to accomplish (as the previous answer showed me) a list which allows me to store and use data from a selected list item.
$('#home').live('pageshow', function(){
// creating object
var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
});
with js fiddle http://jsfiddle.net/amEge/3/
This code works excellent and will allow me to accomplish what I want but fist I need to populate the customerList from a ajax call. But from the "success" function I cannot seem to get the code to work.
$.post(postTo,{id:idVar} , function(data) {
customerList = data;
//alert(customerList);
})
When I move the code inside the ajax function it dose not work. I was just wondering if anyone could help me and maybe show me how to deal with this from asynchronous calls ?
Many Thanks
You need to change your page as below.
// I assume this is your dot net web service url
var webServiceURL = 'customer.asmx/GetCustomer';
// here home is your page's ID
$('#home').live('pageshow', function(){
getCustomerList();
});
function getCustomerList(){
param=JSON.strigify({id:'2'});
callWebService(param, webServiceURL, onGetCustListSuccess, onGetCustListFailed)
}
function onGetCustListFailed(){
alert("service request failed");
}
function onGetCustListSuccess(data, status){
// creating object
// replace previous line with below
// var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
var customerList = JSON.parse(data.d);
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
}
function callWebService(param,url,successFunc,errorFunc){
if(errorFunc=='undefined'){
errorFunc=OnDataError;
}
$.ajax({
type: "POST",
url: url,
data: param,
contentType:"application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc,
beforeSend:function(){$.mobile.loading( 'show' );},
complete:function(){$.mobile.loading( 'hide');}
});
}
Hope this would help you out. If you have problems asks me here.
Correct me if I'm wrong, but I'll hazard a guess that your "live" code looks something like this:
$('#home').live('pageshow', function(){
// creating object
var customerList;
$.post(postTo, {id:idVar}, function(data) {
customerList = data;
//alert(customerList);
});
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// and all the rest...
If so, then your problem is that the code that's depending on your customerList variable being filled in ("all the rest...") runs immediately, rather than waiting for the response from your HTTP request to come back from the Web server. That $.post() doesn't wait around (or "block," as we say in the computer software programming game) while the HTTP transaction makes its way to the Web server and back. Instead, the rest of your code runs immediately, and then later, when that response comes back to the browser, the JavaScript engine dutifully executes your success function (or "closure," as we hm hmm hmmmm).
So what you'll want to do is put all this other code (the stuff that's dependent on customerList) into a separate function, then call that function from within your success closure. You won't even need your customerList variable then; you can just pass the new response data as an argument to your new function.

Telerik MVC Grid - Pass Value to New Controller Action

Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.

Categories