Set globa Variables From JSON Variables - javascript

So I have an update function in javascript that get's json variables from a file. I'm using the variables in other functions, and I'm having to call the same file for that function. I'm wanting to set those variables to be global so I won't have to call the file in the other function, Here's the update function:
function XML() {
$.ajax({
type: "GET",
url: "xmlconnect.php",
dataType: "json",
success: function(data) {
for (var i in data) {
var data = data[i];
var level = data[4];
var cash = data[6];
var income = data[7];
var upkeep = data[42];
var total_income = income - upkeep;
var eincome = data[46];
var health = data[10];
var max_health = data[11];
var energy = data[12];
var max_energy = data[13];
var stamina = data[14];
var max_stamina = data[15];
var Exp = data[8];
var max_exp = data[9];
var attack = data[16];
var defense = data[17];
var skill_points = data[24];
var health_width = health / max_health * 100;
var energy_width = energy / max_energy * 100;
var stamina_width = stamina / max_stamina * 100;
var exp_width = Exp / max_exp * 100;
var sess_id = data['sess'];
if(cash < 1000) {
var user_cash = number_format(cash);
}
else {
var user_cash = format(cash);
}
$('#Cash').html('$'+format(user_cash));
$('#Income').html('$'+number_format(total_income));
$('#EIncome').html(number_format(eincome));
$('#LevelText').html(level);
$('#HealthText').html(format(health)+'/'+format(max_health));
$('#EnergyText').html(format(energy)+'/'+format(max_energy));
$('#StaminaText').html(format(stamina)+'/'+format(max_stamina));
$('#ExpText').html(number_format(exp_width)+'%');
$('#HealthWidth').css('width',''+health_width+'%');
$('#EnergyWidth').css('width',''+energy_width+'%');
$('#StaminaWidth').css('width',''+stamina_width+'%');
$('#ExpWidth').css('width',''+exp_width+'%');
$('#Update').load('activity.php');
}
}
});
}
And for instance I need to use a few of those variables in another function called "Increase" And I have it setup like this:
function Increase(Att) {
$.ajax({
type: "GET",
url: "xmlconnect.php",
dataType: "json",
success: function(data) {
for (var i in data) {
var data = data[i];
var max_health = data[11];
var max_energy = data[13];
var max_stamina = data[15];
var attack = data[16];
var defense = data[17];
var skill_points = data[24];
$('#AttResults').load('increase.php?att='+Att);
$('#Skills').html(number_format(skill_points));
$('#Att_attack').html(number_format(attack));
$('#Att_defense').html(number_format(defense));
$('#Att_max_health').html(number_format(max_health));
$('#Att_max_energy').html(number_format(max_energy));
$('#Att_max_stamina').html(number_format(max_stamina));
XML();
}
}
});
}
But I want to make the first XML Function to be global Variables.

As per W3Schools you can simply do:
variable = value;
(yes, without 'var') and it will make it a global variable unless that same name is used in another scope.

Related

Onclick for arrays in JSON

I'm retrieving data through an api, and creating a list using JS. I was wondering if it was possible to create a onclick function for every element in an array element of a JSON. The elements are being displayed, but nothing happens when I click them. Also, is it possible to pass on data in the JSON with this redirection to a new page?
My code is as follows:
var url = "https://api.nytimes.com/svc/movies/v2/reviews/all.json?api-key=b5f6bc931d6e446a998eb063a7c13d8e";
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
success: function (data) {
var data = data;
details(data);
for (var i = 0; i < Object.keys(data.results[0]).length; i++) {
document.getElementById("movlist");
var item = document.createElement('li');
item.className = 'listele';
var itempicdiv = document.createElement('div');
itempicdiv.className = 'picdiv';
var itempic = document.createElement('img');
itempic.className = 'pic';
itempic.src = data.results[i].multimedia.src;
var itemnamediv = document.createElement('div');
itemnamediv.className = 'namediv';
var itemname = document.createTextNode(data.results[i].display_title);
itemname.className = 'name';
itempicdiv.appendChild(itempic);
itemnamediv.appendChild(itemname);
item.appendChild(itempicdiv);
item.appendChild(itemnamediv);
list.appendChild(item);
}
}
}).done(function (result) {
console.log(result);
}).fail(function (err) {
throw err;
});
function details(data) {
for (var j = 0; j < Object.keys(data.results[0]).length; j++) {
var t = data.results[j];
t.onclick = function () {
location.href = 'detail.html';
}
}
}

How to pass the select box value as an array using AJAX from one page to another in PHP?

var message = $("#send_message").val();
var Teaminput = $("#sms_reminder_team").val();
for (var i = 0; i <Teaminput.length; i++)
{
var team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
var members=Memberinput[i];
}
Get 2 varaibles as array members and team
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
How to send both array variables using AJAX from current page to "dir_sendmessage".
Change the below line
var parameter = "message="+message+"&team="+team+"&members="+members;
to
var parameter = "message="+message+"&team="+JSON.stringify(team)+"&members="+JSON.stringify(members);
Edit: Modify like this too
var team = [];
var members = [];
for (var i = 0; i <Teaminput.length; i++)
{
team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
members=Memberinput[i];
}
Note: When you add var in each line in the loop, it will declare a new variable. You have to edit like the above code
After update the code with the JSON.stringify() function, you will be able to get the value as an array in you PHP code
Ajax will not directly pass Jquery array to PHP
First of all ideally you should send in JSON format or use array.tostring() ( can avoid this )
But if you have to send it as array you can try following:
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: {team:team, members: members},
success: function(data) {
document.getElementById('check').innerHTML = data; } });
var message = $("#send_message").val();
var teaminputt = $("#sms_reminder_team").val();
team = new Array();
members = new Array();
for (var i = 0; i <teaminputt.length; i++)
{
var team=teaminputt[i];
}
var memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <memberinput.length; i++)
{
var members=memberinput[i];
}
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
$("#msg-send-btn").click(function() {
var message = $("#send_message").val();
var optionsmembers = $('#sms_reminder_members option:selected');
var members = $.map(optionsmembers ,function(option) {
return option.value;
});
//---- Using $.map get all selcted data as a an Array.
var postData = {
message,
members
}
//---- For Avoid Json-Stringfy.
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage.php',
type: 'POST',
data:{myData:postData},
//----- And It's Work Perfectly.

Count how many times i have the same word

My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):
You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example
Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);
Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);

