I edit some code jquery weather , and when I add some Response Fields not all Fields clear result I have undefined result conditions .
Example : Max. temp: 42C / 108F Min. temp: 27C / 80F wind : undefined
$(function() { var handlers = {
simplePrint : function (location){
var new_location_div = $('<div>');
new_location_div.addClass('location');
new_location_div.data('l',location.l);
new_location_div.data('city',location.name);
var location_p = $('<p>').text(location.name)
new_location_div.append(location_p);
$('#search_result').append(new_location_div);
},
displayPrint : function (location,day){
var display = $('<div>');
display.addClass('display_on')
location = $('<p>').text('Location: ' + location);
high_temp = $('<p>').text('Max. temp: ' + day.high.celsius + 'C / ' + day.high.fahrenheit + 'F');
min_temp = $('<p>').text('Min. temp: ' + day.low.celsius + 'C / ' + day.low.fahrenheit + 'F');
wind_dir = $('<p>').text(' ' + day.wind_dir +' ');
display.append(location,high_temp,min_temp,wind_dir);
// "Thunderstorm" "Chance of Rain" "Overcast" "Partly Cloudy" "Rain" "Clear"
$('#display_today').slideUp('slow');
var condition = ['clear', 'sunny'].indexOf(day.conditions.toLowerCase())
if (condition === -1 ) {
$('body').fadeTo('slow', 0, function()
{
$(this).css('background-image', 'url("http://harrymoroz.com/wp-content/uploads/2014/04/1_See_It.jpg")');
}).fadeTo('slow', 1);
$('h1').css({'color': 'white'});
$('.starter-template > p').css({'color': 'white'});
}else{
$('body').fadeTo('slow', 0, function()
{
$(this).css('background-image', 'url("https://melodywren.files.wordpress.com/2011/04/p1040585.jpg")');
}).fadeTo('slow', 1);
$('h1').css({'color': 'rgb(#333)'});
$('p').css({'color': 'rgb(#333)'});
};
setTimeout(function(){
$('.display_on').remove();
$('#display_today').append(display);
$('#display_today').slideDown('400');
}, '800'); } } $('#search_form_submit').on('click keypress', function(event) {
event.preventDefault();
var search_query = $('#search_field').val();
if (!search_query) {
$('.location').remove();
return;
};
$.ajax({
url: 'http://autocomplete.wunderground.com/aq?query=' + search_query ,
type: 'GET',
dataType: 'jsonp',
jsonp: 'cb',
})
.done(function(search_api_answer) {
$('.location').remove();
search_api_answer.RESULTS.filter(function(location){
return location.type === 'city'
}).forEach(handlers.simplePrint);
});
$('#search_form').trigger("reset");
});$('#search_result').on('click', '.location', function(event) {
event.preventDefault();
var selected_location = $(this)
var lCode = selected_location.data('l');
$.ajax({
url: 'http://api.wunderground.com/api/0ce1c4a981f7dd2a/conditions/forecast/q/'+ lCode + '.json',
type: 'GET',
dataType: 'json',
// jsonp: 'cb',
})
.done(function(api_city_forecast,conditions) {
todayForecast = api_city_forecast.forecast.simpleforecast.forecastday[0];
cityForecast = selected_location.data('city');
conditions = conditions.current_observation;
handlers.displayPrint(cityForecast,todayForecast,conditions);});});});
Looking at the result of:
http://api.wunderground.com/api/0ce1c4a981f7dd2a/conditions/forecast/q/kzn.json
it seems that some items, like the "day" variable, may not always be filled out how like you expect. Specifically, the "day" variable in that JSON response has no "high" or "low" attribute -- it simply has a valuel.
You might want to make your app cater for this condition, ie when weatherunderground doesn't know all values for a query, but provides a base value.
Related
I created an ajax function that returns my items Price by fetching from my DB. I'm sure there isn't any problem with my php but sometimes I get the same result twice!
jQuery
$('.removemore___').click(function(e) {
var item_id = $(this).attr('data-item');
var col_id = $(this).attr('data-col');
var value = $(this).attr('data-value');
if ($(this).attr('data-trash') == 'trash') {
newPopuper('alert_sure__', 'flex', 'blackScreen');
$('.__aggtoyes').attr('data-item', item_id);
$('.__aggtoyes').attr('data-col', col_id);
$('.__aggtoyes').attr('data-value', value);
} else {
$.ajax({
type: "POST",
url: "includes/chekavailableitem.php?remove",
data: {
item_id: item_id,
col_id: col_id,
value: value
},
dataType: "text",
success: function(response) {
var iNum = parseInt(value);
iNum--;
if (response == 'done') {
$('.value__cart[data-item=' + item_id + '][data-col=' + col_id + ']').html(iNum);
$('.removemore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
$('.addmore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
if (iNum == 1) {
location.reload();
}
} else if (response == 'deleted') {
location.reload();
}
},
error: function() {
$('#wrong-signup').html(': 102');
},
timeout: 5000
});
}
$.ajax({
type: "POST",
url: "includes/get_finalize_cart.php",
data: {},
cache: false,
async: true,
dataType: "json",
success: function(response) {
// var final_price = $.parseJSON(response)
console.log(response);
if (response[0] == 'done') {
$('.final_price__').html(response[1] + ' <span style="font-size: .786rem;font-weight: 400">تومان</span>');
} else {
}
},
error: function() {
$('#wrong-signup').html(': 101');
},
timeout: 5000
});
e.stopImmediatePropagation();
return false;
});
Here is full function in jQuery
<?php
include 'db.php';
include 'function.php';
$user_id = extractUserId();
$chekcart = "SELECT * FROM `box` WHERE `user_id`='$user_id'";
$result_cox_cart_cheker = connectANDdie($chekcart);
$sum_price = 0;
while($row_items = mysqli_fetch_assoc($result_cox_cart_cheker)){
$price = $row_items['item_price'];
$value = $row_items['value'];
$sum_price = $sum_price + ( $price*$value );
$final_value = number_format($sum_price);
$result = ['done',$final_value];
$result1 = json_encode($result);
echo $result1;
}
and I'll also show a screenshot from console page so you can see what my result is:
You're not waiting for chekavailableitem.php?remove to complete before you call get_finalize_cart.php. Since AJAX is asynchronous, the latter might be processed first, so you'll get a duplicate of the old value.
You should put the second $.ajax() call in the sucess: function of the first $.ajax() call, or use a promise.
i want to check whether is a valid item or not before saving the values. then i create java-script function to check validation and return result. but the problem is this function returns before validate items, the always true the condition above if condition. my code is below. could anyone help me please?
this is series of ajax call and i'm not aware of how to use callback for this..
if(IsValidItems() != ''){
//Do something
}
function IsValidItems() {
var IsvalidStatus = '';
var lineqty = 0;
var LineNumber = -1;
var allRowData = jQuery("#tblJQGrid").jqGrid("getRowData");
for (var i = 0; i < allRowData.length - 1; i++) {
if (allRowData[i].BulkItem != "False") {
if (allRowData[i].quantity != '') {
lineqty = parseInt(allRowData[i].quantity);
LineNumber = i + 1;
var postURL = "/BookingDetail/GetItemAvailablity?ItemCode=" + allRowData[i].itemCode + "&StartDate=" + allRowData[i].StartDate + "&EndDate=" + allRowData[i].EndDate + "&srno=" + allRowData[i].srno + "&locationID=" + allRowData[i].Location;
$.ajax({
url: postURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "",
type: "POST",
async: true,
dataFilter: function (data) {
return data;
},
success: function (result) {
if (lineqty > parseInt(result)) {
IsvalidStatus = IsvalidStatus + "," + LineNumber;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
}
}
}
return IsvalidStatus;
}
I'm having a problem with the way I save information in ajax with alert, I made it using confirm in JQuery but the button text can't be changed I so decided to make my own dialog box so I can modify the buttons, but the problem is the data saves before I click the save button.
function saveEdit(e) {
var result = '';
var item = $('input[name=username]').val();
$.ajax({
url: root + 'ccards/getAllDetails',
data: {
item: item
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var hour = dateObj.getUTCHours()
var minute = dateObj.getUTCMinutes();
var second = dateObj.getUTCSeconds();
var datetoday = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
var selected_date = Date.parse(data.modified);
var today = Date.parse(datetoday);
var d = new Date(data.modified);
var h = d.getHours();
var m = d.getMinutes();
var username = data.username.toUpperCase();
var coreuser = data.core_user.username.toUpperCase();
var hr = '';
var time = '';
if (h <= '12') {
hr = h;
time = hr + ":" + m + " AM";
} else {
hr = h - 12;
time = hr + ":" + m + " PM";
}
if (Math.abs(today - selected_date) <= 60 * 60 * 24 * 1000) {
$('#confirmSave').show().dialog({
height: 200,
width: 500,
zIndex: 10,
modal: true,
resizable: false
});
$('#time').html(time);
$('#coreuser').html(coreuser);
if ($('#confirmSave button[name=submit]').data('clicked')) {
result = true;
} else if ($('#confirmSave button[name=cancel]').data('clicked')) {
result = false;
}
}
}
});
return result;
}
$('.clientForm').submit(function(event) {
var form = this;
console.log(form);
if ($("input[name='action']", form).val() == 'save' || $("input[name='action']", form).val() == 'savenew' || $("input[name='action']", form).val() == 'login') {
if ((!validate_email(form)) || (!validate(form))) {
mode = 'edit';
setMode(mode);
return false;
}
}
var save = saveEdit();
if (save == true) {
var dt = $(this).serializeArray();
var action = root + $("input[name='module']", form).val() + $("input[name='method']", form).val();
$('.fields', this).slideUp('fast');
$('.response', this).html("<div class='load'>Processing, please wait...</div>");
$.ajax({
type: 'POST',
url: action,
data: dt,
dataType: 'json',
success: function(data) {
if (data) procJSON.init(data, form);
},
complete: function(data) {
},
error: function(data) {
onError(data);
}
});
}
return false;
});
I recently used the noty plugin, alongside jQuery's deferred to solve a similar problem.
First, a function to show the confirm dialog and return a promise-like object, which resolves to true if the Ok button is pressed, or false if the Cancel button is pressed.
function showConfirm(msg) {
var dfd = $.Deferred();
noty({
text: msg,
type: 'confirm',
dismissQueue: false,
layout: 'center',
theme: 'defaultTheme',
modal: true,
buttons:
[{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: $noty => {
$noty.close();
dfd.resolve(true);
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: $noty => {
$noty.close();
dfd.resolve(false);
}
}]
});
return dfd.promise();
}
Then you can do something like...
$('.clientForm').submit(function(event) {
showConfirm("Do you wish to save?").then(function(confirmed) {
if (!confirmed) {
return;
}
// make ajax request here
}
}
I am using AJAX to get the data and make them into an array like below:
function drawDate(username, date, device, token){
$.ajax({
type: 'GET',
url: dsu + "dataPoints/" + getDatapointId(username, date, device),
headers: {
"Authorization": "Bearer " + token
},
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
return [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
return location_events
}
},
error: function(data){
console.log('Data did not have any locations.')
}
});
}
Then when I tried to call that function, it returned "undefined". I actually want to put that array into FullCalendar like below:
$(document).ready(function() {
var today = moment();
var token = url("#access_token");
$.getJSON(dsu + "oauth/check_token?token=" + token)
.done(function(data) {
var username = data["user_name"];
var device = 'android';
var date = url("#date")? moment(url("#date")).toDate() : new Date();
var redraw = function(){
var test = drawDate(username, moment(date).format('YYYY-MM-DD'), device, token);
console.log(test); //***** Here! I tried to make the return of the function into a variable but it returned "undefined"
};
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: test, //******* I want to the array to be rendered here.
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
})
.fail(function() {
console.log("Fail!");
});
I read most of the similar questions and it seems that I should use callback function but I don't really understand how to use them.
Thank you very much! Any help is welcome!
The problem is that you do AJAX request which is asynchronous and you cannot return this data from drawDate() function. You need to do what you need with data retrieved from server in your 'success' callback. Like following:
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
location_events = [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
}
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: location_events,
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
}
I have a javascript function which generates JSON data at every certain second and then PUT it to a cloud server. Now I don't want to POST in realtime, rather I want to log this data in a buffer and say after n number of data log I will PUT to cloud. For example I want to log 50 data point in 10 second and then with timestamp I will PUT to a server
Now JSON data is passed through var fromDatan. JSON data format is
{"value":"-2.1282838391939194"}
Now the code is:
var acc;
var watchID = null;
function startWatch() {
//set frequency of accelerometer update.1000 = 1 second
var options = { frequency: 1000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
//DISPLAY ACCELERATION DATA
function onSuccess(acceleration) {
acc = acceleration;
var element = document.getElementById("accelerometer");
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
datalock();
}
function postdata () {
var accx = acc.x;
alert(accx);
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
//POST JSON DATA
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9asdedqedqxdqd7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
}
function datalock(){
alert("Entering");
fromData.push({
value: accx.toString(),
});
if (fromData.length >= 10) {
postdata ();
};
var fromData;
}
It is not working, although all other things are correct, the pushing I couldn't implement properly. Can anyone please help me out?
EDIT START
Try this:
var fromData = [];
var jsonCounter = 0;
function postdata () {
var accx = acc.x;
alert(accx);
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9asdedqedqxdqd7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
}
function datalock(){
alert("Entering");
fromData.push({
value: accx.toString(),
});
jsonCounter++;
// post only after 10 entries
if (jsonCounter >= 10) {
postdata ();
jsonCounter = 0; // reset
};
}
EDIT END
Since JSON object does not have a length property, you can do it by using a variable.
Example:
var formdata;
var jsonCounter = 0;
function datalock(){
alert("Entering");
fromData.push({
value: accx.toString(),
});
jsonCounter++;
// post only after 50 entries
if (jsonCounter >= 50) {
postdata ();
jsonCounter = 0; // reset
};
//var fromData; // make it global as it is used in other function.
}
This is my code so far after modifying it as per suggestion from #web-nomad
function postdata () {
var accx = acc.x;
alert(accx);
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
//POST JSON SENSOR DATA
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9e259asdasd6a7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
//var fromData = {};
}
var fromData = [];
var jsonCounter = 0;
//Edit start
function datalock() {
alert("Entering");
//alert(jsonCounter); //It was showing me only count as 0
fromData.push({
value: accx.toString(),
});
alert(JSON.stringify(fromData));// no alert
jsonCounter++;
alert(jsonCounter); //The alert was not coming at all, when I tried this one
// post only after 10 entries
if (jsonCounter >= 10) {
postdata ();
jsonCounter = 0; // reset
};
}
//Edit End
This is the change after your suggestion given #web-nomad