Parsing JSON with AJAX - show random item of the JSON and update after an amount of time - ajax

I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}

Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});

Related

My jquery and ajax call is not responding and showing unexpected error in console

I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")

AJAX dropdown list down not update with var string variable

I have a test script to update a county drop down list whenever the year or state is updated. When I used a literal string when year is selected, the county list updated fine. However when I tried to the county list using an ajax call and used a (var options) to build the list, the drop down list value changed to an empty list even though I verified the value of (var options) contains valid drop down list options.
Please help!
Thanks,
$('#State').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year:year
};
alert("State changed:" + state + ":" + year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
$('#DataId').html("<option value='Select'>Select-S</option><option value='16'>Alameda-S</option>");
alert("Statitical Areas(S): " + options);
//$('#DataId').html(options); //This should work. How to get the value of options into the string
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
$('#Year').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year: year
};
alert("Year changed:" + state +":"+ year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
//$('#DataId').html("<option value='Select'>Select-Y</option><option value='16'>Alameda-Y</option>");
$('#DataId').html(options); //This should work. How to get the value of options into the string
alert("Statitical Areas(Y): " + options);
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
  return  $.ajax({
     url:  url,
     type:  type  ?  type  :  'GET',
     data:  data,
     contentType:  'application/json'
   });
}  
Instead of using another function to call your $.ajax why not call it immediately. There’s no performance improvement on what you had done. Try to revert your code and just add async property if you want to wait the response before proceeding to your lower conditions.
I hope this will help you

css Property for jquery ajax success function

