Checking dynamically generated element in jQuery? - javascript

Please consider the following code:
function autoRecursiveLoad(checkingElementId) {
if (checkingElementId.length) {
return;
}
else {
var targetId = $("#targetContent");
var requestUrl = $('#ajaxUrl').val();
$.ajax({
url: requestUrl,
cache: false,
type: "POST",
async:false,
beforeSend: function(){
},
complete: function(){
autoRecursiveLoad(checkingElementId);
},
success: function(data) {
targetId.append(data);
},
error: function(e) {
}
});
}
}
in the code: checkingElementId is the id of the dynamically generated element. I used checkingElementId.length to see if it already exists yet, if not, send ajax request to load the content, create div with the id of checkingElementId and then appends to targetId, then perform recursive call.
The problem is the div with id of checkingElementId is generated successfully but the code to check if it exists (checkingElementId.length) never worked. Hence, the above function will loop forever. Am I doing something wrong?

I dont know if it is the best solution or not, but this works for me, I trigger the DOMNodeInserted event on the fly, so the function is updated as follows:
function autoRecursiveLoad(checkingElementId) {
$(document).on('DOMNodeInserted', checkingElementId, function () {
// do something when the new dynamically generated item (checkingElementId) added to the page
});
if (checkingElementId.length) {
return;
}
else {
var targetId = $("#targetContent");
var requestUrl = $('#ajaxUrl').val();
$.ajax({
url: requestUrl,
cache: false,
type: "POST",
async:false,
beforeSend: function(){
},
complete: function(){
autoRecursiveLoad(checkingElementId);
},
success: function(data) {
targetId.append(data);
},
error: function(e) {
}
});
}
}

Related

I am not able to clear me textare value after the ajax is submited successful

