I am trying to add AJAX functionality to a WordPress-based site.
When a visitor clicks a menu link, this code loads the text of the text of the required page into the main page:
$('#access a').click(function(event) {
  event.preventDefault();
  var url = $(this).attr('href');
$('#content').fadeOut(500, function() {
$('#content').load(url, function() {
$('#content').fadeIn(500);
});
});
});
My problem is with the search form. It has the following structure in the page:
<div id="my_search"><form role="search" method="get" id="searchform" action="http://myurl.com/" >
<input type="text" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form></div>
When I type a word testing into the form, and click the #searchsubmit” button or Enter key on the keyboard, I am redirected to a new WordPress page with the following address:
http://www.myurl.com/?s=testing
Here’s PHP code that makes it work:
<?php if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyten' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php
/* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called loop-search.php and that will be used instead.
*/
get_template_part( 'loop', 'search' );
?>
<?php else : ?>
<div id="post-0" class="post no-results not-found">
<h2 class="entry-title"><?php _e( 'Nothing Found', 'twentyten' ); ?></h2>
<div class="entry-content">
<p><?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'twentyten' ); ?></p>
</div><!-- .entry-content -->
</div><!-- #post-0 -->
<?php endif; ?>
QUESTION: I want to prevent the default behavior on #searchsubmit click and on Enter key click, and load the content of the search results (http://www.myurl.com/?s=whateverwordItype) into the #content of the main page. How can I do that?
(I suppose I just need to insert that php code inside jQuery code in some way, but the task is a little beyond my knowledge of jQuery and PHP.)
I would be grateful for a code snippet from a knowledgeable person, if possible.
Use some simple jQuery and javascript
In order to load your search results through an ajax request you can grab them directly from the search results page using the following code:
Note:
$(data).find('#content')
is assuming yoursearch.php
results aggregate in an element whose id is content i.e.<div id="#content"> ... Results ... </div>
The above would go into an external file or placed just before the closing
</body>
tag.You can customize the
search.php
page to organize your output results.