Reputation: 379
I am trying to build a search page where the user inputs text into a search box and the page is generated based on the search. I am having timing issues because the blank search page is loading after the JS tries to edit the values on the page.
$.ajax({
type: 'GET',
url: '/index.php/content/generate_search',
data: {
search: input.val()
},
beforeSend: function() {
window.location.href = '/index.php/content/search';
},
success: function() {
$('.hero h1').text(input.val());
}
});
Upvotes: 1
Views: 8256
Reputation: 943220
This code:
beforeSend: function() { window.location.href = "/index.php/content/search"; },
… is causing the browser to leave the page and load a new one before it sends the Ajax request.
Consequently, the Ajax request gets cancelled. If it didn't, then there would be no JavaScript waiting to receive the response.
If you want to visit /index.php/content/search
and then initiate an Ajax request, then the JavaScript to initiate the Ajax request has to be on /index.php/content/search
. A page you've just left can't run JavaScript on the next page.
Upvotes: 0
Reputation: 14583
To check that the DOM is completely loaded, many steps have to be done taking all the browsers into consideration. (I cannot find the implementation in the jQuery source, but I will come back with a link).
The easiest and probably best way of doing it, since you're already using jQuery is by:
$( function() {
// your code here
} );
which is a shorthand for
$( document ).ready( function() {
// your code here
} );
EDIT
Ok, so as I promised, I came back with the implementation of document.ready
. You can find it here, on GitHub. Here is a permanent link to the current version of the file.
Upvotes: 2
Reputation: 1
onload is used for executing code on pageload
window.onload = function() {
// your code
};
Upvotes: 0