In a website I have several ajax-parts that are loaded by events, mostly clicks. To inform the visitor a loading partial is shown. This works nice most of the time, but sometimes the ajax call is receiving the respons so quick it interferes with the beforeSend.
My typical structure looks like this:
$(document).on('click', '.handler', function() {
var target = $(this).attr('data-targetElement');
$.ajax({
url: '/ajax.php?someParameter=hasValue',
beforeSend: showLoading(target)
})
.done(function(response) {
console.log('Hi there, I\'m done!');
$('#' + target).html(response);
});
});
// This is in a function because it's used by all ajax-calls
function showLoading(target) {
$('#' + target).html('My loading message');
}
The problem is, when I'm inspecting console messages, that the loading message is still shown even though the .done() was reached, because Hi there, I'm done! is shown.
So it looks beforeSend doesn't seem to have reached a completed state or something like that causing it to 'freeze', because the content in the targetElement is not updated with the response for the ajax-call.
I'm not sure how to solve to this. Any suggestions?
Update,
Sorry for the typo, I just typed the exemplary code in here...
At first, you need to fix all syntax errors in your code.
Remove ; in the middle of the statement.
$.ajax({
beforeSend: showLoading(target);
// ^ SYNTAX ERROR
})
When you write showLoading(target) you call the showLoading() function immediately.
If you need to set pass it as a callback with parameters, you need to pass a function, that returns your callback.
beforeSend: function() {
showLoading(target);
}
Try removing syntax error semicolon ; at close of beforeSend , utilizing var target = $(this).data('targetelement'); for target variable
$(document).on('click', '.handler', function() {
var target = $(this).data('targetelement');
console.log(target)
$.ajax({
type:"POST",
url: '/echo/html/',
beforeSend: function() {showLoading(target)},
data:{html:"Hi there, I\'m done!"}
})
.done(function(response) {
console.log(response);
$('#' + target).html(response);
});
});
// This is in a function because it's used by all ajax-calls
function showLoading(target) {
$('#' + target).html('My loading message');
}
jsfiddle http://jsfiddle.net/4xp1aag8/1/
Related
So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?
Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.
Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});
I have a confirmation dialog that leads to an update query when the user clicks a link.
<div class="ui-bar">
<a id="confirm" href="#" data-strid="<?php echo $str_info['str_id'] ?>">Confirm</a>
</div>
What I am looking to do is run an update query, then reload the previous page with the updated information on it.
I thought I accomplished this, but some sort of error keeps popping up in firebug and the ajax doesnt seem to be successful. The error only comes when I reload the page...and when I put a delay on it, there is no error, so I can't even read what it is.
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
}
});
$('.ui-dialog').dialog('close')
setTimeout(
function()
{
location.reload()
}, 750);
return false;
});
</script>
Is there any good way of accomplishing this? Again, in summary, I am looking to perform an update query, then reload the last viewed page (not the dialog) so that the changed info is displayed. ../../ajax/add_land is in PHP.
There are few better ways of achieving this but that is beyond the point, in your case you should do this:
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
$('.ui-dialog').dialog('close');
location.reload();
}
});
return false;
});
</script>
When ajax call is successfully executed it will call code inside a success callback. Ajax call is asynchronous action, that means rest of the code is not going to wait for it to finish. Because of this success callback is used. So there's need for the timeout.
One more thing, there's also an error callback, use it to debug ajax problems:
error: function (request,error) {
alert('Network error has occurred please try again!');
},
I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.
I got some progressbar Update Issues. What I like to do is, fire a ajax call which takes some time to complete and during the this call I'd like to fire ajax calls, set by an interval, to update my progressbar.
Since I could not find a solution and only found the Browser's restriction, which would match here. It's always max 2 calls active.
Still, my second call stays pending in Google Chrome, untill my first (main) call finished.
EDIT: full jquery script
// update cars cache
$('#cars_cache_update_run').bind('click', function(){
// remove button
$(this).remove();
// hide import widgets
$('#products_import_widget').css('display', 'none');
$('#vehicles_import_widget').css('display', 'none');
$('#orders_import_widget').css('display', 'none');
$('#test_data_widget').css('display', 'none');
// show blind
$('#cars_cache_update_info').css('display', 'none');
$('#cars_cache_update_blind').css('display', 'inline');
var carsUpdateInterval = setInterval(function() {
getImportState('http://localhost/index.php/import/import_state/cache_update', 'cars_import_progressbar');
}, 1000);
// ajax request
$.ajax({
url: "http://localhost/index.php/import/cars_cache",
async : true,
success: function(data){
$('#cars_cache_update_blind').css('display', 'none');
$('#cars_cache_update_success').css('display', 'inline');
clearInterval(carsUpdateInterval);
},
error: function(thrownError){
$('#cars_cache_update_blind').css('display', 'none');
$('#cars_cache_update_error').css('display', 'inline');
$('#cars_cache_update_error_msg').html(thrownError);
}
});
});
function getImportState(url, id)
{
$.ajax({
url: url,
success: function(data){
var json = $.parseJSON(data);
$.each(json, function(i, item) {
var progressbar_value = json[i]['state'];
$( "#"+id ).progressbar({
value: progressbar_value
});
})
}
});
}
Another funny thing, if I call the interval request by $.get I'll get a strange error..
Working with Codeignitor Framework.
GET http://localhost/[object%20Object] 404 (Not Found) jquery.1.7.min.js:4
send jquery.1.7.min.js:4
f.extend.ajax jquery.1.7.min.js:4
f.(anonymous function) jquery.1.7.min.js:4
(anonymous function)
Many Thanks for your help already, been trying for hours now.. Maybe I'm just a noob.. Haha.
rootless
Don't call multiple ajax with intervals. Try something like this:
function updateProgress(){
$.ajax({
url: "http://localhost/index.php/import/import_state/cache_update",
success: function(data){
var json = $.parseJSON(data);
$.each(json, function(i, item) {
var progressbar_value = json[i]['state'];
$( "#cars_import_progressbar" ).progressbar({
value: progressbar_value
});
});
updateProgress(); // after success, call the same function again
}
});
}
updateProgress(); // start updateProgress
Hope it helps :]
I am implementing a twitter-style follow/unfollow functionality with the following jquery.
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif" >');
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#follow'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;
});
});
I have a similar unfollow function. However i have the following problem:
When I have N items {1,2..i.N} each with id = followi and I click on the follow button. I find that some of the items respond while others do not. I suspect it is a pure javascript issue...otherwise i figure none of the buttons would respond at all.
Is it a timing issue...all help is appreciated. Also i'd appreciate it if you could point me to a simpler method.
Thanks!
Well you are doing the UI update in your ajax success handler, so the reaction time for the UI updated is based on the speed of the Ajax response. And if the server doesn't return successfully, the UI update won't happen at all.
A simpler method with instant response:
$(function() {
$(document.body).delegate(".follow","click",function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif"/>');
$('#follow'+I).fadeOut(200); // act instantly since we assume it will go well
$('#remove'+I).fadeIn(200); // act instantly since we assume it will go well
$.ajax({
type: "POST",
url: "follow.php",
data: info,
complete: function(){ //always remove the loader no matter if it goes well or not
$("#loading").slideUp();
},
error: function() {
//handle error
$('#follow'+I).fadeIn(200); // correct mistake
$('#remove'+I).fadeOut(200); // correct mistake
}
});
return false;
});
});