I have a search script written in jQuery. To submit a query a user presses enter and then a URL for the results page is created which is something like #search/QUERY/. However, when you either reload the page, click a result which goes to a different page or return back from a previous page the search results are no longer there. Why could this be?
My jQuery code is:
$(document).ready(function(){
$("#search").keyup(function(e){
if(e.keyCode==13){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query;
window.location.hash='search/'+query+'/';
document.title=$(this).val()+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
}
});
});
When a user reloads the javascript, all variables and functions are reinitialized. JavaScript does not pass variables from page to page. You either need a server side solution, or use JavaScript storage. The later may not work in all browsers.
This is because you are loading the search results dynamically with an AJAX call. If the page gets reloaded, that information gets lost.
A possible solution would be to store the search query and/or results in the user session. Then you will be able to automatically add the content on page reloads.
Related
So i am building a search on website, and main search form is on home page where user can input information's like, interests, books, movies.
And that form should submit to another page where search will be displayed.
So it's similar like any other search, but on search page, i should keep parameters in url, so it's not going to be POST, it would be GET.
Home page is something like mywebsite.com
And when form is submitted it's posted with GET parameters so user can keep search results in his url. Submitted post should lead to something like.
mywebsite.com/search?interests=sports&books=harry+potter&movies=moviename
And because it can take some time to search and load results i would like to load the page and than do an ajax post to search function and populate search results once ajax responds.
I've built in past some ajax content loading and post and load data with ajax, but all that while keeping on same page, i never built when you submit content from one page to another in wordpress.
Any suggestions how can i do that and make ajax grab the content ?
I found the answer, and it's actually quite easy, instead triggering ajax with function, for example function with button click.
Just trigger ajax on page load, and don't enqueue script anywhere else except on that page, this would help a bit.
if ( is_page_template('template-search.php') ) {
wp_enqueue_script('ajax_search');
}
This will ensure script is loaded only on that template page, and as for script it self, just load ajax on page ready:
jQuery(document).ready(function($) {
jQuery.ajax({
dataType: 'json',
url: search_flight.ajaxurl,
data: {
action: 'search_flight',
},
beforeSend: function() {
},
success: function(data) {
console.log(data);
},
error: function() {
}
});
});
I have a button call this script, so it does the post in the background, but I need to reload the current page to display an updated php query, I realize there was probably a better way in jquery to the query part, but its crunch time, and all I want to do is get a successful page refresh.
Because the buttons were generated in php, the javascript code is at the end of the body.
I've tried location.href, window.location.reload(true);, document.write which only wrote to the page, document.location.href did nothing.
We are using jQuery/jQuery mobile, I was not on front end dev team, so I'm desperate to get this to work. to clarify, I need a page refresh after the $.post() command, within this code, which does work
<script type="text/javascript">
$('#reserveBook').click(function () {
var isbn = sessionStorage.getItem('isbn');
$.post(
"../inventory/postpage.php",
{ isbn: isbn }
);
});
</script>
There's no point in using AJAX if you need a page refresh regardless. As Dan Bracuk said in his comment, you'd be better off just doing a traditional form submission.
However, if you're set on having the page refresh, just add window.location.reload() in the success handler for your AJAX call:
$.post(
"../inventory/postpage.php",
{ isbn: isbn },
function(response) {
window.location.reload();
}
);
I have a div that contains a student's schedule, and there is a drop-down box for selecting by semester.
Once they select the semester, there is an ajax post, but when it refreshes, it displays the entire website within that div (with the appropriate schedule for that semester).
It looks like an iframe within a webpage, as seen here: http://cl.ly/Dy3b
Here is the ajax post script
<script type="text/javascript">
$(document).ready(function() {
$('#term').change(function() {
var form_data = {
term : $('#term').val(),
ajax : '1'
};
var u = $("#schedulePortletURL").attr("href");
$.ajax({
url: u,
type: 'POST',
data: form_data,
success: function(msg) {
//alert(u);
$('#view-schedule').html(msg);
}
});
return false;
});
});
</script>
If possible, could you give me some suggestions of what to investigate to correct this? Thank you
My guess is that the call to the server is returning a full HTML page, and your code then puts the full HTML page into the view-schedule div.
To resolve this, create a new HTML page that you can call that contains a html fragment - the chunk that you want to live in the view-schedule div. Then change schedulePortletURL to point to the new HTML page.
Alternately, you could get the html back (the msg) and parse it to pull out the data you are interested in, then insert the filtered data into the view-schedule div.
Does the existing website have a API at all that you can call?
Another possibility is that some kind of error checker in your server-side script is mistakenly firing and causing a redirect to some web page. That web page is then retrieved by the AJAX, then displayed in the DIV. I have had this happen before. You should check your server side script.
If you do not have full control over the webpage you are fetching the fetched page should be considered unpure and you should use iframe. Remember that with .html(blob) you will also get javascript code, flash objects etc. which can be used to compromize your users.
If you on the other hand have full control over the fetched webpage (which I assume) you should make a if-statement in your template that checks if the request is ajax-based.:
Pseudo serverside template code:
if not request.is_ajax():
import header.html
import body.html
if not request.is_ajax():
import footer.html
I have a code that after clicking on a link ('#versionPageFromProdLink'), will redirect the page to the index page. The index page has that contains the content. I want to hide this after the page is redirected and show the next div that i have ().
The page is redirected however the jQuery function after the window.location.replace( url ); line is not called.
How will I be able to redirect and call the jQuery after page redirection?
Code:
jQuery( '#versionPageFrmProdLink').click( function(){
window.location.replace( url );
// jQuery code below is not called, <div id="versionMainContent"> is not hidden
jQuery(".versionMainContent").hide("fast", function(){
jQuery( ".versionProductContent" ).show();
});
});
As stated, the location.replace means the code "after" it won't execute. What you will need to do, is append a hash "index.html#divCode" or some such (you could also use a query string in this case) and then detect that onload / on document-ready for the index page, then update the hide/show status there.
This is fundamentally impossible.
Once you navigate to a different page, the previous page, including all of its Javascript, is gone.
You must handle the secondary executation after the redirect in the page you are redirecting to.
Example:
Page 1
jQuery( '#versionPageFrmProdLink').click( function(){
window.location.replace( url );
}
Note during redirection you can pass a query string in the URL to check a condition in the next page.
Page 2
Now that you redirected to the next page. You can place a document.ready function and run what is needed.
$(document).ready(function () {
jQuery(".versionMainContent").hide("fast", function(){
jQuery( ".versionProductContent" ).show();
});
Your design is the problem. Redirecting stops the flow of execution. You can use ajax to make a server call and continue execution.
Or, if you prefer you can perform a redirect and pass a URL parameter like ?hideVersionMainContent=true and perform the hide server side.
There are other ways to accomplish the task, but that should give you a few ideas.
The code after your location.replace operates on the page that you're leaving (if it is ever run at all; changing the location navigates away from the page and may well terminate your code right there).
You'll need to pass the information to display to the new page, and have code on the new page fill in the stats. There are lots of ways to do that:
On the query string
Via web storage (sessionStorage would probably make sense)
Cookies (but don't, it's not what they're for)
hi here is the problem: my url is like this
http://somesite.com?theSearch=someword&a=b&c=d
on this page search results are displayed and on this page i have put the functionality of ajax search i.e. the results are updated without the page reload but the problem is if the user clicks on any link on the page and then presses the back button he results on the page page with the search results of "someword" not the new word typed (i mean the word for which the ajax results were updated) the client complains it and i need to fix it anyone have a solution?
i am using jQuery
You can't change the location.href without a new load. What you can do is set the hash.
Every time you make a search change the hash
function doSearch(searchword) {
location.hash = searchword;
//your search code
}
Now the hash will refer to the latest search. And then add this code to "override" the get parameter ?theSearch=.
$(document).ready(function() {
if(location.hash.length>0) {
doSearch(location.hash);
}
});
Its not a nice solution since you will load 2 search results, but it will work.
You can try Sammy. It utilizes the URL hash (#) so you can create single page applications that still respond to the back button in your browser, just like facebook. And it runs on jQuery.