I'm trying to load some ajax content into a table, unfortunately it's only loading the last row multiple times instead of loading each new rows.
This is the code I'm using:
function periodicRefresh()
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayLastEvent",
success: function(msg){
var newid = msg;
current = $("#list tr:first").get(0).id;
if(newid != current){
while (current<newid)
{
current++;
addToList(current);
}
}
}
});
}
function addToList(x)
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayRow&row="+x,
success: function(msg){
$("#list").prepend(msg);
$("#list tr:first").highlightFade({
speed:3000
});
lastrow = x-20;
$('#'+lastrow).remove();
}
});
}
displayLastEvent returns the id of the last row.
displayRow returns the last row
You need to push your xmlHttps into an array or abstract data type, which you can then attach events handlers. Seems jquery doesn't do that for you.
I would address this issue by encouraging you to change your approach since it looks like you're likely making more AJAX requests than necessary whenever more rows need to be added to the list (2+ instead of just 2).
I would update include/ajaxActions.php?action=displayRow to accept a CSV of ids (or whatever it is you're passing in), and returning a set of row data, instead of data for just one row.
I think that:
current = $("#list tr:first").get(0).id;
return always the same result as jQuery remember only the page when it was first loaded.
For example, if you have a single tr[id=0]:
pass 1 : current = 0; msg = 1 -> 1 tr prepended with id = 1;
pass 2 : current is always 0 (not 1); msg = 1 -> 1 tr prepended with id = 1;
...
what you should do, is make jQuery recognize your page structure after adding your messages, or store the last index in a different way: using hidden input for example:
HTML:
<input type="hidden" value="0" id="lastId"/>
script:
initialize #lastId value when the page is loaded:
$(document).ready(function(){
$("#lastId").val(0);//or by using your displayLastEvent action
});
modify periodicRefresh to read #lastId value:
function periodicRefresh()
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayLastEvent",
success: function(msg){
var newid = msg;
var current = $("#lastId").val();
if(current<newid) $("#lastId").val(newid);
if(newid != current){
while (current<newid)
{
current++;
addToList(current);
}
}
}
});
}
Related
i have a load more button on some content that is pulled from a database via ajax.
The ajax call looks like so:
// JavaScript Document
// load more builds function
$(document).ready(function(){
var pageIndex = 1;
$('#loadmorebuilds-div').click(function() {
$.ajax({
url: 'includes/loadmorebuilds.php?type=' + type + '&pageIndex=' + pageIndex,
success: function(html) {
$("#buildcontainer").append(html).waterfall('reflow');
$("#loadmorebuilds-div").stop().fadeOut();
pageIndex++;
var rowCount = MAKE THIS THE VALUE THAT IS APPENDED;
$('.testcount').html(rowCount);
if (rowCount < 18) {
$('#loadmorebuilds-div').remove();
$('.countvar').detach();
} else {
$('.countvar').detach();
}
}
});
});
});
In the appended items, is a div that contains a value of the row count for the database query that has been carried out via the above ajax call.
Normally, i would put this value into a JSON return and simply do e.g.:
rowCount = response.rowCount
However i am not using a JSON datatype but HTML.
How can i get this value from the appended div in the data and use it to set a var?
Thanks!
Use either:
val = $("#thatDiv").text();
or
val = $("#thatDiv").attr("value");
The latter of which, is if you put the value in a pseudo attribute...
I just don't get it, obviously. I've tried setters and getters, self invoking functions, you name it. It's like the click handler is returning a value but there's no way for me to keep it?
This is my code in the first file request.js
var testId = (function (inId) {
var citeId = inId;
return citeId;
})();
function mainAjax() {
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
});
}
var promise = mainAjax();
this is the code in my second file requestMain.js,
promise.done(function (json) {
var linkBase = "http://www.sciencebase.gov/catalog/item/";
var link = "";
var itemId = "";
var urlId = "";
$.each(json.items, function(i,item) {
link = linkBase + this.id;
$('#sbItems').append('<li><b>' + this.title + ' - </b>' + this.summary + '</li>');
});
$('#sbItems a').on('click', function (e) {
e.preventDefault();
var str = $(this).attr('id');
if (str.length == 7) {
itemId = str.slice(5,6);
}
else if (str.length == 8) {
itemId = str.slice(5,7);
}
testId = json.items[itemId].id;
alert(testId);
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
This webpage displays a list of links. A link could have some more information that I want displayed on a second webpage or it could have nothing. So when a link is clicked I need to store/save/keep the id from the link so that I can use it in the url to make another ajax request, because until I get the id the ajax request for the next page will have no idea what information to ask for.
For now I'm simply doing this
alert(testId);
But what I'm trying to do is this,
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' + testId + '?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
// Then doing something with json.something
testId would be used in the url and it would change depending on the link that was clicked on the previous page. The ajax call is totally dependent on the click event and is displayed on a separate webpage with new information.
And this would be in my third file requestCitation.js which currently gives me a big undefined when doing
alert(testId);
I think this is a scope issue, but how can I store the value returned from a click??? So that I can then use it globally? It seems like the value disappears outside of the scope as if there was never a click at all even thought I'm storing it in a variable?
the html for the first page has script tags for request.js and requestMain.js and the second page has script tags for request.js and requestCitation.js, so they can both see the variable testId.
Thanks for the help!
Here's the jsfiddle
These are the links and when a link is clicked
Your testId is holding the value retuned by the function you're calling, and since the function returns its argument and you've called it without arguments, it will be undefined:
var testId = (function (inId) {
var citeId = inId;
return citeId; //returns the argument
})(); // called with no argument
I'm not entirely sure what you're trying to do but if you're trying to keep the data returned from the AJAX request as a global variable, I would have thought it was done using something similar to the below.
E.g.
var promise = '';
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
data: '';
success: function(data){
promise = data;
}
});
But as I said I'm not understanding fully so I could be very wrong with my answer.
I'm scratching my head how to combine results of 2 jQuery ajax calls which return the results into the same DOM element. Here is my setup:
there are 2 calls: one from a list of foods and second from a list of ingredients
both calls return a list of ingredients
the idea is to make a shopping list (ingredients to buy) based on 2 sources (list of foods and list of ingredients)
user can create shopping list either by selecting foods (ingredients are retrieved from the database) or he can select ingredients directly from a list of ingredients
Problem: these 2 calls are working fine each on its own. But the problem is that result from one call is always replacing the result from the second call and vice-versa.
var postUrl = "http://localhost:8000/ingredients/";
var ingrUrl = "http://localhost:8000/ingrs/";
var selectedFoods = [];
var selectedIngrs = [];
$('.foods a').click(function(event){
clickedLink = $(this).attr('id');
if (selectedFoods.indexOf(clickedLink) != -1) {
var index = selectedFoods.indexOf(clickedLink);
selectedFoods.splice(index, 1);}
else {
selectedFoods.push(clickedLink);
};
var jsonFoods = JSON.stringify(selectedFoods);
$.ajax({
url: postUrl,
type: 'POST',
data: jsonFoods,
dataType: 'html',
success: function(result){
$('.ingredients').html(result);
}
});
});
$('.ingr-list a').click(function(event) {
clickedIngr = $(this).attr('id');
if (selectedIngrs.indexOf(clickedIngr) != -1) {
var index = selectedIngrs.indexOf(clickedIngr);
selectedIngrs.splice(index, 1);}
else {
selectedIngrs.push(clickedIngr);
};
var jsonIngrs = JSON.stringify(selectedIngrs);
$.ajax({
url: ingrUrl,
type: 'POST',
data: jsonIngrs,
dataType: 'html',
success: function(result){
$('.ingredients').html(result);
}
});
});
I tried to play around with this line $('.ingredients').html(result); using append instead of html but that won't work because the user should be able to take ingredients off the list (see the if conditions in both functions).
Just use different containers for them
<div class="ingredients">
<div id="first"></div>
<div id="second"></diV>
</div>
Then set the .html() of $("#first") and $("#second") instead of .ingredients
Use .append
$('.ingredients').append(result);
see if this is the answer underscore js template
what you need to do is not passing html back, but passing json back, and using js template to render it at the browser.
some fake code:
var global_ingredients = [];
var list = "<% _.each(ingredients, function(ingredient) \
{ %> <li><%= ingredient.name %></li> <% }); %>;";
$.post('', postdata, function(ingredients){
global_ingredients.push(ingredients);
// here you could also eliminate duplicated ingredients,
// sort the ingredients, do whatever you likes
var new_html = _.template(list, global_ingredients);
$('.ingredients').html(new_html);
});
I've managed to refresh whole pages or single elements with Ajax. However, i am now trying to update my article-comments on the go.
I have an articles page, which outputs all the articles. Beneath each article, there is a table which outputs the comments belonging to the article, and a form to write a new comment.
How do i refresh each of these tables at the same time?
I've been looking at this, but i can't get it implemented correctly:
$(document).ready(function(){
//ajax.php is called every second to get view count from server
var ajaxDelay = 1000;
var ids = [];
$('[id^="zone-"]').each( function() {
ids.push( this.id );
});
setInterval(function(){
$.ajax({
url: 'ajax.php',
dataType: 'json',
type: 'get',
data: { refresh: 'hits', ids: ids },
success: function(data) {
for (var key in data) {
var div = $('#zone-' + key).html( data[key] );
}
}
});
}, ajaxDelay);
});
jQuery AJAX live update on multiple elements on the same page
I am having some trouble working out how to get data from a form to post via ajax. I have the following code but it doesn't seem to be sending though the data from elements like checkboxes and radio buttons. Instead it is sending though all the fields. ie if there is a set of radiobuttons it is sending through all the possibilities not just the checked ones. The form can be made up of any type of element and have an undermined amount of elements in it, so I need to iterate through in the way I am. That part seems to be working, but I can't seem to get the javascript to grab the selected data. Do I need to manually check each element's type and then check to see if it checked etc?
myString = "";
my_form_id = "1";
my_url = "phpscript.php";
elem = document.getElementById("form_" + my_form_id).elements;
for(var i = 0; i < elem.length; i++)
{
if (i>0) { myString += "&"; }
myString += elem[i].name + "=" + elem[i].value;
}
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});
`
Since you're using jQuery, you can drastically simplify it all:
var my_form_id = "1";
var my_url = "phpscript.php";
var form = $("#form_" + my_form_id);
$.ajax({
type: "POST",
url: my_url,
data: form.serialize(),
success: function(data) {
// process the post data
}
});
jQuery's serialize method does all the work for you. But if you wanted to do it by hand, then yes, you would have to check each field.