Hey there,
Again, I've been searching a solution to find out why a function, would not being called... and guess what, I did not find.
I have a form, that I submit using jQuery Ajax. When error, I get every local data, I got, I sorted them, and show them to the user.
Here is the sample code :
$.ajax({
type: "POST",
url: "http://xxx/register.php",
data: form,
success: function(msg){
//console.log("Data Saved: " + msg);
$.iGrowl(2,stringdata[4]);
var data = parseJSON(msg);
if(data.msg.score != undefined){
var cpt = 0;
$.each(data.msg.score, function(index,el){
if(cpt<8){
if(el.selected)
$('tbody').append('<tr class="win"><td>' + el.name + '</td><td>' + el.score + '</td></tr>');
else
$('tbody').append('<tr><td>' + el.name + '</td><td>' + el.score + '</td></tr>');
}
});
}
else{
$.iGrowl(3,"Erreur inconnue...");
}
$("#scorediv").css("visibility","visible");
$( "#formule" ).css('opacity',0);
$( "#scorediv" ).css('opacity',1);
},
error: function(data) {
cpt = 0;
var i = 0;
score.each(function(r){
arrayScore[i] = r;
i++;
});
arrayScore.sort(function(a, b){
console.log("sorting...");
if(a[3])
{
if(b[3])
{
return (b[3].value - a[3].value); //causes an array to be sorted numerically and descending
}
}
});
$.each(arrayScore, function(index,el){
//arrayScore.forEach(function(el) {
//score.each(function(el){
if(cpt<8)
{
if(el[2].value == form[2].value)
$('tbody').append('<tr class="win"><td>' + el[1].value + '</td><td>' + el[3].value + '</td></tr>');
else
$('tbody').append('<tr><td>' + el[1].value + '</td><td>' + el[3].value + '</td></tr>');
cpt++;
}
else
return false;
});
var user = form;
store.save(user, function(r) {
});
$.iGrowl(3,stringdata[5]);
$("#scorediv").css("visibility","visible");
$("#formule").css('opacity',0);
$( "#scorediv" ).css('opacity',1);
}
});
My array is never sorted. If I change this part :
var i = 0;
score.each(function(r){
arrayScore[i] = r;
i++;
});
by this :
score.each(function(r){
arrayScore.push(r);
});
arrayScore is never filled.
I try to execute each line in the console step by step, it works.... I'm getting kind of crazy... and I really do not know what could have happened ?
Any help would be graceful appreciate !
P.S : I'm using, jQuery1.5 + Lawnchair and CSS3 animation.
Code tested on safari and chrome.
Thanks !
Javascript array objects don't support a method called each. You should try
$.each(score, function(index, value){...});
Related
I am facing a problem where I want to return all the rows one by one without interupting the current function. The issue is intermittent. Sometimes I can get all the datatables data but sometimes not.
Then I started investigating and realised after checking the developer tool in network section that it throws error after page 10. And the error is 429 too many requests. Also, realised that the script was synchronous json call.
429 too many requests
I tried using below code in my script but the spin is not working. Also, found that this is not recommended way.
Can someone help me with solution? Thank you
// Set the global configs to synchronous
$.ajaxSetup({
async: false
});
My Script
function getMed(sDate, eDate) {
var pData;
var firstURL = mUrl + "?sDate=" + moment(sDate).format(dateFormat) + "&eDate=" + moment(eDate).add(1, 'day').format(dateFormat) + "&pNum=1";
....
}).done(function (data) {
if (pData.Number > 0) {
var counter = 0;
// Set the global configs to synchronous
$.ajaxSetup({
async: false
});
var requestsProcessed = 0;
for (var i = 1; i <= pData.Number; i++) {
$("#iconSpin").css('display', 'block');
var pURL = mUrl + "?sDate=" + moment(sDate).format(dateFormat) + "&eDate=" + moment(eDate).add(1, 'day').format(dateFormat) + "&pNum=" + i;
console.log("calling: " + pURL);
var pageRequest = $.getJSON(pURL, function (data) {
requestsProcessed++;
$("#progress").innerHTML = "Fetching batch " + requestsProcessed + " of " + pData.Number + " batches.";
....
}).fail(function () {
$("#iconSpin").css('display', 'none');
console.log("fail for " + pURL + " in " + new Date());
});
console.log("completed for " + pURL + " in " + new Date());
}
} else {
alert("There is no data.");
}
}).fail(function () {
$("#iconSpin").css('display', 'none');
});
}
I don't know I can't access to values of the variable in Javascript.
urli have values like: https://cors.io/?https://tb.rg-adguard.net/php/get_edition.php?version_id=11&lang=name_en
But I tried to print values of name_lang with console.log(this.namelang) but it shows undefine
Here my code:
var urli = 'https://cors.io/?https://tb.rg-adguard.net/php/get_edition.php?version_id=' + version_id + "&lang=" + namelang;
$.ajax({
type: "GET",
url: urli,
dataType: 'json',
success: function(response){
var options = '';
console.log(this.namelang);
$.each(response.editions, function() {
options += '<option value="' + this.edition_id + '" style="color: ' + this.color + '">' + this.namelang + '</option>';
});
$('#edition_id').html('<option value="0">- ' + seledition + ' -</option>'+options);
$('#edition_id').attr('disabled', false);
$('#language_id').html('<option>- ' + sellanguage + ' -</option>');
$('#language_id').attr('disabled', true);
$('#arch_id').html('<option>- ' + selachitecture + ' -</option>');
$('#arch_id').attr('disabled', true);
}
});
Are you sure you have namelang in your response???
I can not see namelang when I checked the URL.
Below is response from the urli
{
"editions": [
{
"name_en": "Windows 8.1 Pro + Core",
"color": "green",
"edition_id": "960032"
},
{
"name_en": "Windows 8.1 Pro N + Core N",
"color": "green",
"edition_id": "960033"
}
]
}
After I understanding your requirements properly here I came up with the solution. You don't know what will be the language name, it can be name_en or name_fr but name_ will be common. Right? If YES then below is the solution:
Working code snippet here:
let response = {"editions":[{"name_en":"Windows 8.1 Pro + Core","color":"green","edition_id":"960032"},{"name_en":"Windows 8.1 Pro N + Core N","color":"green","edition_id":"960033"}]};
$.each(response.editions, function() {
console.log(this.edition_id);
console.log(this.color)
let keysArr = Object.keys(this);
let langname = "name_";
for (var key in this) {
if (key.substring(0, langname.length) === langname) {
console.log(this[key]); // your desired value
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That's because this, inside that callback, is just the JQuery xhr object, as seen here:
The response object contains what you want. But namelang is not inside that. The sample URL you gave has an array of two JSON objects.
To access, say, the first object's color, you'd take response[0].color.
I want to download the AJAX user list available at http://zadanie.ee/users.json, And I would like to display
1.The number of all users,
2.The Number of active users,
3.The Number of active women,
4.The Number of active men,
from JSON API, using jquery/javascript etc,
How can I achieve this? or can some one provide me a simple tutorial to start with?
Here is what I have done so far :
CODE:
<script>
function ViewData()
{
$.getJSON("http://zadanie.ee/users.json",
function(data)
{
var items = [];
$.each(data.Users,
function(key, value)
{
items.push("<li>" +
value.username + "<br />" +
value.active + "<br />" +
+ "</li>");
});
$('<ul/>', {html: items.join(")}).
appendTo('body');
});
}
</script>
Any help or any idea will be appreciated, Thanks.
Please try this code.
$(document).ready(function (){
$.getJSON("http://zadanie.laboratorium.ee/users.json",function(data)
{
var items = [];
var number_of_user = 0;
var number_of_active_user = 0;
var number_of_active_men = 0;
var number_of_active_women = 0;
$.each(data,
function(key, value)
{
number_of_user += 1;
if(value['active'] == true){
if(value['gender'][0] == 'Female' || value['gender'][0] == 'female'){
number_of_active_women +=1;
}
else if(value['gender'][0] == 'Male' || value['gender'][0] == 'male'){
number_of_active_men +=1;
}
}
});
console.log("number_of_user ==> "+number_of_user +" number_of_active_user ==> "+ number_of_active_user +" number_of_active_men ==> "+ number_of_active_men +" number_of_active_women ==> "+ number_of_active_women);
});
});
Hope this helps.
Use AJAX to read data and then parse it accordingly.
$.ajax({
type: 'GET',
url: '"http://zadanie.laboratorium.ee/users.json"',
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
console.log(element.username);
});
}
});
I have (part of) a form HTML produced by a PHP loop:
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
The input goes in a db tables:
store
-------
cityID
cityname
store
I have a JavaScript that alerts me if the store entered is already in other cities:
$(document).ready(function() {
$('.store').on('change', function() {
var storeValue = $('.store').val();
$.post('stores.php', {'word': storeValue}, function(data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v) {
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
alert('Already in the following cities: ' + '\n' + verifStore);
});
});
});
Problem is that JavaScript is fired by the .class and I have more .class inputs in my form, so (of course) it doesn't work properly. How should I modify my JavaScript code? Maybe there is in JavaScript a way to consider each .class field separately... Something like .each or .foreach ...?
Let's say, you have been asked to put 4 different values for the city and they are not supposed to be present in the DB. I would create a class named error:
.error {border: 1px solid #f00; background: #f99;}
And now, I would go through each of the input using $.each:
$(".store").each(function () {
$this = $(this);
$this.removeClass("error");
$.post('stores.php', {'word': $this.val()}, function (data) {
if ( /* Your condition if the word is present. */ )
alert("Already there!");
});
});
Note that this code will send as many as requests to the server as many inputs are there. So handle with care.
You can optimize your function if you do just one request.
var values = $(".store").map(function(){
return this.value;
}); // values is an array
$this.removeClass("error");
// stores.php should be ready to receive an array of values
$.post('stores.php', {'word': JSON.stringify(values)}, function (data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v){
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
if(varifStore)
alert('Already in the following cities: ' + '\n' + verifStore);
});
SOLUTION (at least for me...)
After reading all answers and suggestions, I was able to make it work with this code. Hope it will be helpful for others :)
$(document).ready(function() {
$('.store').each (function(){//do it for every class .store
var $this = $(this); //get this object
$this.on('change', function(){ //when this change...
var searchValue = this.value; //assign the input to a variable
if (searchValue != ''){ //if the variable is not emprty
$.post('stores.php',{'term' : searchValue}, function(data) { //check and return data in alert
if (data.length < 10){ // if number not in db, green
$this.css({'border' : 'solid 4px #17BC17'});
}
var resultAlert = '';
var jsonData = $.parseJSON(data);
$.each(jsonData, function(k, v){
resultAlert += '[' + v.cityID + '] ' + v.cityname + ' ' + v.value + '\n';
}); //each
alert('ALERT!' + '\n' + 'store in other cities' + '\n' + searchValue + ': ' + '\n' + resultAlert );
$this.css({'border' : 'solid 4px #FFCC11'}); // if in db, yellow
});// post
}//close if
if (searchValue == ''){ //if the variable is empty, this turn green, if you delete a yellow number
$this.css({'border' : ''});
}
}); //close on change
});//close .each
});
I am trying to invoke a getJSON function for each value in an array and if the user is offline, display their name. However, I keep getting undefined. When a number is hard coded for i though, it works fine.
function getStreamersList() {
$('#listOfStreams').html("");
for (var i = 0; i < streamers.length; i++) {
console.log("This works: " + streamers[i]);
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamers[i], function(data) {
if (data.stream !== null) {
$('#onlineStreams').append('<div class="online"><p>' + data.stream.channel.status + '</p></div>');
} else {
console.log(streamers[i]);
$('#offlineStreams').append('<div class="offline"><p>' + streamers[i] + ' is offline.</p></div>');
}
}, 'jsonp')
}
}
Can someone please explain what's happening? Thanks for any help!