In my website http://www.eventiame.com/publicar/ there's a form with several fields.
When the page loads it shows the pace animation (it does some ajax request when loading so that's ok) but when I submit the form (I do it via ajax too) the animation doesn't appear.
I tested uploading an image (so it would take longer) and still no animation is shown.
I also tried changing the "async" parameter to true or false in the akax request but still no good.
Here's the specific code for the ajax call which is not working:
$.post('Sample.php,$(this).serialize(),function(data){
$(target).html(data);
},'html');
You may try this:
$(document).ajaxStart(function() {
Pace.restart();
});
I had this same problem and I found a solution in Pace issues section. Source
I hope my answer is not too late, but in case of those that might still need it, i had thesame issue also and i solved it.
By default, Pace will show any ajax requests which begin as a part of a normal or ajax-y page load, or which last longer than 500ms. your ajax request didnt trigger the pace because it's too soon.
1, Modify the Pace.js :
Find restartOnRequestAfterunder the defaultOptionsand change it to desire time (in milliseconds) value 5 ms.
restartOnRequestAfter: 5,
2, Tracking:
By default, Pace will only track GET HTTP method, so add all other method you might need such as POST request.
ajax: {
trackMethods: ['GET', 'POST', 'PUT', 'DELETE', 'REMOVE'],
...
}
SOURCE: http://github.hubspot.com/pace/
You have a missing closing single quote, should be:
$.post('Sample.php', $(this).serialize(), function(data){
$(target).html(data);
}, 'html');
Related
Today one of the weirdest things i have ever seens just happened.
I have a loop in a page that does a synchronous ajax request for each element of the loop. Since it was taking too long i decided to stop the loop by refreshing the page.
When the page loaded i couldn't click on any element of the page so i checked Firebug console and i saw that the ajax calls of the previous loop were still being done (the loop is set to start after i click on a link, so it can't start as soon as page loads).
To stop the loop i had to close the current tab and open my page in a new one.
It's worth mentioning that i have a datatables table on that page and i have enabled the option to save the table state, maybe this is interfering with my code (the loop itself is not part of the datatables initialization, though it uses data from the table).
I have also noticed that some things of the loop aren't being done. It should've changed the page of the datatable by time to time, and it should've written in the javascript console, both things don't happen after i refresh the page, the ajax calls are still going though.
Here's the code where the loop is contained:
//This variable will contain a reference to the datatable
var oTable;
var isWorking=false;
//Change the datatables page
function changeTablePage(oTable, page, clear){
if(clear){
oTable.fnClearTable();
oTable.fnDraw();
}
oTable.fnPageChange(page);
}
//This part is inside a document.ready block
$(document).on("click", ".validation-all-click", function(event){
if(!isWorking){
isWorking=true;
//saves the current page, will be needed for later
var page=oTable.fnPagingInfo().iPage;
var numberPage=0;
var done=false;
while(!done){
console.log("page: "+numberPage);
changeTablePage(oTable, numberPage, false);
var nNodes = oTable.fnGetNodes();
var len=nNodes.length;
$('.validation-click', nNodes).each(function( index, value ){
//id of the element to be validated
var id=$(value).data("rowid");
//Calls the validation url
$.ajax({
url: "/validate?id="+id,
async: false
});
});
//if the datatables page has 0 items, then it's done
if(len==0){
done=true;
}
numberPage++;
}
//goes back to the original page
changeTablePage(oTable, page, true);
isWorking=false;
}
});
I don't want this behavior to happen, but i have no idea on why it's happening and how to prevent it
Thanks for sharing your story. I don't see any specific question in the post, so I'll just comment on whatever I feel like.
As I understand it, browsers aren't required to redraw the UI while JavaScript is running. Since there's a script blocking on a synchronous ajax request, maybe it's to be expected that you don't see the changes to the table until the loop finishes.
Furthermore, it may also be that the browser isn't required to destroy a page while its scripts are running. That would explain why you saw requests in Firebug after refreshing the page--perhaps the previous copy of the page was still running in a hidden state.
edit: valepu reports in a comment, below, that the table does change while the script is running. That's fine. The browser can probably determine that it can redraw the UI during the ajax call (which doesn't affect the JavaScript environment). valepu also clarifies that the visual updates stop after refreshing the page, though the requests continue to go out. This is also consistent with the idea that the browser has just hidden the previous page (until it finishes) and loaded up a new copy of the page when refreshing.
As for how to prevent it: the most reliable way would be to use asynchronous requests, or otherwise yield between requests. Sorry, folks.
I have solved by adding a variable that will stop the loop when i exit the page:
var stopLoop=false
$( window ).unload(function() {
stopLoop=true;
});
both loops will now check if this variable is false before executing the code inside the loop.
This works on Firefox but not on Chrome though.
-- EDIT --
In the end i have solved by editing the code in order to make the ajax calls asynchronous and using the callback functions to continue the cycle, though it was no simple task (some days later i found a new solution that allowed me to do all that i needed in a single call when i found out how to recover the parameters used by datatables to retrieve data, but this has nothing to do with the original question). So, for future references: expect this "weird" behaviour when making a loop with ajax synchronous calls
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var siteTitle = $.ajax({
url: 'http/',
type: 'POST',
data: { http: 'siteTitle' },
success: function(title) {
$('.title').html(title);
}
});
</script>
I have a site title and it's grabbed through jQuery's $.ajax() call. The title of the site needs to be configurable. So I grab the title through the ajax request but it doesn't show up on the site for about ~1.5s.
Is there anyway to decrease this time?
The site title is in about 6 places so it looks awkward with nothing there for ~1.5s.
Thanks.
I would recommend that you handle the configurable title on the server and render it with the page instead of requesting it through ajax.
Not sure what server side language you're using, but most will have a way to generate dynamic content on the server and pass it back to the browser.
Have some default text like "loading..." as your title value. Then it won't be so bad when the ajax call updates it 1-2 seconds later.
If it is a span element (instead of a window title) then maybe even a loading gif. I think users are getting used to seeing those spinners now and won't question the extra 1-2 seconds wait time for the actual title
working on a commenting system using PHP.
Everything works, the insert, the validation and also the ajax call.
Currently i am doing a .load() on the container that holds the page content.
However, this causes issues when trying to post comments again. The javascript doesnt work, some of the javascript functions linked with the comments also dont work and little things like that.
How should i be dealing with comments, every time a user posts one.
Like on facebook for example, you post a comment and the new one is just placed underneath the last.
The only thing i can think of i using .append() and appending the new comment to the list.
In my PHP page i could set a JSON return of the username, the comment, the users profile picture etc and then append all of that data back?
Otherwise is there a better method of simply 're-loading' the div container after the success ajax call?
Thanks, what i have works... but i want to be learning things the CORRECT way.
Craig.
You can use $.ajax to load new comments and use .append() or prepend() to insert the new comments in the container. If you wrap the call in a function you can call the function over and over (for instance every 2 seconds) to check for new comments.
If I remember correctly .load() will only execute when the element is ready after browser refresh.
What things are not working? Remember that events and data must be bound after succesful AJAX call. Meaning if you bound events to links when the page loaded they are obviously still in effect. But if you insert a link later on it does not have any events.
What I would normally do is something like this:
$.ajax({
url: 'ajax.php',
data: { 'parameters': 'yada yada' },
dataType: 'json',
success: function( data ) {
$('.links').unbind().click(function() { alert('hello!'); });
}
});
The reason for the .unbind() is that you will otherwise bind several events on the existing links - and you don't want that ;-)
The client I am working for is trying to make it so that his page never has to reload. Instead he just wants to use AJAX. Now I realize that the way im doing it is not a very efficient way to do it but it is the easiest and you would understand why if you would see his site..
I'm trying to get it to work so that AJAX will refresh only parts of the page or the whole page.
My code is:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
function refresh (update) {
$.get(location.href, function (data) {
console.log(data);
var EL = $(data).find(update);
var HTML = $('<div>').append(EL.clone()).html()
alert(HTML);
$(update).replaceWith(HTML);
});
}
</script>
</head>
<body>
<div style="font-size: 64px;">The current timestamp is <b class="time"><?php echo rand(999, 9999999); ?></b></div>
<br><br>
<button onclick="refresh('.time')">Refresh Time</button>
</body>
</html>
When you first load the page PHP generates a random number. Hitting the refresh button is suppose to refresh this number. However, the same number stays there. The request returns the exact same page instead of return a page with a new number.
And again, people note that I know this is not a very efficient way to do this, but its the way i'm trying to get it to work
Am I doing something wrong? (besides requesting the whole page when only actually using part)
EDIT
You can try it out here: http://methods.x10.mx/projects/refreshPageParts.php
Change your call to this, to break the caching:
function refresh (update) {
$.ajax({
type: "get",
cache: false,
url: location.href,
success: function (data) {
$(update).replaceWith($(data).find(update));
}
});
}
See the notes on caching in the documentation: http://api.jquery.com/jQuery.ajax/
By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false. To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true.
I tested your example on my local wamp stack and it is working fine!
btw: you forgot semicolon after the following line (It is not necessary though)
var HTML = $('<div>').append(EL.clone()).html();
EDIT: your code is working... also on the url you provided. The strange thing is you have to wait a few minutes before it is working. So when you visit the page and press the button, the time won't be updated... however if you wait few minutes it will... only once then you have to wait again. I bet your server is caching the page. So your problem is server side... disable the cache and it will work!!
EDIT:
you also could try to make the get url dynamic with a dummy parameter like so
http://methods.x10.mx/projects/refreshPageParts.php?v=dummy
maybe you don't have to make dummy dynamic, it might work with a static variable also. i'm curious, let me know ;-)
I am trying to do async page open inside div with $.ajax but i am still having about 3sec delay after clicking link and that time page is jammed. Happens at least chrome and sasfari. Where am i going wrong way..?
$.ajaxSetup({
async: true
});
$(document).ready(function() {
$("#Button").click(function(evt) {
$('#change').html('<p><img src="ajax-loader.gif" width="15" height="15" /></p>');
$.ajax({
url: "reg.php",
cache: false
}).done(function( html ) {
$("#change").html(html);
});
});
});
No, asynchronous ajax requests like that don't hold up the browser. The problem is elsewhere, in code you haven't shown. The code you've shown will correctly do an async request.
Speculating on possible issues with what we can't see:
If the link has an href, you're not cancelling the default action, so it could be loading the page. You can prevent the default by calling evt.preventDefault() within your click handler, or by doing return false; at the end of it (which does that and also stops propagation).
If you have other code elsewhere setting async: false as the default, perhaps your ajaxSetup changing it back isn't getting called.
If you are using PHP sessions then the script will halt the browser until reg.php is completely finished.
In reg.php you will need to add this somewhere:
session_write_close();
This will allow you to read the session data but not write to it.
This is the case because you would probably never want two ASYNC scripts trying to write to the session at the same exact time.