optima header image by norlies.de norlies.de

Tutorial: Simple form-submit using AJAXSeite 2 von 3

1. Create a normal HTML-Form

Ajax formOn the screenshot you can see the form I created. It has a radio-select (male or femal, name: gender, values: m,f), an input-field (name: your_name), a select-field with two options (”I am coming” or “I am going”, name:doing, values:come,go), a textarea for the “answer” and a submit botton. There should be no problem to create this form. Make shure that the textarea has an id named answer_id.

Now, on the form-tag we need to call our ajax-funtion:

This will call our AJAX-function submitAjax() and, if everything is ok, give back false so the normal form-submit will NOT be executed. If AJAX-function fails, f.e. JavaScript is disabled, the normal form-submit will be executed instead.

The variables that are give to the AJAX-function are:

  • index.php, the url to request
  • this, the form itself
  • answer_id, the id of the HTML-element, where the AJAX-answer has to be written. In our example it is a textarea field. But it can also be a div or anything else.

Set an echo of a php-variable between the textarea-tags, so we can output our answer for the normal requests:

2. Create a PHP-function for the request

Now we need a PHP-function to answer the request. Place it on the top of your php-file.
I did the following…

As you can see, we give back a very meaningful answer. For normal requests we need to call this function, just before the form is written. So, insert the following before output of the html-form:

Nothing heard about AJAX until here? But the normal post should already work, isn’t it? If not, download my script at the end of the page and compare it with your own file.

Antwort schreiben







php(dot)net mysql gentoo GNU Linux Valid XHTML 1.0 Strict RSS Feed für Einträge RSS Feed für Kommentare

kostenloser Counter

yoomanity - Einfach mal was Gutes tun