$(document).on('click','#commentsubmitimage',function(e) {
console.log("beni");
e.preventDefault();
var content =$('#commenttext').val();
console.log(content);
var imageid = $('#imagecomid').val();
$.ajax({
type: 'POST',
url: "/user/postcoment/" + imageid,
data:{
contenta:content
},
success: function(data) {
// have try this
document.getElementById(commenttext).innerHTML = '';
// have try this
$('#commenttext').val('');
},
error: function(data) {
console.log(data);
}
});
});
I want to clear my textareaa with id ="commenttext" i have try all the methods and it doesnt happen nothing any suggest ?
if your success call back working correctly then write
success: function(data) {
alert("working");
$("#commenttext").val("");

How can I make sure that other functions is run after this get function is fully completed and rendered?

I have this script that adds elements with data by a get json function.
$(document).ready(function() {
ADD.Listitem.get();
});
It basicly adds a bunch of html tags with data etc. The problem I have is following:
$(document).ready(function() {
ADD.Listitem.get();
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
-
get: function(web) {
AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem);
},
renderListitem: function(data) {
$("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template");
}
and here is the json get:
ADD.Utils.JSON.get = function (url, data, onSuccess) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
success: onSuccess,
error: ADD.Utils.JSON.error,
converters: { "text json": ADD.Utils.JSON.deserialize }
});
}
The array each loop is not running beacuse the get method is not finished with rendering the Listitem-section-item-title selector so it cant find the selector.
Is there any good solutions for this?
You could change your functions to return the promise given by $.ajax :
ADD.Utils.JSON.get = function (url, data) {
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
converters: { "text json": ADD.Utils.JSON.deserialize }
}).fail(ADD.Utils.JSON.error);
}
get: function(web) {
return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem);
},
So that you can do
$(document).ready(function() {
ADD.Listitems.get().done(function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Callback:
$(document).ready(function() {
ADD.Listitem.get(url,data,function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Without callback:
If you cant get the get method to take a callback or return a promise then I think the best way will be to check when its done.
$(document).ready(function() {
ADD.Listitem.get();
var timer = setInterval(function(){
if ($("#thingWhichShouldExist").length>0){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
clearInterval(timer);
}
},50);
});
Retrieve the values and on success, call a function which will push the values into the array.
Also, arr.push($(this.text())); should be arr.push($(this).text());.

Javascript. Run a AJAX flow after current AJAX stops

So I have a simple javascript that loads more comments from a database when the user clicks More.
Now I would like to extend this script so that it first populates the SQL database before it starts letting users view the comments. And I feel that I'm on the right track but I can't get it to work.
First the code that does WORK.
$(function() {
$('.load_more').live("click",function() {
var photoid = document.getElementById('photoid').value;
var lastid = document.getElementById('lastid').value;
if(lastid!='end'){
$.ajax({
type: "POST",
url: "/more_comments_ajax.php",
data: {
photoid : photoid,
lastid : lastid
},
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("div#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
Now I feel that this should be possible to expand like this.
$(function() {
$.ajax({
type: "POST",
url: "/populate_sql.php",
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
sucess: $('.load_more').live("click",function() {
var photoid = document.getElementById('photoid').value;
var lastid = document.getElementById('lastid').value;
if(lastid!='end'){
$.ajax({
type: "POST",
url: "/more_comments_ajax.php",
data: {
photoid : photoid,
lastid : lastid
},
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("div#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
});
Where am I loosing it?
You can use this function. I used it before and it works great. after first callback receives then it send second request.
(function($)
{
var ajaxQueue = $({});
$.ajaxQueue = function(ajaxOpts)
{
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next)
{
ajaxOpts.complete = function()
{
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
})(jQuery);
use it like the normal ajax. sample:
$.ajaxQueue({ url: 'x.php', data:{x:x,y:y}, type: 'POST',
success: function(respond)
{
.....
}
});
so you can check if there was a callback from first ajax then send second request.
hope it helps you.
Thanks for the answer. It was not exactly what I needed but it gave me an idea and the solution that works for me was 2 javascripts working together. I'm leaving the code here if someone needs something similar.
<script type="text/javascript">
jQuery(function($){
var pid = '<?php echo $ids['0']; ?>';
$.ajax({
type: "POST",
url: "/prepare_sql.php",
data: "pid="+ pid,
beforeSend: function() {
$('div#updates').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html) {
$("div#updates").replaceWith(html);
}
});
});
</script>
<script type="text/javascript">
$('.load_more').live("click",function() {
var photoid = document.getElementById('photoid').value;
var lastid = document.getElementById('lastid').value;
if(lastid!='end'){
$.ajax({
type: "POST",
url: "/more_comments_ajax.php",
data: {
photoid : photoid,
lastid : lastid
},
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("div#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
</script>

jquery ajax sucess data into facebox

UPDATE: The code if working I has some css issues.
I'm trying to put ajax data into facebox modal box, I have the following code but facebox modal box is not loading. Looking into firebug ajax is returning the correct data but i do not know how to pass that data to facebox.
$('a[rel*=facebox]').live("click", function() {
var ajaxpostID=$(this).parent().attr("id"); //Get entry ID
$.ajax({
url: 'http://www.someurl.com/ajax/facebox-ajax.php',
type: "POST",
data: ({
ajaxpostID: ajaxpostID
}),
success: function(data) {
$.facebox(data);
},
error: function() {
$.facebox('There was an error.');
}
});
});
Something like this worked for me:
//added some id to anchor tag and
$('a[id='some_anchor_id']').live("click", function() {
var ajaxpostID=$(this).parent().attr("id"); //Get entry ID
jQuery.facebox(function() {
var form_data = {
ajaxpostID: ajaxpostID
};
$.ajax({
url: "http://www.someurl.com/ajax/facebox-ajax.php",
type: 'POST',
data: form_data,
success: function(data) {
jQuery.facebox(data);
},
error: function() {
$.facebox('There was an error.');
}
)
});
})
})
Hope it works for you

How can I run Ajax functions synchronously from Javascript?

I have the following code:
$('#DoButton').click(function (event) {
event.preventDefault();
$("input:checked").each(function () {
var id = $(this).attr("id");
$("#rdy_msg").text("Starting" + id);
doAction(id);
});
});
function doAction(id) {
var parms = { Id: id };
$.ajax({
type: "POST",
traditional: true,
url: '/adminTask/doAction',
async: false,
data: parms,
dataType: "json",
success: function (data) {
$("#rdy_msg").text("Completed: " + id);
},
error: function () {
var cdefg = data;
}
});
}
When the button is clicked it checks the form and for each checked input it calls doAction() which then calls an Ajax function. I would like to make it all synchronous with a 2 second delay between the completion of one call and the running of the next. The delay is to give the user time to see that the last action has completed.
By setting async=false will that really make the ajax function wait?
How can I add a 2 second wait after the Ajax has run and before the next call to doAction?
There is option in jQuery to set the ajax function synchronous
$.ajaxSetup({
async: false
});
To make the function to wait you can use .delay()
Try the solution of this question also.
Try to do it using recursion
$('#DoButton').click(function (event) {
event.preventDefault();
doAction( $("input:checked").toArray().reverse() );
});
function doAction(arr) {
if( arr.length == 0 ) return;
var id = arr.pop().id;
$("#rdy_msg").text("Starting" + id);
$.ajax({
type: "POST",
traditional: true,
url: '/adminTask/doAction',
async: false,
data: { Id: id },
dataType: "json",
success: function (data) {
$("#rdy_msg").text("Completed: " + id);
setTimeout(function(){ doAction(arr); }, 2000);
},
error: function () {
var cdefg = data;
$("#rdy_msg").text("Error: " + id);
setTimeout(function(){ doAction(arr); }, 2000);
}
});
}
Use setTimeout for the AJAX call doAction.

Categories

Resources