views:

45

answers:

3

Is there a simple tutorial for this somewhere?

Ideally I'd like to have a textbox and a button, and when the user clicks the button, the textbox is sent to the server, which returns a value based on it.

The client then populates another textbox with the return value, but all without refreshing the page.

If it's possible, showing/hiding a loading gif would be awesome too.

I'm not finding any simple tutorials for how to do this, can anyone point me in the right direction?

+1  A: 
Sam
+1  A: 

You would do it like this:

$.ajax({
    url: 'handlerscript.php',
    type: 'POST',
    data: {q: $('#theInput').val()},
    success: function(data) {
        $('.result').html(data);
        alert('Load was performed.');
    },
    beforeSend: function() {
        $('.loadgif').show();
    },
    complete: function() {
        $('.loadgif').hide();
    }
});

To walk you through the function, the first parameter url is set to the location of the resource you want to get a response from. The type parameter sets the HTTP method used, it is most commonly set to either GET (which is the default value) which appends any data being sent to the url or POST which appends any data being sent to the request header. data is an object or string containing the data to be sent to the requested page, it can either be in object form {param1: 'value1',param2: 'value2'} or as url encoded string "param1=value1&param2=value2". The success method is called when a response has been received from the server which was successful. The beforeSend method is called before the request is sent and the complete method is called when a response has been received from the server regardless of the success of the request.

For more info, check out the Official jQuery API documentation of the jQuery.ajax() object

Andrew Dunn