tags:

views:

303

answers:

3

I see lots of jquery tutorials from building the submit form from scratch, and that is cool, but I'm wondering if I can convert my existing form.

I'm using a typical form, and already have an email and blank values checking in place. Right now, on submitting the form, the user is taken to the confirmation php page withing form-submit.php.

I'd like to change that to just giving a user a line on the current page "Your form has been submitted"

Here is my form:

<form name="theForm" action="/contact-form2.php" method="post" onsubmit="return formCheck(this);" >
<table class="formTable" cellpadding="3" cellspacing="0">
  <tbody><tr>
    <td align="left"><b>Name:</b></td>
    <td><input name="name" id="name" size="25" value="" type="text" /></td>
   </tr>
  <tr>
    <td align="left"><b>Email:</b></td>
    <td><input name="email" id="email" size="25"  type="text" /></td>
  </tr>
  <tr>
    <td align="left"><b>Confirm Email:</b></td>
    <td><input name="email_confirm" id="email_confirm" size="25"  type="text" /></td>
  </tr>
  <tr>
    <td align="left"><b>Subject:</b></td>
    <td><input name="Subject" id="subject" size="35" value="" type="text" /></td>
  </tr>
  <tr>
    <td align="left" valign="top"><b>Message:</b></td>
    <td><textarea name="Message" id="message" cols="30" rows="6"></textarea></td>
  </tr>
  <tr align="left"><td>&nbsp;</td><td><input type="submit" value="Submit" onclick=" return checkEmail();" />&nbsp;<input type="reset" value="Reset" /></td></tr>
</tbody>
</table>
</form>

So is it possible to just change the on submit or onclick to be able to both submit the form through the external php file, and stay on the same page?

A: 

Yes, you can change the onclick form action to a javascript:myajaxsubmit() function.

Xorlev
Cool. Thanks for telling me what to look for.
Joel
Will that replace the existing html without a full page reload?
HerbN
Can you please give me more details of what I would change in the above form to achieve this with myajaxsubmit?
Joel
+1  A: 

You can convert the existing form, but it is not as simple as just changing the onSubmit or onClick events.

When you use jQuery or another Ajax library to do a callback you are loading new content into the existing page. To do that you need a labeled block, usually a div, to contain any data to change. You also need to write the wrapping code for the callback to send it and to update the page's HTML.

The quick and dirty version on your form would be to wrap the table in a div tag and the Ajax call return new HTML for that div. Your new target for onsubmit would be the wrapping code for the callback I described above.

You still need to do all the work to use jQuery and point it to the right places. As I use prototype.js I can't really detail the jQuery process, but all the tutorials you are reading can.

HerbN
I''m already using jquery in other places, so I can figure out how to replace div contents. What I need to know is:1) how to send this form to my php script without leaving the page and 2) where I will put the ajax object in the for to call the div replacing action.
Joel
Ah, yes, you should be able to. Unless jQuery is odd it should be able to read any page. That said, you won't need all the components in that page now.
HerbN
+1  A: 

Yes it is. I would suggest introducing some Javascript (the following example uses jQuery):

<script type="text/javascript">
// when the DOM is ready
$(document).ready(function() {
    // bind some code to the form's onsubmit handler
    $('form[name=theForm]').submit(function() {
        if(formCheck(this)) {
            // $.post makes a POST XHR request, the first parameter takes the form's
            // specified action
            $.post($("form[name=theForm]").attr('action'), function(resp) {
                if(resp == '1') {
                    alert('Your form has been submitted');
                } else {
                    alert('There was a problem submitting your form');
                }
            });
        }
        return false;
    });
});
</script>

The return false at the end of the above submit handler prevents the browser from loading up the form's action (following the url) in the traditional way. Furthermore, if Javascript is not present, the form will submit the old school way, so essentially you have added a layer of usability above your standard form implementation which degrades gracefully.

I would like to point out that it is always a good idea to provide the user with realistic feedback. That is to say, the ajax posting of the form can capture some indication of this from the server, in the above example I have assumed that a '1' means that the record was successfully saved, and a '0' means it was not saved (the query failed, etc.). The message displayed to the user depends on this outcome.

karim79
@karim79: You have provided a complete implementation. However, when the data submition fails it would be better to just add a warning instead of destroying the form and all the data the user has entered into the fields. Thus: $('form[name=theForm]').append('<div align="center">There was a problem submitting your form</div>');
Majid
@Majid, ouch! what an annoying oversight. Just changed the stupid replaces with alerts :)
karim79
Hi Karim-I am still taken to the other page on submit even with this code...
Joel
@Majid, although appending a formatted div as you suggested is clearly the better way to get the message to the user.
karim79
@Joel - have you included the jquery script in the HEAD section of your document?
karim79
hi-well I had put the script above the form. When putting it below, now I do get a response-but it is telling me the form could not be submitted. (the form does submit fine normally).
Joel
@Joel, the example code relies on the server returning a 1 for successful submission of the form or otherwise for failure. If you replace the code inside the $.post block with a simple alert('success'); you won't get the failure message anymore :) However, I strongly suggest that the message reflect whether or not the record has been saved.
karim79
ah-this form is simply sending an email to me-not going to a database...does that change things? Sorry I don't know enough yet to give full information. :(
Joel
Joel, you need to include the jQuery library with a line in <head> section of your file; like this: `<script src="jquery.js" type="text/javascript"></script>` Make sure you point to the right place (instead of `src="jquery.js"` you may need something like `src="../js/jquery.js"` depending on where you keep the jquery source file.
Majid
@karim79, I think using alerts is fine here too, though for the success condition we'd better also disable the form inputs.
Majid
I do have jquery already there-it's pointing fine and doing exciting things on other parts of the page :-D The problem is that the form itself is not actually submitting now with this code here...I am getting a 200 OK on Firebug saying the form is being seen when clicking submit.Ah-but I am getting this error in firebug "you cannot send a blank form" ... hmm
Joel