I'm working with MVC3, using the following jQuery AJAX call:
function Displaymaingrid () {
var Geo = $('#ddlGeo').val();
var Vertical = $('#ddlVertical').val();
var Month = $('#ddlMonth').val();
if(Vertical == "All")
{
var Flag = 1;
}
else
{
var Flag = 2;
}
$.ajax({
url: "#Url.Action("TRUnutilizedOwnershipChange", "TravelReady")",
datatype: "html",
type: "post",
data: {strGeo:Geo, strVertical:Vertical, intMonth:Month, intFlag:Flag},
error: function(){},
success: function(data){
$('.travTableContent').empty();
var text3 = data.data.lstunutilizedownershipentities;
for( var item in text3)
{
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
}
});
}
I want to set the CSS property for success function:
$('<tr />').html(text3[item]).appendTo('.travTableContent');
I want to add the following CSS property in the above line:
("tr:odd").css("background-color", "#d0d1e2")
Where do I need to insert this line?
Add it after the "for" statement.
for( var item in text3){
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
$("tr:odd").css("background-color", "#d0d1e2");

AJAX loop for WordPress (posts from different categories)

I try to implement AJAX posts loop for WordPress from Tuts+
I want this loop to show under comments form in single post page in three columns (each for another category)
In single.php I have divs (numbers comes from category):
<div class="news_posts-6"></div>
<div class="news_posts-3"></div>
<div class="news_posts-2"></div>
My ajaxLoop:
jQuery(function($){
var page = 1;
var loading = true;
var $window = $(window);
var cat = [6,3,2];
var load_posts= jQuery.each(cat, function(){
var $content = $(".news_posts-" + this);
$.ajax({
type : "GET",
data : {numPosts: 2, pageNumber: page, cat: this},
dataType : "html",
url : "http://127.0.0.1:4001/wordpress/wp-content/themes/twentyeleven-child-theme/loopHandler.php",
beforeSend : function(){
if(page != 1){
$content.append('<div id="temp_load" style="text-align:center">\
<img src="/images/ajax-loader.gif" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
$content.append($data);
$data.fadeIn(500, function(){
$("#temp_load").remove();
loading = false;
});
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
load_posts();
}
});
load_posts();
});
Part of loopHandler.php:
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 0;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : 0;
echo $numPosts;
echo $page;
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'cat' => $cat
));
I tried use simple array containing categories numbers but it doesn't work. Depends on
data : {numPosts: X, pageNumber: page, cat: this},
there is X post displaying in each column (same posts from first category).
I guess I need to use JSON, which I tried, but it was total disaster (I don't know how to put it together). I just need to call AJAX for three different arguments.
Thanks for any help
Well, there are various ways you can go about this.
One way is looping over your categories client side first, and make separate request per category. This is what you are essentially doing in your code. You are iterating over an array of categories and making a request for each.
Another way is to pass that array of categories to your handler. All you need to do is modify your handler to accept an array of integers or categories. Then you can return a JSON object. But this involves a lot more editing and on top of that it does not solve the issue of having different sizes and heights for each section.
Thus, below, I have modified the code a little bit to also keep track of multiple sections. There are just a few small edits we need:
Each section needs to have a category number, pagination number, content section, and a flag whether its loading or not. Each needs to be stored in a single list for tracking.
We need to iterate over each category to initialize it.
We need to iterate over each category on window scroll and check if the next item should be loaded
We need to make sure that each request relates to the requested category
Start by modifying your divs a little (this is just a matter of preference, i prefer storing metadata like this in an attribute instead of a class):
<div class="news_posts" data-category="6"></div>
<div class="news_posts" data-category="3"></div>
<div class="news_posts" data-category="2"></div>
Here's a modified JS (please be aware that I changed up some variable and function names):
jQuery(function($){
var $window = $(window);
var cats = [];
var contentDivs = $(".news_posts");
var initializeCats = function(){
// adds category objects to a list for tracking
for(var i = 0; i < contentDivs.length; i++){
var catNum = $(contentDivs[i]).attr("data-category");
var cat = {
catNum : catNum,
catPage : 1,
loading : true,
catDiv : $(contentDivs[i]);
};
cats.push(cat);
load_post(cat);
}
};
var load_post = function(cat) {
$.ajax({
type : "GET",
data : {
numPosts : 2,
pageNumber : cat.catPage,
cat : cat.catNum
},
dataType : "html",
url : "http://127.0.0.1:4001/wordpress/wp-content/themes/twentyeleven-child-theme/loopHandler.php",
beforeSend : function(){
if(page != 1){
// this was a bad idea when i wrote the article originally
// never concatenate strings on multiple lines by escaping
// the carriage return
// $content.append('<div id="temp_load" style="text-align:center">\
// <img src="/images/ajax-loader.gif" />\
// </div>');
cat.catDiv.append("<div class='temp_load' style='text-align:center'>" +
"<img src='/images/ajax-loader.gif' />" +
"</div>");
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
cat.catDiv.append($data);
$data.fadeIn(500, function(){
cat.catDiv.find(".temp_load").remove();
cat.loading = false;
});
} else {
cat.catDiv.find(".temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
cat.catDiv.find(".temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
var onWindowScroll = function(){
for(var i = 0; i < cats.length; i++){
var cat = cats[i];
var contentDiv = cat.catDiv;
var content_offset = contentDiv.offset();
if( !cat.loading &&
($window.scrollTop() + $window.height()) >
(contentDiv.scrollTop() + contentDiv.outerHeight() + content_offset.top)
) {
cat.loading = true;
cat.catPage++;
load_post(cat);
}
}
}
initializeCats();
$window.scroll(onWindowScroll);
});
The PHP file is pretty much the same, just comment out the echo $numPosts line:
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 0;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : 0;
// echo $numPosts;
echo $page;
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'cat' => $cat
));
This is just something quick I whipped up. I HAVE NOT TESTED IT. Try it out, watch out for syntax errors, and cross your fingers :). I hope this will work for you and if it does not, we can look into modifying it so that it does.

AJAX Jquery: execution order of events

I have a webpage with different elements (a list of links and two select boxes) connected between them. Clicking on them may affect one of the other element and all of their values contribuite to update a value to show on the page.
So, the code is this:
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
my_change();
console.log('second' + someVar);
});
function my_change() {
$.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
})
};
};
When I load the page the my_change function is called. It does some stuff and then triggers a change event on a select-box. I need to update a value using what's inside this select box and only then let the execution to proceed. So what I need this code to do would be to print 'first', and then 'second' with the value of the variable. What actually happen is that it prints 'second' 'first'.
I think it's because I'm doing asynchronous calls. What can I do?
There's several ways to do this.
You could use jQuery $.when and call the console.log after the ajax response finishes.
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
$.when( my_change() ).then(function(){
console.log('second' + someVar);
});
});
function my_change() {
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
})
};
};
Or you could add a callback argument to the my_change(callback) function.
$(document).ready(function() {
var someVar = '';
$("select#size").bind('change', function() {
someVar = $(this).val();
console.log('first');
});
my_change(function(){ console.log('second' + someVar) } );
});
function my_change(callback) {
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
if( typeof callback !== 'undefined' && typeof callback === 'function' )
callback();
$("select#options").html(options.join('')).trigger('change');
})
};
};
The 'second' console.log() is being called first since the asynchronous $.getJSON() call waits for the response from the server before firing its callback function. You could save the jqXHR object to a variable and then use that to run your 'second' consone.log() with $.when():
$(function() {
var someVar = '';
$("#size").on('change', function() {//on() is the same as bind() here
someVar = $(this).val();
console.log('first');
});
//save the jQuery XHR object from your $.getJSON request
var jqXHR = my_change();
//when the above jQuery XHR object resolves, it will fire the second console.log
$.when(jqXHR).then(function () {
console.log('second' + someVar);
});
});
function my_change() {
//here we return the jQuery XHR object for the $.getJSON request so we can run code once it resolves
return $.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("#size").trigger('change');
$("#options").html(options.join('')).trigger('change');
})
};
Here is documentation for $.when(): http://api.jquery.com/jquery.when
A quick side-note: it is generally slower to add a tag-type to a selector, especially when you are selecting IDs as that is already a very fast method of selecting elements.
Any code that relies on the response of the getJSON must be placed in, or called from, the getJSON callback.
That's what a callback is for.
You should note that your my_change function will not have access to the someVar variable because it is local to the ready() callback.
To remedy this, move the my_change function inside the ready() callback.
Or just pass a function directly to my_change.
my_change(function() {
console.log('second' + someVar);
});
And have the getJSON callback invoke the function.
function my_change( func ) {
$.getJSON("photos/change_product", {json_stuff}, function(data) {
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<option value="' + data[i].id + '">' + data[i].label + '</option>');
}
$("select#size").trigger('change');
$("select#options").html(options.join('')).trigger('change');
func();
});
}

Resources