Ajax

Ajax related tutorials, plug-ins and stuff.
There are 6 articles published in this category. Please try the search if you can't fint what you're looking for.


Live ajax search using the Google search API

Monday, May 19, 2008

I realized the bogus-search-results script from Live Ajax Search jQuery Plug-in may not have been very satisfying to you visitors, so I thought I'd show you how to use the Google search API to create a real live ajax search on your site.

This example requires PHP and if you're running any version below 5.2 you'll need Michal Migurski's JSON-class as well.

The PHP (and HTML erm..)

The Google search API is basically just a URL you pass a search-query to and it returns a JSON with results.
I won't go in to too specific details about the API, if you wish to know more please refer to the documentation.

Create a search-results.php file and put the following code in it:

<?php
require_once 'JSON.php';

# Your site URL
$site 'exscale.se';

# Make sure a search-query was entered
if(isset($_GET['q'])) {
    
# Are we on the first page?
    
$start = isset($_GET['start']) ? $_GET['start'] : 0;

    
# The URL to the Google search API
    
$url 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' .urlencode($_GET['q']) .'%20site:' .$site .'&rsz=large&start=' .$start;

    
# Initiate CURL
    
$ch curl_init();
    
curl_setopt($chCURLOPT_URL$url);
    
curl_setopt($chCURLOPT_RETURNTRANSFER1);
    
curl_setopt($chCURLOPT_REFERER'http://' .$site);
    
$body curl_exec($ch);
    
curl_close($ch);

    
# Decode the JSON returned (you need the JSON-class if json_decode is undefined)
    
$body json_decode($body);

    
# Build array
    
$i    0;
    
$search_results = array();

    
# Loop through all results
    
foreach($body->responseData->results as $r) {
        
$search_results['results'][$i]['title'] = $r->title;
        
$search_results['results'][$i]['url'] = $r->url;
        
$search_results['results'][$i]['content'] = $r->content;
        
$i++;
    }

    
# Loop through all the pages of results
    
if(isset($body->responseData->cursor->pages)) {
        foreach(
$body->responseData->cursor->pages as $p) {
            
$search_results['pages'][] = $p->start;
        }
    }

    
# Make sure some results were returned
    
if(isset($search_results['results'])) {
        
?>
        <h2>Search results for &quot;<?php echo @$_GET['q']; ?>&quot;</h2>

        <ol<?php echo @$_GET['start'] > ' start="' .($_GET['start'] + 1) .'"' '' ?>>
        <?php foreach($search_results['results'] as $sr) { ?>
            <li>
                <h3><a href="<?php echo $sr['url']; ?>"><?php echo $sr['title']; ?></a></h3>

                <p><?php echo $sr['content']; ?><br /><a href="<?php echo $sr['url']; ?>">Read more</a></p>
            </li>
        <?php ?>
        </ol>

        <?php if(isset($search_results['pages'])) { ?>
            <ul>
            <?php $i 0; foreach($search_results['pages'] as $p) { $i++; ?>
                <li>
                    <?php if((!isset($_GET['start']) && $p == 0) || (@$_GET['start'] == $p)) { ?>
                        <strong><?php echo $i?></strong>
                    <?php } else { ?>
                        <a href="/search/?q=<?php echo @$_GET['q']; ?>&amp;start=<?php echo $p?>"><?php echo $i?></a>
                    <?php ?>
                </li>
            <?php ?>
            </ul>
        <?php ?>
        <?php
    
}
    else {
        
?>
            <p><strong>Sorry, there were no results</strong></p>
        <?php
    
}
}
?>

As the search-results.php-file doesn't contain any DOCTYPE, html, head or body-elements it is obviously not valid HTML. How you implement the search-results on your own site differs depending on what type of site-structure you've got set up. Regardless you should probably be able to figure it out.

If you do include some sort of head/foot-templates in the search-results make sure not to include them if it's an ajax-call (isset($SERVER['HTTPXREQUESTEDWITH'])).

I'm going to assume the search-results.php will be included from a search.php-file in the root of your site. So visiting /search.php would display the search-results (provided a query is set) along with whatever else your site consists of, but visiting just /search-results.php will only output the results.

The HTML form

Now all you need to do is set up a form that submits a get-request to search.php:

<form method="get" action="/search.php">

    <p>
        <label for="q">Search</label> 
        <input type="text" name="q" id="q" /> 
        <input type="submit" value="Find" />
    </p>

</form>

The Ajax-magic

And now hijax that form:

<script type="text/javascript" src="http://aframework.googlecode.com/svn/trunk/__core/Modules/Base/1-jquery-1.2.1.js"></script>
<script type="text/javascript" src="http://aframework.googlecode.com/svn/trunk/__core/Modules/Base/jquery.dimensions.js"></script>
<script type="text/javascript" src="http://aframework.googlecode.com/svn/trunk/__core/Modules/Base/jquery.liveSearch.js"></script>
<script type="text/javascript">
    $('#q').liveSearch({ajaxURL: '/search-results.php?q='});
</script>

</body>

I've set up an example-page and you can also download the example-files.

Enjoy!

Woopsy

Seems curl_init isn't available from my host (bummer). The example should still work for you locally though,and hopefully live as well (unless you suffer from the same limitations).

jQuery Live Ajax Search Plug-in

Friday, May 16, 2008

Use this plug-in on an input[type="text"] and it will display search-results based on the input's contents on key-up.

The search-results box is fully customizable using CSS and its contents is completely up to you.

I've set up a simple example with some bogus search-results.

You use it like:

$('input[name="q"]').liveSearch({ajaxURL: 'my-search-results.php?q='});

The ajaxURL-parameter should point to your back-end search-results. Whatever you see when you visit that address in your browser will be put in the search-results div.
If you don't use $_GET['q'] for the search-query you need to change the "?q="-part to, for example, "?searchTerm=".

The bogus-search-results.php-file used in the example looks like this, but yours can look however you want.

<h2>Search results for &quot;<?php echo @$_GET['q']; ?>&quot;</h2>

<ol>
    <?php for($i 0$i 10$i++) { ?>
        <li>
            <h3><a href="#">Lorem ipsum <strong><?php echo @$_GET['q']; ?></strong> lorem</a></h3>

            <p>Lorem ipsum dolor sit amet lorem <strong><?php echo @$_GET['q']; ?></strong> ro the lorem in lipsum dolor sitamus <strong><?php echo @$_GET['q']; ?></strong> lorem ipsum?<br /><a href="#">Read more &raquo;</a></p>
        </li>
    <?php ?>
</ol>

You can as usual get the code and the default styling from google code. Have fun. Oh, and it requires dimensions.

Submit form using ajax jQuery plug-in

Sunday, January 20, 2008

This plug-in will prevent your form's default action on submission and instead submit all data using XHR. Use it like this:

// submit the '#contact form'-form using XHR, then update the #contact-element with the response
$('#contact form').ajaxSubmit('#contact');

It will submit to the form's action using the form's method unless specified differently when calling the plug-in.
The plug-in will submit any element in the form that has a name-attribute to the URL specified in action.

The ajaxSubmit plug-in takes two arguments, the first is either a string containing a CSS-selector pointing to the element that should be updated with the response, or a custom callback-function that will run after ajax-response is ready. The response will be passed to the callback function.

The second argument is a config-object where you can set action, method and loading. They default to form's action, form's method and 'Loading...'. The loading-var is used to replace the text in the submit-button. You may wanna change to 'Sending...' or something similar if that is more appropriate.

You can get the latest version of the jQuery ajaxSubmit plug-in here.

Ok, enjoy.

Live form-validation jQuery plug-in

Sunday, January 20, 2008

This plug-in adds valid/invalid icons next to form-controls and validates them as user types.

It requires PHP for the validation so your server needs to have PHP installed.
An easy way to check if PHP is installed is to create a file (foo.php), put:

<?php
    phpinfo
();
?>

in it, upload it to your server and then go to the file in your browser and see what it says.
There should be a load of information if you have PHP installed.

The form-validator requires you use some common names for your form-inputs.
There's only three fields specified at the moment; 'name', 'email' and 'message'. But if you're not completely unfamiliar with PHP you should have no problem adding more of your own.
Also, if you prefer 'content' or 'comment' or something instead of 'message', simply open the FormValidator PHP-class, find the line that defines the message-validation and rename to whatever you like.
Anything passed to the FormValidator that isn't defined in the class will always return true.

Now, to validate a form using jQuery you will obviously need your HTML form (the plug-in looks for input[type="text"] and textarea) set-up, and a .js-file that initiates the plug-in:

$(document).ready(function() {
    $('#contact form').liveValidation({
        validIco: 'gfx/validIco.gif',        // url to valid icon
        invalidIco: 'gfx/invalidIco.gif',    // url to invalid icon
        action: 'AjaxFormValidator.php'        // url to php-file
    });
});

You can download a zip with the 2 required PHP-files, a couple of valid/invalid icons, an example PHP-file as well as jQuery and the live validation plug-in here. Or you can always get the latest version of the plug-in here together with the two needed PHP-files: FormValidator and AjaxFormValidator.

Have fun!

Ajax/Hijax Rating Exempel

Wednesday, April 18, 2007

Det är mycket snack om ajax nu för tiden, och jag tänkte bara visa ett simpelt exempel på hur man använder ajax på "rätt" sätt. Dvs, det är tillgängligt även om användaren inte har JS aktiverat.

Kolla in exmplet live här.

Ajax Scan

Tuesday, October 03, 2006

Ajax-Scan is a php/javascript (ajax) directory-listing script. It works like "explorer"on windows.

Ajax-Scan is still a bit under construction, but when i'm happy with it i'll release the code.

Ajax-Scan



Post It

From June 02 to April 23

  1. Mogrify is what you're looking for if you want to convert multiple images to multiple other images in ImageMagick
  2. Tommorrow, finally, the inFamous demo will be friggin availble on PSN!! Suweeeeeeeeet
  3. Fuck canvas is cool, I've started playing around with old 3D-shit again :)

February 2012

S M T W T F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29


Recent Comments

  1. buy thesis on A Modular Design Pattern:
    Choosing buy dissertation service a...
  2. research papers on A Modular Design Pattern:
    Want to find cheap literature essay...
  3. professional resume service on A Modular Design Pattern:
    Yeah doubtless very constructive f...
  4. website submission service on A Modular Design Pattern:
    Are willing to get Search engine op...

Style Switcher

The style switcher allows you to change the look and feel of exscale.se.
Only CSS and JavaScript are changed. The XHTML stays the same.

For more information about the styles, check the styles page.


Categories


Random Quote

Det gör inget att jag skrattar för det jag tänker på är så roligt - Ostens Linda


Random Images




Answer This!

Do you find the "scroll-pagination" annoying? (If you don't know what it is, scroll to the bottom of the first-page)


Blog Roll