JS Alert or append is not working on DOM - javascript

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');
}
});
});

Related

how to convert parameter string as column or known object in bootstrap datatable in javascript

in javascript file:
```
function onSearch(filter, data, parameter) {
this.filter = filter;
var row = 1;
$.ajax({
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url,
cache: false,
success: function (msg) {
var json = JSON.parse(msg.d);
var html = "";
$.each(json, function (index, obj) {
//html += ""
// + "" + row.toString() + ""
// + "" + obj.Material_No + ""
// + "" + obj.Material_Name + ""
// + "";
html += parameter;
row++;
});
var table = $('#tbDetails').DataTable();
table.destroy();
$("#tbDetails tbody").html(html);
$('#tbDetails').DataTable({
"destroy": true,
"order": [[0, "asc"]]
});
$('#myModal-1').modal('toggle');
},
error: function (e) {
alert(e.responseText);
}
});
return false;
};
```
in html file :
```
var parameter = ""
+ "" + row.toString() + ""
+ "" + obj.Material_No + ""
+ "" + obj.Material_Name + ""
+ "";
onSearch(filter, data, parameter);
```
Please help, i want to the variable parameter to known object, as i comment code before
You want to tell onSearch how to format the data that it fetches, but you can't reference row and obj directly since they're not available until the network call completes. What you're looking for is a callback function. You're actually already using callbacks - you pass a callback function as the second argument to $.each, and the success parameter of $.ajax.
You'll need to change onSearch to accept a callback function as the third parameter, and then pass it when you call onSearch, something like:
function onSearch(filter, data, callback) {
// ...
$.ajax({
// ...
success: function (msg) {
var json = JSON.parse(msg.d);
var html = callback(json);
// ...
},
});
}
onSearch(filter, data, function (json) {
var html = "";
$.each(json, function (index, obj) {
html += ""
+ "" + obj.toString() + ""
+ "" + obj.Material_No + ""
+ "" + obj.Material_Name + ""
+ "";
});
return html;
});
There's no variable named row, so I'm assuming that should be obj. You may need to edit accordingly.

Trouble printing JSON objects to HTML with javascript

I have the following ajax code to handle the ajax request of a search form.
$(document).ready(function() {
$('#alert-message-warning').hide();
$('.shadow-z-1').hide();
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('#csrf').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
console.log(Object.keys(data).length);
console.log(data);
var cha = Object.keys(data).length;
if (cha > 0) {
$('.shadow-z-1').show();
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data.start + "</td><td>"+ data.end + "</td><td>" + data.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
else{
$('#alert-message-warning').show();
$("#alert-message-warning").fadeTo(2000, 5000).slideUp(5000, function(){
$("#alert-message-warning").slideUp(5000);
});
}
}
});
});
});
If required parameters are selected and submitted results are given in JSON Objects. e.g 5 objects but the java script code prints all the rows of the db table (all 10 rows). What wrong am I doing here ?
Detailed JSON objects
What you're getting is an array of objects. So access your object you have to go to that index and get the object.
eg : data[0].start
Or you can use for loop.
for(let i in data) {
console.log(data[i].start + "\t" + data[i].end);
}
$(document).ready(function() {
$('#alert-message-warning').hide();
$('.shadow-z-1').hide();
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('#csrf').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
console.log(Object.keys(data).length);
console.log(data);
var cha = Object.keys(data).length;
$('.shadow-z-1').show();
if (cha > 0) {
for (var i = 0; i < data.length; i++) {
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data[i].start + "</td><td>"+ data[i].end + "</td><td>" + data[i].end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
}
else{
$('#alert-message-warning').show();
$("#alert-message-warning").fadeTo(2000, 5000).slideUp(5000, function(){
$("#alert-message-warning").slideUp(5000);
});
}
}
});
});
});
You just need to loop through your data.
The variable data is the entire Json object, you need to iterate through this object and append each of the objects.
data.foreach(function(obj) {
$('.shadow-z-1').append("<tr class='liquid-row><td>" + obj.start + "</td><td>"+ obj.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
} )
This way you're iterating and appending the results.
On a new Ajax call you may want to remove everything so you don't mix results from different calls.
Hope this helps

JSON callfunction doesn't fire

here is my example
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false";
$.getJSON(url, function (data) {
alert("inside json");
//console.log(data);
$.each(data.results[0], function (i, inside) {
console.log(i);
});
//var addr = data.results[0].geometry.location.lat;
});
now i realized that the call function doesn't fire at all....i read other post here and they say that it happens when JSON is not in valid format but here i am getting JSON from Google API so i hope its in valid format.... JSON is here
http://maps.googleapis.com/maps/api/geocode/json?latlng=27.88,78.08&sensor=false
can you please give your comments on this? or may be i am making some mistakes
Maybe try a full ajax call:
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false",
data: {},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
for (var i = 0; i < Result.d.length; i++) {
element = Result.d[i];
console.log(element);
};
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
can you add it to
$(document).ready(function(){
});
for example:
$(document).ready(function () {
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false";
$.getJSON(url, function (data) {
alert("inside json");
//console.log(data);
$.each(data.results[0], function (i, inside) {
console.log(i);
});
//var addr = data.results[0].geometry.location.lat;
});
});

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