Ajax get data to get another ajax data - javascript

I need some pointer about combining nested ajax call.
$.ajax({
type: "GET",
dataType: "json",
url: generalurl + "/Chore" + objectid + "?$expand=Process",
success: function (data, textStatus) {
list = $(data)[0]["TM1.ChoreProcessRel"];
res = [];
for (var i = 0, l = list.length; i < l; i++) {
var e = list[i];
GetDirectories(e.ID, function (d) {
alert(d); //this is working fine already
});
//I just want to include d on the below statement but I'm still getting undefined
res.push({
title: "" + e.Name, key: e.LogicalName + d,
});
}
}
});
and this is the GetDirectory code
function GetDirectories(choreid, callback) {
var theurl = webapiurl + '/Models' + getTopUrlVars()["model"] + '/ChoreProcess(' + choreid + ')?$expand=Process';
$.ajax({
type: "GET",
url: theurl,
data: {},
dataType: "json",
success: function (response) {
callback(response["TM1.ChoreProcessesProcess"][0].ID);
},
failure: function (msg) {
alert(msg);
}
});
}
Is it possible to do this? I tried using global variable but then the first value is "".

if you have return in getDirectories, try use variable
var d = GetDirectories(e.ID, function (d) {
alert(d); //this is working fine already
});
//I just want to include d on the below statement but I'm still getting undefined
res.push({
title: "" + e.Name, key: e.LogicalName + d,
});

Related

$.ajax is not working but $.getJSON is working

I am trying to get share count of pininterest and below code is working well
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.getJSON(PIUrl, function (data) {
pi_like_count = data.count;
alert(pi_like_count +' pininterest');
});
but when I am trying to put below code issue is coming as
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.ajax({
method: 'GET',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest');
},
error: function (data) {
alert('error' + data.count + ' pininterest');
console.log(data);
},
async: false
});
Console.log error as
promise: function promise()
readyState: 4
responseText: "{\"error\":\"Invalid callback, use only letters, numbers, square brackets, underscores, and periods.\"}"
This issue is coming when I am using $.ajax, I had tried same to get facebook share count and is working well but pininterest is not working
more explaination
function GetScores(url) {
var FBUrl, TWUrl, LNUrl, GLUrl, PIUrl;
var url1 = "";
url1 = encodeURIComponent(url1 || url);
//Fetch counters from PInterest
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest');
} ,
complete: function (jqXHR, data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest complete');
},
error: function (req, status, error) {
alert('error');
},
async: false
});
//Fetch counters from Facebook
var fb_share_count = 0;
FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
url: FBUrl,
success: function (data) {
fb_share_count = data.share.share_count;
alert(fb_share_count+' facebook');
},
async: false
});
var totalshare = parseInt(fb_share_count) + parseInt(pi_like_count);
return totalshare;
}
Here Facebook count and total share count is get then after the pinterest count alert is showing i.e. when this function is calling second time then after pinterest is giving old count.
Try it:
function GetScores(url, onCountTotal) {
var FBUrl, TWUrl, LNUrl, GLUrl, PIUrl;
var url1 = "";
url1 = encodeURIComponent(url1 || url);
//Fetch counters from PInterest
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?';
$.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
var fb_share_count = 0;
FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
dataType: 'json',
url: FBUrl,
success: function (data) {
fb_share_count = data.share.share_count;
var totalshare = parseInt(fb_share_count) + parseInt(pi_like_count);
onCountTotal(totalshare);
//alert(fb_share_count + ' facebook');
},
error: function (data) {
onCountTotal(-1);
},
async: true
});
},
error: function (req, status, error) {
onCountTotal(-1);
},
async: true
});
}
//EXAMPLE HERE CALL FUNCTION WITH CALLBACK
GetScores("http://www.google.com", function (count) {
alert("Count = " + count);
});
Here's what you could try using a CallBack :
var result = 0;
function handleData(data) {
result+=data.count;
}
function GetScores(url) {
var url1 = encodeURIComponent(url1 || url);
getFb(url1).done(handleData);
getPi(url1).done(handleData);
return result;
}
function getPi(url1){
var PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?';
return $.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl
});
}
function getFb(url1){
var FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
return $.ajax({
type: 'GET',
url: FBUrl
});
}
You can adapt for every platform you need the shares from, just add another function in GetScores and handle properly the returned json
You could also do something like :
function getFb(url1, callback){
var FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
url: FBUrl,
success: callback
});
}
getFb(function(data){
result+=data.count;
});
Try to adapt your code depending on the result of your alerts

