tags:

views:

356

answers:

3

I'm trying to AJAXIFY a form without using jQuery plugins. What is the process for making this happen. I have my form. What should I set the action to? What should the header script be? Keep in mind that I do not want to use any plugins. I just need a basic algorithm for ajaxifying forms using jquery.

+5  A: 

The action should be whatever it would be if you weren't using JavaScript.

NB: The links below all go to the relevant section of the jQuery documentation)

Then you would bind a function to the submit event that serialized the form data and used that to make an Ajax request (probably reading the URI from the action attribute). It would have to prevent the default action for submit events.

I believe jQuery sets an X-Requested-With HTTP header. So you just need to modify your server side process to return different data if that is present (with the right value). This could be as simple as just switching to a different view (if you are using a MVC pattern).

David Dorward
Instead of relying on X-Requested-With header, you can set an input 'flag' in the JS/jQuery submit handler: HTML: <input type="hidden" id="is_ajax" name="is_ajax" value="" /> ... JAVASCRIPT: $('input#is_ajax').val('Y'); ... Then server-side test for is_ajax POST value == 'Y'.
micahwittman
A: 

It depends. If you just want to send your values without reloading the page, I suggest you bind the submit event of the form to a function like so

jQuery('form#myForm').bind(submitValues);

After this, you would then set the function

function submitValues() {
   //do stuff here
   jQuery.ajax({
      //your ajax parameters here
   });

   //this is important to cancel the default action on submit (ergo. go to the address as defined in action
   return false;
}

For further infos on the ajax command, look here

Mike
+2  A: 

The simplest method is to use the $.load() method.

$.load(action, data, callback)

The action could be a PHP script, ASP page, or simply another web page. If the data is null, it performs a GET. Otherwise, it performs a POST. The callback method is executed when the method is complete (not necessarily successful).

http://docs.jquery.com/Ajax/load

For example:

<form>
    $.load("scripts/processOrder.php", { item: itemID, quantity: ordered }, function {
        window.location.href = "orderComplete.htm";
    });
</form>

When the form is submitted, the processOrder script is executed with the itemID and ordered arguments passed as data. When the script is finished, the browser navigate to the orderComplete page for additional processing or status display.

If you wish to take more control over the Ajaxification, you can use the $.get, $.post, or $.ajax methods.

Neil T.