Synchronous javascript does not work

I have a script which generates an array of audio files to be played on the click of a button. I am trying to use synchronous JS in order to change the values of some global variables and have been testing for changes with alerts but I get 'undefined' as a result (or my popups do not show).
My code:
jQuery.ajaxSetup({async:false});
var s;
var group;
var curr_rec;
var curr_start = 1;
var curr_end;
var curr_s_obj;
var recs;
var sync = new Array();
var sync_group = new Array();
var check_rec;
var check_id;
var check_start;
var check_end;
var loaded = 0;
var s_obj;
function compare(a,b){
if(a.fields.start_time<b.fields.start_time)
return -1;
if(a.fields.start_time>b.fields.start_time)
return 1;
return 0;
}
function process_data(recs){
for(var i=0;i<recs.length;i++){
check_rec = recs[i];
check_id = check_rec.fields.file_ID;
check_start = check_rec.fields.start_time;
check_end = check_rec_fields.end_time;
if((curr_start.getTime() <= check_start.getTime() && check_end.getTime()<= curr_end.getTime()) ||
(curr_start.getTime()>=check_start.getTime() && curr_start.getTime()<=check_end.getTime()) ||
(curr_end.getTime()>=check_start.getTime() && curr_end.getTime()<=check_end.getTime())
)
{
//diff = (check_start.getTime() - curr_start.getTime())/1000;
//check_rec["difference"] = diff;
sync.push(check_rec);
}
}
}
function load_data(sync){
var diff;
var last = sync[sync.length-1];
for(var j=0;j<sync.length-1;j++){
s_obj = new buzz.sound(sync[i].fields.rec_file);
sync_group.push(s_obj);
diff = (last.fields.start_time.getTime() - sync[i].fields.start_time.getTime())/1000;
if(diff>=0){
s_obj.setTime(diff);
}
else{
alert("error");
}
}
loaded = 1;
}
function synchronise(id){
$.ajax({
type:"GET",
url:"/webapp/playSound:" + id,
success: function(data){
curr_rec = eval("(" + data + ")");
curr_start = curr_rec.fields.start_time;
curr_end= curr_rec.fields.end_time;
curr_s_obj = new buzz.sound(curr_rec.fields.rec_file);
});
alert("ggo");
$.ajax(
type:"GET",
url:"/webapp/getRecs",
success: function(data){
recs = eval("("+ data +")");
process_data(recs);
});
alert(curr_start);
sync = sync.sort(compare);
load_data(sync);
var s1 = new buzz.sound( "../../static/data/second_audio.ogg");
s = new buzz.sound( "../../static/data/" + id +".ogg"); //curr_rec.fields.rec_file
/*
sync_group.push(s);
s.setTime(20.5);
sync_group.push(s1);
*/
group = new buzz.group(sync_group);
}
function playS(id){
if(loaded==0)
synchronise(id);
group.togglePlay();
}
function stopS(){
group.stop();
}

How to use a variable as key in json array in javascript

I have following json formate
"[{"tempId":[{"cityName":"London"},{"weather":"overcast clouds"}]}]"
In above format tempId is not a String-value it is a variable.It's value is something like "25Dec2013".But it is inserted as it is mean a name of variable and not a value.
So it should look like
"[{"tempId":[{"25Dec2013":"London"},{"weather":"overcast clouds"}]}]"
I have done following code.I have written one comment in code where the actual problem is.
var arrCityrecordForADay = [];
function getWeatherDataForCities(cityArray, callback) {
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24 * 60 * 60);
for (var i in cityArray) {
for (var j = 1; j <= 2; j++) {
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q=" + cityArray[i] + "&dt=" + toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrCityRecordForDay = [];
arrCityRecordForDay.push({
"cityName": data.list[0].city.name
}, {
"weather": data.list[0].weather[0].description
});
var tempId = data.list[0].city.name+""+timeConverter(data.list[0].dt);
arrCityrecordForADay.push({
tempId: arrCityRecordForDay // Here tempId is inserted as "tempId" not its value
});
if (((arrCityrecordForADay.length)) === cityArray.length) {
callback(arrCityrecordForADay);
}
}
});
toDaysTimestamp = toDaysTimestamp - (24 * 60 * 60);
}
}
}
$(document).ready(function () {
var cityArray = new Array();
cityArray[0] = "pune";
cityArray[1] = "london";
var result = document.getElementById("msg");
getWeatherDataForCities(cityArray, function (jsonData) {
var myJsonString = JSON.stringify(jsonData);
console.log(myJsonString);
});
});
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
//var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
var time = date+''+month+''+year;
return time;
}
How to insert a variable as a key in above example?
EDIT:
And Why output is not stable.Some time wrong and sometime correct.
Here is correct output:
"[{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"London22Dec2013":[{"cityName":"London"},{"weather":"overcast clouds"}]}]"
Some times it shows following output after some refresh.
"[{"Pune24Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]}]"
How to overcome this?
Your response will be appriciated !!
You have to use a temp variable to achieve this:
var obj = {};
obj[tempId] = arrCityRecordForDay;
arrCityrecordForADay.push(obj);

Categories

Resources