I'm loading comments with ajax in my website, and I'm sending to users notification with an anchor to the specific comment.
The anchor is not working, that piece of DOM isn't loaded yet.
How can I handle this? Maybe something "on ajax complete" ? I can do a script that launch "on ajax complete", but I don't know how to manage the anchor in the url.
$.ajax has a complete() callback that you can put code into. you can run location.hash = yourAnchorHash.
You could use jQuery's complete or success callback depending on whether you only want your code to fire when the call is successful or always when the call is complete.
$.ajax({
type: "POST",
url: "yourURL",
contentType: "application/json; charset=utf-8",
data: yourData,
async: true,
success: function (msg) {
//get stuff done when ajax call is successful
},
complete: function()
{
//get stuff done when ajax call is complete
}
});
Related
I'm diving into JavaScript and AJAX technologies now, and I understand AJAX and POST well with it. Now I wonder whether there's something like a broadcasting channel that my PHP code (in this case, Laravel controller) broadcast to, which then is received by JavaScript on the client side in order to manipulate something, say a process like this:
User clicks a button, a spinner is shown inside the button. Next to the button, there's a status label indicating the current process/task being processed. Finally, the button becomes a link or something else. So, what I want now is that I can update the status multiple times, since my current AJAX code will only receive one message, or one status, at the end of the process and that's it, nothing in between:
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
success: function(result)
{
console.log(result.status);
}
});
Now I wonder how this further works.
You can make use of beforeSend event of ajax and use to start a progress bar and when it completes you can make progress bar width to 100%
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
beforeSend : {
// start progress bar
},
success: function(result)
{
console.log(result.status);
// complete progress bar
}
});
Additionally, you could use css to apply transition to give the feeling the of progress in progress bar.
Use the concept of javascript callback or promise. You can creatw a script where when the button is clicked , a onclick function will run and change the content inside of tge button and when changed do the ajax call and if success call the promise again
I am doing a simple ajax call.but in the page i'm calling there's an ajax call to a pdf file. Is there a way to make the page wait until all the ajax calls on the requested page are loaded? I am getting as well the following error :"Can't create DocumentThreadableLoader"
$.ajax({
type: "POST",
dataType: "text",
url: '/test/test.pdf',
success: function (data) {
$('body').html(data);
},
data: body
});
Not recommended since ajax is meant for async calls
$.ajax({
type: "POST",
dataType: "text",
async: false, // ADD THIS LINE
url: '/test/test.pdf',
success: function (data) {
$('body').html(data);
},
data: body
});
Best Solution
Use callback structure and or jQuery built in promises (success, done, always, complete, etc).
load pdf data into html body
$( "body" ).load( "test/test.pdf" );
I have an ajax call inside ajax. Problem is I have to wait second ajax finish because until that time browser freezes. Why is this happening if I set it to async true? I dont want to wait for any response from this second inner ajax and I dont need any response from it. It is just an email notification to some users based and needs parameters from first ajax.
$.ajax({
url: 'route_process.php',
cache: false,
async: true,
type: 'post',
data: {type: document.getElementById('type').value},
dataType: 'html',
success: function(data) {
data = data.split("brk");
$('.spinner').css({'display':'none'});
$('#save_button').prop("disabled",false);
$.ajax({
url: 'sent_hike_drive_notification.php',
cache: false,
type: 'post',
async: true,
data: {type: data[1], insert_id: data[2], date_search_array: data[3], from_city_lat: data[4], from_city_lng: data[5], to_city_lat: data[6], to_city_lng: data[7], counter: data[8], insert_id2: data[9], date_search_array2:data[10]},
dataType: 'html',
success: function(result) {
}
});
Drive.resetRoute();
alert(data[0]);
},
Thanks all, now I found out the problem is not maybe in those ajaxs. User wants to move to another webpage through load when click on menu icon.
$('.main_body').find('.container').load(url);
This dont works until those ajax finish. So not complete browser freezes only I cannot navigate to next page.
Common, Ajax is indeed async but You should remember that a success handler is called only when the ajax call is complete whether sync or async So this inner ajax call can be called only when the first is complete. There is no way you can access inner ajax call without first being completed. All you can do is make an ajax call via callback on the success handler of the outer ajax.
This is not an exact answer to your problem but only a help/checklist :
The most common causes of the UI freezing on making an ajax call when the call is async:true are as follows:
A lot of Dom manipulation taking place on response of the call.
A lot of data is being sent by the server and processing it requires time.
If a session is being maintained and it is not closed before multiple ajax callbacks (this happens to avoid race conditions).
Something on the server side goes wrong/extremely slow on the ajax call and the client side is stuck.
Network speed is too slow.
EDIT: Based on the response from asker , to help others if they face similar issue.
Is there a redirection involved which is locking up with ajax response.
It is highly unlikely that the UI freezes despite all the check points mentioned above taken care of.
In any case the solution might be one of the following approaches :
Try making a call to the second ajax after a timeout of like 5000 ms.
Try promises : how does jquery's promise method really work?
(worst way)Try using an iframe to make the requests.
try to use promise.
$.ajax({
url: 'route_process.php',
cache: false,
async: true,
type: 'post',
data: {type: document.getElementById('type').value},
dataType: 'html'
}).promise().then(function(data) {
data = data.split("brk");
$('.spinner').css({'display':'none'});
$('#save_button').prop("disabled",false);
$.ajax({
url: 'sent_hike_drive_notification.php',
cache: false,
type: 'post',
async: true,
data: {type: data[1], insert_id: data[2], date_search_array: data[3], from_city_lat: data[4], from_city_lng: data[5], to_city_lat: data[6], to_city_lng: data[7], counter: data[8], insert_id2: data[9], date_search_array2:data[10]},
dataType: 'html',
success: function(result) {
}
});
Drive.resetRoute();
alert(data[0]);
})
I'm using the jQuery form plugin and when I use ajaxSubmit, the submission does happen (I checked for the 200 response) but the success callback is not called because I'm not seeing the alert(). Does anyone have any ideas as to why this is happening?
$("#edit-form form").submit(function() {
$(this).ajaxSubmit({
success: function(data){
alert("here")
},
method: "POST",
datatype: "json",
forceSync: true
});
return false;
});
EDIT: forgot to mention that the form is in an iframe (idk if that'll make a difference or not) created by a fancybox.
I have a function that pulls data from two locations and places the returned content on a modal dialog that is displayed to the user.
Both requests are asynchronous because they're cross-domain. The problem lies in that I don't want to display the modal until both requests have finished loading. How can I check to make sure both requests have finished before loading the modal?
I have tried placing the openModal functions in the success handler of the second request and that works when the first requests finishes loading before the second request, but sometimes this isn't the case.
Here's a copy of my code:
function loadData(id) {
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller1/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
}
});
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller2/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
openModal();
}
});
}
function openModal() {
// Open the modal
}
Check out the new version of jQuery -- 1.5. It has support for exactly your problem, you can check out this blog post for the solution of your problem: http://www.erichynds.com/jquery/using-deferreds-in-jquery/
You could put the one of the ajax requests inside the success callback of the other request, but that wouldn't be as efficient as having them both request at the same time. Then you'd just have to put the openModal call inside the success callback of the inner ajax request. Not optimal, it would be a quick and easy fix if this solution would work for you until a better option is found.
I'm going to keep thinking on this one...
$.when(
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "moon",
tagmode: "any",
format: "json"
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})).then(function (res1, res2) {
});