request.getParameter("pgIndex") always returns null in the servlet

I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.So I put System.out.print() at every major sections and finally found out that the request.getParameter("pgIndex") is always returns null.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pgIndex");
//whether pgIndex=1 or pgIndex=2 in the url, always returns null as the output.
System.out.println("pg - " + sPageIndex);
pageIndex = sPageIndex == null ? 1 : Integer.parseInt(sPageIndex);
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
Criteria criteriaCount = ses.createCriteria(ProductHasSize.class);
criteriaCount.setProjection(Projections.rowCount());
totalNumberOfRecords = (int) (long) (Long) criteriaCount.uniqueResult();
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pgIndex=" + j;
String active = j == pageIndex ? "active" : "";
s2 = s2 + "<li class='" + active + "'>" + j + "</li>";
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"d1\":\"" + s1 + "\",\"d2\":\"" + s2 + "\"}]");
products.jsp
<div class="row">
<div class="col-md-12">
<ul class="pagination" id="pagId"></ul>
</div>
</div>
JavaScript
$(document).ready(function () {
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
UPDATE :
$(document).on("click", "#pagId a", function (event) {
//tried with adding another function . But still returns null.
event.preventDefault();
var para = $(this).attr('href').match(/\d+/);
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
data: {pgIndex: para},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
Thanks in advance.
In sending JSON data, you will not simply receive it as request parameter. Instead, just add "normal" parameter:
Sending as HTTP POST
$.ajax({
url: 'AdimnProductFilterAction',
type: 'POST',
data: {
'pgIndex': para
},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
Or as HTTP GET
$.ajax({
url: 'AdimnProductFilterAction?pgIndex='+para,
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
To add parameter into your servlet call.

JS Alert or append is not working on DOM

Please look at this code on https://jsfiddle.net/safron6/9g98j68g/embedded/result/
I am trying to get the calculated result from the list of APIS and JSON code that is generated to show the precipIntensity. At the end of the code there is an alert and the code works in firebug but nothing is showing up. What may be the reason why the alert does not pop up?
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
});
totalPrecipSinceDate did not declared.
I can't access your hosted data source.
Replacing your current $.getJSON call with an $.ajax call should work:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.ajax({
type: 'GET',
url: darkForecastAPI,
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain") {
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
},
error: function(){
alert('failure');
}
});
});

JSONP callback error: Property 'insertFilmData' of object [object Object] is not a function

I Have 3 nested $.ajax calls using JSONP, the first $.ajax calls work in the function but the third fails to execute the call back giving me this error: Uncaught TypeError: Property 'insertFilmData' of object [object Object] is not a function
CODE:
function searchFilms(film, settings) {
if (film === '') {
console.log("enter a movie");
} else {
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/configuration?api_key=XXX',
async: false,
jsonpCallback: 'getSearchResults',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json.images) {
settings.imageData = json.images;
getSearchResults(json, settings);
}
}
});
function getSearchResults(data, settings) {
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/search/movie?api_key=XXX&query=' + film,
async: false,
jsonpCallback: 'deliverResults',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json.total_results !== 0) {
deliverResults(json, settings);
}
}
});
function deliverResults(data, settings) {
var results = data.results;
var html = "<ul id='film-search-results' data-role='listview' data-inset='true'>";
for (var i = 0; i < results.length; i++) {
var result = results[i];
var filmId = result.id;
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/movie/' + filmId + '?api_key=XXX&append_to_response=' + settings.extras,
async: false,
jsonpCallback: 'insertFilmData',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json) {
settings.html = html;
insertFilmData(json, settings);
}
}
});
function insertFilmData(data, settings) {
var poster_base_url = settings.imageData.base_url;
var poster_size = settings.imageData.poster_sizes[0];
var poster_filepath = data.poster_path;
var poster_url = poster_base_url + poster_size + "/" + poster_filepath;
var html = settings.html + "<li><img src='" + poster_url + "' alt='Poster' /><a class='ui-link-inherit'><h3 class='ui-li-heading'>" + data.title + "</h3><p class='ui-li-desc'><strong>" + data.tagline + "</strong></p><p class='ui-li-desc'>" + data.overview + "</p></a></li>";
}
}
html = html + "</ul>";
console.log(html);
$('#content-add-title').html(html);
$('#film-search-results').trigger("create");
}
}
}
}
I'm pretty new to using JSONP for cross domain calls so i'm not sure what's going wrong seeing as the first two call backs fire and it's only the last one that doesn't. any help or direction would be greatly appreciated. Thanks
It's looking for a method called insertFilmData and can't find it. Presumably it will work if you define the function to be a method of the object which is a parameter to the ajax call, ie:
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/movie/' + filmId + '?api_key=XXX&append_to_response=' + settings.extras,
async: false,
jsonpCallback: 'insertFilmData',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json) {
settings.html = html;
insertFilmData(json, settings);
}
},
insertFilmData: function(data, settings) {
var poster_base_url = settings.imageData.base_url;
var poster_size = settings.imageData.poster_sizes[0];
var poster_filepath = data.poster_path;
var poster_url = poster_base_url + poster_size + "/" + poster_filepath;
var html = settings.html + "<li><img src='" + poster_url + "' alt='Poster' /><a class='ui-link-inherit'><h3 class='ui-li-heading'>" + data.title + "</h3><p class='ui-li-desc'><strong>" + data.tagline + "</strong></p><p class='ui-li-desc'>" + data.overview + "</p></a></li>";
}
});
Alternatively, you could just keep it as it is now, but change the line jsonpCallback: 'insertFilmData', to jsonpCallback: insertFilmData,. This will mean one of the arguments to the ajax call will be the function itself, not the name of the function. (And if I understand this correctly, it doesn't matter that the function definition is below this line, because it's a named function and it's in scope.)

Help passing variables between functions in ajax callbacks

OK I am building something that makes an ajax request to one server where it determines the url it needs to then make a new ajax request to another place. Everything is progressing thanks to all the help at SO =) .. however I am stuck again. I am struggling with getting the variables to return to the different functions as I need. The second (jsonp) request returns a json function which looks like :
jsonResponse(
{"it.exists":"1"},"");
and my code...
var img = "null";
var z = "null";
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
$(data).find("ITEM").each(function()
{
query = $("SKU", this).text();
query = 'http://domain.com/' + query + '?req=exists,json';
img = $("SKU", this).text();
img = '<img src="http://domain.com/' + img + '">';
var date =$("LAST_SCAN" , this).text();
$.ajax({
url: query,
dataType: 'jsonp'
});
$("table").append('<tr>'+'<td>' + (date) + '</td>' + '<td>' + (z) + '</td>');
});
}
});
});
// function required to interpret jsonp
function jsonResponse(response){
var x = response["it.exists"];
// console.log(x);
if (x == 0) {
console.log("NO");
var z = "NO IMG";
}
if (x == 1) {
console.log(img);
//this only returns the first image path from the loop of the parseXml function over and over
var z = (img);
}
return z;
}
So I guess my problem is a two parter.. one how do I get the img variable to loop into that if statement and then once that works how can I return that z variable to be used in the first xml parser?
Try this synchronous approach:
var itemQueue = [];
$(document).ready(function ()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
itemQueue= $(data).find("ITEM").map(function ()
{
return {
sku: $("SKU", this).text(),
date: $("LAST_SCAN", this).text()
};
}).get();
getNextItem();
}
});
});
function getNextItem()
{
var item = itemQueue[0];
var query = "http://domain.com/" + item.sku + "?req=exists,json";
$.ajax({
url: query,
dataType: 'jsonp'
});
}
function jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
var x = response["it.exists"];
var z = x == "0" ? "NO IMG" : "<img src=\"http://domain.com/" + item.sku + "\">";
$("table").append("<tr><td>" + item.date + "</td><td>" + z + "</td>");
}
Store 'date' in a global variable, and move the logic to append HTML elements into the jsonResponse function. You cannot return control flow from jsonResponse because it's called asynchronously, but you can continue doing anything you'd like from that function.

Categories

Resources