I am pushing na element into a javascript array while it is in for each loop. but the loop is not as expected.
Code:
//lets say the length is 1 for array id.If its in error it has to loop 2 times, but looping only once
$.each(id, function(i, itemI) {
$.ajax({
type: "GET",
url: url1.trim(),
dataType: "json",
success: function(data) {//do something
},
error: function(xhr,status){
//push an element into array here
id.push("something");
}
});
})
As per doc, $.each takes the length property of object/array initially and iterate until it meet the length.
You can do like this.
var id=0, req = makeReq(id), makecalltimeout;
function makeReq(id)
{
id = id || "something"; //If id is undefined during first call.
var data = {id:id};
$.ajax({
type: "GET",
url: "google.com",
dataType: "json",
data:data,
success: function(data) {//do something
},
error: function(xhr,status){
clearTimeout(makecalltimeout);
makecalltimeout = setTimeout(makeReq(Math.floor(Math.random()*10)),1000)
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here I will make the request when it fails recursively with a time interval of 1 second. Just to send random data in the params, I have used Math.floor(Math.random()*10. You can replace with what you like.
Related
I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}
I'm trying to get a single image from each ajax request and append it to a li box container, the first ajax returns a list of 20 objects, with name and a url
$.ajax({
url: "http://pokeapi.co/api/v2/pokemon/",
dataType: "json",
method: "GET",
cache: false,
success: function(data) {
for (var i = 0; i<data.results.length ;i++){
$("#root ul").append('<li class="box"></li>');
$("li").eq(i).append('<h2>' + data.results[i].name +'</h2>');
}
setPkmImage(data.results);
console.log(data);
},
error: function(data) {
console.log("Error");
}
});
The problem starts when I try to make a call for each of those objects to request an image, it works with the async: false, but i don't want to do it that way since it takes a lot of time to load all the images.
function setPkmImage(res){
for (var i = 0; i < res.length; i++) {
var promise = $.ajax({
url: res[i].url,
dataType: "json",
method: "GET",
cache: false,
//async: false,
promise.done( function(data) {
console.log(data);
$("#root ul");
$("li").eq(i).append('<img src="' + data.sprites.front_default+ '"/>');
});
promise.fail( function(data) {
console.log("Error");
});
});
}
}
I'm trying to use promises but I don't know exactly how to structure it
Two major problems, one is syntax and the other is you need a closure loop
First the $.ajax is not closed properly.
Should look more like:
var promise = $.ajax({
url: res[i].url,
dataType: "json",
method: "GET",
cache: false
});
promise.done(...
promise.fail(...
As for the closure loop, i won't be what you want it to be inside the ajax callbacks because the for loop will have been completed before the data for requests is returned. Thus i will be at it's maximum by then
Try changing the for loop to $.each which creates a closure
$.each(res, function(i, item){
var promise = $.ajax({
url: item.url,
dataType: "json",
method: "GET",
cache: false
});
promise.done(...
promise.fail(...
})
I usually use the next solution. After first request is done, I've insert to dom img with url (url is come from request) and browser will load images automatically.
What I want is a technique to refresh my div if there are changes in my database. Here is the point,
What i want: How can i condition to know if the first value from my database is lesser than the upcomming value.
In my situation, i put my ajax function to be run every 5secs here is it:
lastcountQueue is declared as global in javascript
function check_getqueue() {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
lastcountQueue = data[0]['count'];
}
});
}
Q:where would i put the condition something if lastcountQueue < data[0]['count]; condition means something if the data is lesser than lastcountQueue it means there was a change in my database portion.
Another Clear Situation for my question:
I want to make a function like these: the ajax will run every 5 seconds where it query a value to count my no. of queues in database. If my first query is giving me 5 value, and the second is giving me again another 5, then there must be nothing change happens, then if my third value gives me 4, where it is not equal to the last query, then i would do something
Probably something like this:
function check_getqueue() {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
var tmpCountQ = data[0]['count'];
if (tmpCountQ < lastcountQueue) {
// Process the change
}
lastcountQueue = tmpCountQ;
}
});
}
Here is the updated answer:
function check_getqueue() {
$.ajax({
url: siteurl + "sec_myclinic/checkingUpdates/" + clinicID + "/" + userID,
type: "POST",
dataType: "JSON",
success: function(data) {
if (data[0]['count'] != lastcountQueue) {
//Your logic here
lastcountQueue = data[0]['count'];
}
}
});
}
I have a function that is called multiple times which uses jquery to fetch different JSON from an API.
I have been trying to get a cumulative count of part of that JSON. Here is sort of what I have:
getTheData(aBlah,bBlah,cBlah);
getTheData(aStuff,bStuff,cStuff);
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
console.log(data.subdata.length);
'the rest of the code'
});
}
I am trying to get a cumulative total of data.subdata.length but I'm not sure how to go about getting it.
This is a classic use case for closures:
var closure = function(){
var counter = 0;
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
counter += data.subdata.length;
'the rest of the code'
});
}
function getcount(){
return counter;
}
return {
getTheData:getTheData,
getcount:getcount
}
};
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
This helps control the scope of the counter variable. So you can do things like:
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
//counter in the new closure is zero
var newClosure = closure();
newClosure.getTheData(aBlah,bBlah,cBlah);
newClosure.getTheData(aStuff,bStuff,cStuff);
var totallyNewCount = myClosure.getcount();
hi actually i read many topic about array and jquery and they all show example using jquery inside the hmtl script tag but what i try to learn is how to read an array sent by php throught ajax inside a js file
here is my php example
$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);
then here is my ajax
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
// here i want to read the array and make a loop for each element
},
});
thanks if you can help me
try basic for loop with count using length This .. this should help surely.
function ajax_test()
{
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i]);
}
}
});
}
Try a for loop to loop the records
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
var record;
for(record in response)
{
console.log(response[record]);
});
},
});
Please use below code :
$(response).each(function(key,value){
console.log(value);
});
Here each loop of response array and value get ('jazz',rock,...etc).
try see this, clear solution for your question
https://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
$.each : A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. Reference documentation
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
//Check if the response is in expected JSON format.
var flag = isJSON(response);
if(flag === true)
{ response = JSON.parse(response); }
//Iterate the Array using for each loop of jquery
$.each(response, function( index, value ) {
console.log( "Index : " + index + "Value : " + value );
});
} // End of success function
}); //End of Ajax
//JSON format check
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
You can get array indexes and values by using .each in jQuery as:
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
$.each(response, function(index,value)
{
console.log(index); // print all indexes
console.log(value); // print all values
});
},
});
<div id="dat" name="dat"></div>
<script type="text/javascript">
$.ajax({ url: "music_list.php",
dataType: 'json',
cache: false,
success:function(response) {
for( res in response) {
document.getElementById('dat').innerHTML+=response[res]+"<br/>";
}
}
});
</script>