I want to check if its the first app start. I run my app via xcode on my iphone on usb. But everytime i close the app on iphone and start it again with clicking the icon on my phone - like a restart - it dont recognize that the app was startet before. What i am doing wrong?
$(document).ready( function() {
if (localStorage.getItem("applaunch")) {
window.localStorage.getItem("callstatus");
}else{
//Local storage is not set, hence first time launch. set the local storage item
window.localStorage.setItem('applaunch',1);
window.localStorage.setItem("vipstatus", "0");
window.localStorage.setItem("callstatus", "0");
}
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxxxxxxxxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid.toUpperCase();
}
window.localStorage.setItem("username",generateUUID());
var username = window.localStorage.getItem("username");
var vipstatus = window.localStorage.getItem("vipstatus");
var callstatus = window.localStorage.getItem("callstatus");
$.ajax({
type: 'post',
url: 'http://www.bla.com/action.php',
data: {
data: {"username": username, "vipstatus" : vipstatus, "callstatus" : callstatus},
},
success: function(result) {
console.log(result);
}
});
});
Everytime i restart the app on the phone (NOT VIA XCODE BUILDING AGAIN) its making a new entry in my db - see ajax.
Set a variable that says whether it's the first time. Then only make the AJAX call when the variable is true.
$(document).ready( function() {
var first_time;
if (localStorage.getItem("applaunch")) {
first_time = false;
}else{
//Local storage is not set, hence first time launch. set the local storage item
window.localStorage.setItem('applaunch',1);
window.localStorage.setItem("vipstatus", "0");
window.localStorage.setItem("callstatus", "0");
first_time = true;
}
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxxxxxxxxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid.toUpperCase();
}
if (first_time) {
window.localStorage.setItem("username",generateUUID());
}
var username = window.localStorage.getItem("username");
var vipstatus = window.localStorage.getItem("vipstatus");
var callstatus = window.localStorage.getItem("callstatus");
if (first_time) {
$.ajax({
type: 'post',
url: 'http://www.bla.com/action.php',
data: {
data: {"username": username, "vipstatus" : vipstatus, "callstatus" : callstatus},
},
success: function(result) {
console.log(result);
}
});
}
});
Related
I have logic where i am trying to add host url dynamically so it work in all env based on hosst, so below trying to find a file that is there in host but its never going into $.each statement , if call url directly http://18.35.168.87:6000/Sdk/wrapper-sdk/client/out.json it worked and rendered data, any idea what could have wrong in below code to achieve this task ?
main.js
function myFunction(val) {
var url = "../../wrapper-sdk/" + client + "/out.json";
if (window.location.hostname.indexOf("localhost") !== -1 ||
window.location.host.indexOf("localhost") !== -1) {
var scripts = document.getElementsByTagName('script');
var host = '';
$.each(scripts, function (idx, item) {
if (item.src.indexOf('Sdk/wrapper-sdk') !== -1 && (item.src.indexOf('out.json') !== -1)) {
host = item.src.split('?')[0];
host = host.replace('wrapper-sdk/' + client + '/out.json', '');
}
});
url = url.replace('../../', host);
}
$.ajax({
url: url + "?no_cache=" + new Date().getTime(),
dataType: "json",
"async": false,
success: function (data) {
console.log(data);
},
error: function () {
console.log('error while accessing api.json.')
}
});
}
I would suggest breaking up some of your checks into their own function. Makes it just a bit easier to follow the logic.
function validIp(str) {
var parts = str.split(".");
var result = true;
$.each(parts, function(i, p) {
if (parseInt(p) > 0 && parseInt(p) < 255) {
result = result && true;
}
});
return result;
}
function checkLocalUrl(str) {
var result = 0;
if (str.indexOf("localhost") >= 0) {
result = 1;
}
if (validIp(str)) {
result = -1;
}
/*
0 = Some Domain or Host Name, not LocalHost
1 = LocalHost
-1 = IP Address
*/
return result;
}
function changeSources(client) {
if (checkLocalUrl(window.location.hostname) || checkLocalUrl(window.location.host) {
var scripts = $("script");
var host = '';
scripts.each(function(i, el) {
var src = $(el).attr("src");
var nUrl = new URL(src);
var pro = nUrl.protocol;
var hn = nUrl.hostname;
if (nUrl.pathname.indexOf('/Sdk/wrapper-sdk') == 0 && nUrl.pathname.indexOf('out.json') > 0) {
host = pro + "://" + hn + "/wrapper-sdk/" + client + "/out.json";
}
$.ajax({
url: host
data: { no_cache: new Date().getTime() },
dataType: "json",
async: false,
success: function(data) {
console.log(data);
},
error: function() {
console.log('error while accessing api.json.')
}
});
});
}
}
}
See also: new URL()
You can send a string to checkLocalUrl() and it will return 1 or true if it's potentially a localhost URL. It will return 0 or false if it's any other domain pattern or -1 or false if it's an IP address.
In changeSources() we can use this to check for local urls and perform the AJAX you defined.
I'm using the code below to get a date value from a jQuery datepicker.
function GetViewModelData() {
var actionViewModel = [];
var rowCount = $('#myDynamicTable tbody tr').length;
var actionDate;
for (i = 1; i <= rowCount; i++) {
actionDate = document.getElementsByClassName("txtDateOfAction")[i - 1].value;
var parts = actionDate.split("/");
var dt = new Date(parseInt(parts[2], 10), parseInt(parts[1], 10) - 1, parseInt(parts[0], 10));
var rdtViewModel = new DetailsViewModel(0, dt);
actionViewModel.push(rdtViewModel);
}
var obj = new ReportViewModel(0, actionViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I'm then using the code below to send my value to an SQL server database.
var SubmitData = function() {
$(".btnSave").click(function() {
Loader();
var viewmodel = GetViewModelData();
var actionCode = $.trim($("#actionCode").val()).toLowerCase();
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Submission/Save',
success: function(data) {
$("#divMaster").html(data);
return false;
},
error: function(e) {
alert("An error occured");
return false;
}
});
});
}
The problem i'm facing is that if the client and the server are in different time zones, the date value the client selected is reduced by 1 when being saved on the server.
For example, if the client selects 19/01/2017, it is saved as 18/01/2017 on the server (in the database).
If the client is in the same time zone as the server, every things works fine.
How can resolve this issue?
I'm trying to send a drone a new set of coordinates every 1/2 of a second. Right now, it's not working the way I planned on it working (aka it's not working at all). I have 90 different Lat, Long, and Alt coordinates all predetermined inside my .js file. They are listed like this-
setTimeout(function () {long_in=-74.61122515230907;lat_in=41.05861743700108;alt_in=10}, 5000);
setTimeout(function () {long_in=-74.61124258212661;lat_in=41.05864962647036;alt_in=10}, 10000);
setTimeout(function () {long_in=-74.61125021662482;lat_in=41.05867214783328;alt_in=10}, 15000);
and so on...
Then they will need to pass thru this function -
if (coordinate == "GPS") {
console.log("GPS go");
lat_out = lat_in;
long_out = long_in;
alt_out = alt_in;
console.log(lat_out, long_out, alt_out)
}
And finally it will send this command to the drone-
var msgdata = {};
msgdata["twist"] = {};
msgdata.twist["twist"] = {};
msgdata.twist.twist["linear"] = {};
msgdata.twist.twist.linear["x"] = lat_out;
msgdata.twist.twist.linear["y"] = long_out;
msgdata.twist.twist.linear["z"] = alt_out;
msgdata.twist.twist["angular"] = {};
msgdata.twist.twist.angular["z"] = 1.00;
msgdata["tolerance"] = 2.00;
msgdata["async"] = true;
msgdata["relative"] = false;
msgdata["yaw_valid"] = true;
msgdata["body_frame"] = false;
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(msgdata),
url: "http://" + ip + "/ros/" + namespace + "/navigation/position_set",
success: function (data) {
console.log(data, "Coordinates sent", lat_out,long_out,alt_out);
}
});
I have defined all of my variables prior to this code globally. All of the commands work perfectly fine, I just can't get them to all refresh every 1/2 of a second. Do I need to have all of these commands inside every setTimeout or something? Thanks for the help.
Yes you need to make the call again and again. You could wrap it in a function and make the call happen again and again from the setTimeout.
I have created a callback chain to guarantee order of execution based on #Liam's recommendation and the comments discussion.
setTimeout(function() {
long_in = -74.61122515230907;
lat_in = 41.05861743700108;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in, function() {
setTimeout(function() {
long_in = -74.61124258212661;
lat_in = 41.05864962647036;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in, function() {
setTimeout(function() {
long_in = -74.61125021662482;
lat_in = 41.05867214783328;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in);
}, 5000);
});
}, 5000);
});
}, 5000);
var coordinate = "GPS";
function prepSignal(long_in, lat_in, alt_in, callback) {
if (coordinate == "GPS") {
console.log("GPS go");
lat_out = lat_in;
long_out = long_in;
alt_out = alt_in;
console.log(lat_out, long_out, alt_out, callback);
sendSignal(long_in, lat_in, alt_in, callback);
}
function sendSignal(long_in, lat_in, alt_in, cb) {
var msgdata = {};
msgdata["twist"] = {};
msgdata.twist["twist"] = {};
msgdata.twist.twist["linear"] = {};
msgdata.twist.twist.linear["x"] = lat_out;
msgdata.twist.twist.linear["y"] = long_out;
msgdata.twist.twist.linear["z"] = alt_out;
msgdata.twist.twist["angular"] = {};
msgdata.twist.twist.angular["z"] = 1.00;
msgdata["tolerance"] = 2.00;
msgdata["async"] = true;
msgdata["relative"] = false;
msgdata["yaw_valid"] = true;
msgdata["body_frame"] = false;
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(msgdata),
url: "http://" + ip + "/ros/" + namespace + "/navigation/position_set",
success: function(data) {
console.log(data, "Coordinates sent", lat_out, long_out, alt_out);
if(cb && typeof cb == "function") {
cb();
}
}
});
}
}
You have to run recalculation inside setTimeout after you set a value.
I am using a script to get specified contents of specific links on a webpage and it has worked fine before, but after the site changed to https, it has stopped working.
The script is as follows:
var URL = window.location.origin
var episodeLinks = $('table.listing a').map(function(i,el) { return $(el).attr('href'); });
$.ajaxSetup({async:false});
$.getScript("https://kissanime.com/Scripts/asp.js");
var login = "vergo777";
var api_key = "R_6a13f014b38f4f80a31cf7d80a7c18c7";
var long_url;
var startEpisode;
do {
startEpisode = prompt("Enter episode number you want to start from");
if(startEpisode <= 0 || startEpisode > episodeLinks.length) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var endEpisode;
do {
endEpisode = prompt("Enter episode number you want to end at");
if(endEpisode <= 0 || endEpisode > episodeLinks.length || endEpisode < startEpisode) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var videoQuality = prompt("Enter video quality you want to download. Example - '960x720.mp4' (without the quotes)");
var i;
for (i = (episodeLinks.length - startEpisode); i >= (episodeLinks.length - endEpisode); i--) {
jQuery.ajax({
url: URL + episodeLinks[i],
success: function(result) {
var $result = eval($(result));
var stringStart = result.search("var wra");
var stringEnd = result.search("document.write");
var javascriptToExecute = result.substring(stringStart, stringEnd);
eval(javascriptToExecute);
$("body").append('<div id="episode' + i + '" style="display: none;"></div>')
$('#episode' + i).append(wra);
var downloadQualityOptions = $('#episode' + i + ' a').map(function(i,el) { return $(el); });
var j;
for(j = 0; j < downloadQualityOptions.length; j++) {
if(videoQuality === downloadQualityOptions[j].html()) {
long_url = downloadQualityOptions[j].attr('href');
console.log(i);
get_short_url(long_url, login, api_key);
}
}
},
async: false,
script: true
});
}
function get_short_url(long_url, login, api_key)
{
$.getJSON(
"http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url,
async: true
},
function(response)
{
console.log(response.data.url);
}
);
}
I am getting the error: Uncaught ReferenceError: asp is not defined(…)
Any help is very appreciated, thank you!
I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});