Javascript. Run a AJAX flow after current AJAX stops - javascript

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>

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("");

Handle with ajax request after click link

i have link in my page
+1111
i want to save every click in database
i made this ajax code :
<script type="text/javascript">
$('#tel').on('click', function() {
var location = $(this).attr('href');
var action = 'script.php';
$.ajax({
method: 'POST',
url: action,
data: '',
dataType: 'json',
success: function (data) {
window.location = location;
},
error: function(data){
return false;
}
});
});
</script>
now what must i do, what is the code i have to put in script.php
First you need send some data to script.php, for example
url: action,
data: {location: location},
dataType: 'json',
next in script.php you can read this data
$_POST['location']
create sql query and save data in DB.
send href as json
<script type="text/javascript">
$('#tel').on('click', function() {
var location = $(this).attr('href');
var action = 'script.php';
$.ajax({
method: 'POST',
url: action,
data: {"href":location}, // this line update
dataType: 'json',
success: function (data) {
console.log(data['state]); // this line add for debug server side
window.location = location;
},
error: function(data){
return false;
}
});
});
</script>
and update script.php like below:
<?php
if($_POST['href']){
//connect to database
//update table
echo json_encode(array('state'=>'ok'));
}else{
echo json_encode(array('state'=>'error'));
} ?>

How to fire anothing action before a each loop (with ajax) complete

I have try for the following for a long time and i have no more idea now, anyone can help me please.
I just want to reload the current page after add items to the cart, I have try the stupid way by count, promise then and other else, but all fail.
The problem is... the page already reloaded before the item add to the cart...!
The following is my sample:-
$("#Button").click(function () {
var CurrentURL = window.location.href;
var SelectedProduct = $('.SelectedProduct').length;
$('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json"
});
--SelectedProduct
if (SelectedProduct === 0) {
window.location.href = CurrentURL;
$('#CartListContent').slideDown()
}
});
});
$("#Button").click(function () {
var CurrentURL = window.location.href;
var promise = $('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json"
});
promise.done(function () {
window.location.href = CurrentURL;
$('#CartListContent').slideDown()
});
});
});
}
});
I don't know how much control you have over the server side code, but you should let the API handle adding an array of products to cart, that would make it so much faster and simpler. http://jsfiddle.net/hqn3eufa/
$("#Button").on('click', function () {
var selected_products_ids = [];
$('.SelectedProduct').each(function () {
selected_products_ids.push(this.id);
});
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { ids: selected_products_ids },
datatype: "json",
success: function() {
window.location.reload();
}
});
});
You can make use of the success callback of ajax and the reload function:
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json",
success:function(data){
window.location.reload();
}
});
your page reload before the add to cart completes.
use a callback to find out when the add to cart is completed:
$("#Button").click(function () {
var CurrentURL = window.location.href;
var promise = $('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json"
}).success(function () {
window.location.href = CurrentURL;
$('#CartListContent').slideDown()
});
});
});
}
});
Now i use the following way, it is stupid but work:-
Anyother suggestion..!?
var SelectedProduct = $('.SelectedProduct').length;
$('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json",
success: function (data) {
--SelectedProduct
if (SelectedProduct == 0) {
window.location.reload()
}
}
});
});

Checking dynamically generated element in jQuery?

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) {
}
});
}
}

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

Categories

Resources