Get second object from json after countdown - javascript

I'm using a countdown script from mike giesson to create some sort of Day Deal function. The script has an onComplete function. The product data comes from a json file.
I build the product html with a getJson query. This is functioning good. The only thing I try to achieve is that when the onComplete function is fired the second object in the json file is called. After that the third etc...
Is this even possible? I have other options, like building for example 5 products and hide and show when done. I thought it would be nicer to build it this way :)
So what I have done:
jQuery
function getDaydealProducts(){
$.getJSON('url/page1.ajax', function(data){
var productsHtml = [];
$.each(data.products, function(index, product){
var productHtml =
'<div class="item">' +
... etc .... + '</div>';
productsHtml.push(productHtml);
});
productsHtml = productsHtml.join('');
$('.clock').html(productsHtml);
});
)
var myCountdown1 = new Countdown({
onComplete : countdownComplete
});
function countdownComplete(){
getDaydealProducts(); //get second product.
}
So I tried to build a function that grabs the products, then start the counter. After that a new json call needs to be done with the second object.
Is that possible? And can somebody give me some directions?
thx

Related

How to access and use multiple data from json object? Do I need to make an array?

I am a beginner and using $.get to retrieve data from a rest API such as:
[{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},
{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}] }
$.get('http://xxxxxxxxxxx,
function (data) {
var obj = $.parseJSON(data);
So from what I understand I have retrieved the data from the REST API and parsed it so it is stored in a variable called obj.
My question is, how do I access and use each unique record in the obj variable?
Each record has it's own picture (item1.jpg, item2.jpg etc).
Whem my app loads I want it to show the item1.jpg image, and I want to be able to navigate to the other item pictures using buttons (previous / next).
I also want the description and price to be displayed underneath in some text input fields.
What I have figured so far is that I should:
Iterate through the obj variable, and store each record into an array.
Upon app initialisation I can set the default value for the image placeholder to array[index0].url, and set the description and price fields.
I can then set the previous and next buttons to array[currentIndex-1] or array[currentIndex+1].
Would this be the best way to do it?
Or can I just do this without using an array and manipulate the obj.data directly?
Thanks!!!
I may not be understanding what exactly what you want to do but I think I have the gist. If you just want to show the picture then the array of just images probably wouldn't be a bad idea. However, it looks like the Jason you're getting is already in an array. You can just use array index notation to get to what you want.
ie)
var arr = //your json response ;
var current = 0; //sets currently displayed object to the first in the array
var setCurrent = function () {
var image = arr[current]["url"];
}
You can then modify current however you want (on click on arrow iterate up/down, etc) then call the setCurrent function to set your image the the one you want. Hope that helps!
You can use the response you have from $.get() directly.
It is an array of objects.
You can use it like this:
console.log(data[2].description);
// outputs: "Console"
I've made a CodePen demo where it has a 4th object with a real image url to show you how to use the url info...
EDIT
Just in case you wouldn't know this:
You can use the response inside the scope of the $.get() callback...
You can not use it straith after the $.get() outside the callback since $.get() is asynchronous.
You can use it in some other handler wich will happen after the response is received.
var getResponse;
$.get('http://xxxxxxxxxxx', function (data) {
getResponse = data;
console.log(data[2].description);
// outputs: "Console"
console.log(getResponse[2].description);
// outputs: "Console"
});
console.log(getResponse[2].description);
// outputs: "Undefined"
// But since this handler will be triggered long after the response is obtained:
$("#somebutton").click(function(){
console.log(getResponse[2].description);
// outputs: "console"
});
In order for your page javascript to be able to access the data retrieved from your ajax request, you'll need to assign it to some variable which exists outside the callback function.
You will need to wait until the ajax request has been processed before you can read the array. So you might want to set the actual default image to be something that doesn't rely on the ajax request (a local image).
Here's a simple approach
// fake testing ajax func
function fakeget (url, callback) {
setTimeout(callback(JSON.stringify([
{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"}, {"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"},
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}
])), 1000);
}
// real code starts here
// global variables for ajax callback and setImg func to update
var imageData, currentImg;
// change this back to $.get for real
fakeget('http://xxxxxxxxxxx',
function (data) {
imageData = $.parseJSON(data);
setImg(0);
}
);
function setImg(index) {
// turns negative indices into expected "wraparound" index
currentImg = (index % imageData.length + imageData.length) % imageData.length;
var r = imageData[currentImg];
$("#theImg").attr('src', r.url);
$('#theDescription').text(r.price + " " + r.description);
}
$("#prev").click(function () {
setImg(currentImg - 1);
});
$("#next").click(function () {
setImg(currentImg + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img id='theImg' src='somedefault.jpg'>
<div id='theDescription'></div>
</div>
<button id='prev'>Prev</button>
<button id='next'>Next</button>
Few observations :
Your JSON Object is not a valid JSON.
No need to parse it again your data is already a JSON Object.
Working fiddle
var data = [{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}, {"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}];
for (var i in data) {
var imgUrl = data[i].url;
console.log(imgUrl);
}

Json data from table in an onclick function show in seperate div

I'm trying to get data used in my table to be used in a div when I click on the table. The thing is, there are multiple tables in my script according to the data of my JSON. So my JSON consists of object that consists of object. For example:
My table(s) are rendered like this:
data.forEach(function(somedata){
return '<table><tr><td>'+somedata.something+'</td></tr></table>';
});
Now I've tried to get the onclick to work in this case but I cant seem to figure out how. I'd like to not use specific ID's rendered in the foreach like:
var i=0;
data.forEach(function(somedata){
i++;
return '<table id="'.id.'"><tr><td>'+somedata.something+'</td></tr></table>';
});
the variable somedata consists of an object so I cant just make an onclick in the html code of the table either and send the data in it.
So somedata would look something like this but json encoded:
somedata{
[0]=>array(
'something'=>'test',
'theobject'=>array(...)
),
[1]=>array(etc...)
}
Now what I want is to get the data from theobject in a seperate div as soon as I click on the table that belongs to the right somedata.
I've been thinking of making a jquery on click for this but then I would need specific ID's in the table(if that's the only possible solution then I'd take it). Cant I do something with this or something? Or send the data at the same time it's being rendered cause in my code I can at the moment of course reach to somedata.theobject
I think I'm thinking a bit too difficult about this. Am I?
You can pass this in onclick function like
return '<table onclick=makeObject(this)><tr><td>'+somedata.something+'</td></tr></table>';
And then use the function to get the data
function makeObject(that){
var tbl = $(that).find('tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
}
There are a few ways to go about this. Rather than using the forEach function we can use the jQuery.map function, since you've indicated that you're open to using jQuery :-)
var $els = $.map(data, function(somedata, i){
var $el = $('<table><tr><td>'+somedata.something+'</td></tr></table>')
.click(function(e) {
populateDivWithData(somedata.theobject);
});
return $el;
});
The call to .click inside each will create a separate click handler for each item in data; each click handler then has access to the relevant theobject value.
EDIT: Thanks #Loko for the reminder about the .forEach built-in

Unique jQuery function to update data from any table

I have a jQuery function on a separate functions.js file, that is in charge of making a SQL update by posting some info. This is working properly, here you can see it:
Function being called on my php file, passing just element's ID info:
$('.tableContent').on('click', '.discontinueIcon', function() {
turnId = $(this).attr('data-id');
discontinueRow();})
Function working properly on a separate functions.js file:
function discontinueRow(){
row = '#' + turnId;
$.post('config/forms/turn_conf/turn_discontinue.php', { tu_id:turnId }).success(messageOKKKK);}
As I will need to create many more functions updating info from many tables, I was trying to have a unique function, and provide it with needed info being sent with parameters from the php files. As I am new to this, do not even know if it is possible, and if it is I definitely can't get the way to.
I tried to store the needed values on several variables on my php file:
$('.tableContent').on('click', '.discontinueIcon', function() {
turnId = $(this).attr('data-id');
action = "'config/forms/turn_conf/turn_discontinue.php'";
elements = "tu_id:turnId";
discontinueRow(action,elements);})
And using these parameters on the separate functions.js file as this shows:
function discontinueRow(action,elements){
row = '#' + turnId;
$.post(+action+,{ +elements+ }).success(messageOKKKK);}
But this does not work. Is it possible to pass by this way parameters to a function? In this case, what is going wrong here?
You can do it like this:
$('.tableContent').on('click', '.discontinueIcon', function() {
turnId = $(this).attr('data-id');
discontinueRow('config/forms/turn_conf/turn_discontinue.php', { tu_id:turnId });
});
you also need to set up your function with input parameters:
function discontinueRow(url, params){
row = '#' + turnId;
$.post(url, params).success(messageOKKKK);}
}

Iterating through and displaying json data

I have a codeigniter app and in one of my views, i have an ajax call to an API that returns json data. Once i get the data, I loop through it and append records to an existing table.
There are two ways to run this ajax call. One is to request "all" data, the other is to filter by location.
Both ways return data, but when Im trying to loop through the filtered data set, the ajax is failing.
Here's the code that loops through the record set:
if (JSONdata.length != 0)
{
//create a heading row and attach it to the existing table.
var heading = $('<tr id="tblheading" naming="tblheading">').appendTo($('#switchrecords'));
heading.append($('<td>').append().text('Name'));
heading.append($('<td>').append().text('Object ID'));
//loop through each JSONdata item in the array and append another row to the switchrecords table.
$.each(JSONdata, function(i, objswitch) {
console.log('objectid is:'.objswitch.id);
console.log(objswitch.id);
var row = $('<tr>').appendTo($('#switchrecords'));
row.append($('<td>').append($('<a href='+ BASEPATH + 'index.php/controller/methodname/' + objswitch.id + '>').text(objswitch.name)));
row.append($('<td>').append(objswitch.id).text(objswitch.id));
});
Here's what I've done so far:
I've made sure that both result sets have the same fields, namely "id" and "name". Mind you, the filtered data set includes more fields than the non filtered result but i don't think that should matter.
I've used console.log to dump both result sets... Here's a snippet from both. The first one is ALL and the other is filtered.
[{"name":"888-12-993-99-1","id":"1","dict_value":"compact"},{"name":"888-22-SR1-RTR-1","id":"2","dict_value":"compact"},{"name":"888-21-SR1-SW-1","id":"3","dict_value":"compact"},{"name":"888-11-SR2-SW-2","id":"4","dict_value":"compact"},....etc
[{"parent_id":"2","tag_id":"10","Location":"Building1","id":"7","name":"888-22-228-22-1","label":null,"asset_no":"1026067","objtype_id":"1503"},{"parent_id":"2","tag_id":"5","Location":"Building2","id":"6","name":"888-2-263-88-1","label":null,"asset_no":"1026068","objtype_id":"1503"}, .... etc.
As you can see from the code snippet, I've tried to add some debug information to see what's happening inside the loop. However, I'm getting the following error message on the first console.log() call:
[17:13:30.675] TypeError: "objectid is:".objswitch is undefined
I'm not really too sure how to resolve this. Any suggestions would be appreciated.
I apologize in advance if it's a silly mistake! I've been programming all day and my brain is mush! =)
Thanks in advance for the help.
Unless I'm completely off it looks like .objswitch should be + objswitch.
Try
console.log('objectid is:' + objswitch.id);
instead of
console.log('objectid is:'.objswitch.id);
Looks like your syntax is wrong for concatenation .. It should be done using a + , I see you are using a .
Instead of objswitch try using this
$.each(JSONdata, function(i) {
console.log('objectid is:' + this.id);
console.log(this.id);
var row = $('<tr>').appendTo($('#switchrecords'));
row.append($('<td>').append($('<a href='+ BASEPATH + 'index.php/switches/getswitchdetails/' + this.id + '>').text(this.name)));
row.append($('<td>').append(this.id).text(this.id));
});
Otherwise try using the variable in general
$.each(JSONdata, function(i) {
console.log('objectid is:'+ JSONdata[i].id);
console.log(JSONdata[i].id);
var row = $('<tr>').appendTo($('#switchrecords'));
row.append($('<td>').append($('<a href='+ BASEPATH + 'index.php/switches/getswitchdetails/' + JSONdata[i].id + '>').text(JSONdata[i].name)));
row.append($('<td>').append(JSONdata[i].id).text(JSONdata[i].id));
});

replacing or managing json data from ajax request

I've got a page that makes an ajax request and gets data back in json format.
I needed to sort this data before adding it to the DOM, so it is put into an object with the following code
function(data) {
var birthDates = {};
var uids = {};
$.each(data.users, function() {
if (!uids[this.uid]) {
uids[this.uid] = [];
uids[this.uid].push(this);
}
if (!birthDates[this.birthDate])
birthDates[this.birthDate] = [];
birthDates[this.birthDate].push(this);
});
for (var d in birthDates) {
var date = d;
$('div#holdDates').append('<ul class="dayList" id="' + date + '"><li class="date" >' + date + '</li></ul>');
$.each(birthDates[date], function() {
$('ul#' + date).append('<li class="show" id="' + this.uid + '">' + this.name + '</li>');
});
}
$('li.show').click(function() {
var getuid = $(this).attr('id');
$showArr = uids[getuid];
// now I can get the extended data about the user
this all works great when the page is loaded for the first time, however I'm running into two problems, both as a result of making a second ajax request
1) if i make the same ajax request (giving the same variables, so the same data comes back again), then the data gets added to the newly created objects (uids, and birthDates) twice, and I can't figure out how to keep that as unique
2) sometimes (and i haven't been able to debug to figure out why) i don't get any of the extended user data from uids object. (the stuff I do after the li click
Any ideas? Am i doing this efficiently?
I find it strange that you can't empty an object that you've created, but apparently everything I'm reading says that you can't.
Addition
well, after posting this, the next thing I was doing was building a dynamic tag cloud which is dependent on the returned json.
so, now I run into the same problem again. I need to tag-cloud to be new after each request. I really hope there is a way to get rid of 'legacy' data in javascript.
Thanks,
Pete
Everything declared with the var keyword inside of your function(data) will be created anew each time the function is called.
What's the symptom of your problem? Have you actually looked at the value of the uids variable in firebug and seen that items are being duplicated, or do you just see your dates/names getting doubled up on the page?
My suspicion is that this is a result of not clearing the DOM elements that you are calling .append() on before you display your results.
Try adding to the beginning of the function:
$('div#holdDates').empty();
as well as to your date display loop:
$('ul#'+date).empty();
and for good measure, at the beginning of function:
$('li.show').unbind('click');

Categories