I have a basic PHP form here that sends an email when submitted:
<div id="contact">
<form id="contact_form" action="<?=base_url()?>contact/email_form" method="post" name="contact">
<h4>Questions? Comments?</h4>
<p>
<label>Name</label>
<input name="name" id="name" type="text" class="text" />
</p>
<p>
<label>Email</label>
<input name="email" id="email" type="text" class="text" />
</p>
<p class="message">
<label>Question</label>
<textarea name="message" id="message" rows="5" cols="5"></textarea>
</p>
<p class="alt">
<input value="Send Info" id="submitbutton" type="submit">
</p>
</form>
This form works well but I currently have no validation so if the form is submitted even when the fields are blank. Isn’t it possible to do validation with jquery?
Once the form is submitted it POSTS to a controller file in codeigniter which does the emailing logic using an email helper in codeigniter. See here:
if($this->email->send())
{
echo 'Message has been sent';
}
else
{
show_error($this->email->print_debugger());
}
As you can see this redirects to the email_form view and echos the results. Is it possible to just stay on the same contact page that has the form and have the results of the post show there instead of redirecting to the <?=base_url()?>contact/email_form view? I was thinking of having the Text of the SUBMIT button change to “Message Sent” or something like that and then clearing the form fields. This way they stay on the contact page.
Is all of this possible with jquery? Thanks!
Yes, it is all possible.
Specifically, you would do something like this:
You would be looking for the
$.post()function. However, I like to keep as much control as possible, so I use the$.ajax()function.They both take URLs and data to process, so this would be very useful for you.
You would handle a successful return (presumably, with a particular success code to process on) in the “success:” parameter of
$.ajax()or the success callback of$.post().From inside that function, you can change the content of DOM elements (like the button in your example) using CSS selectors and jQuery functions like
.html().Here are some tutorials to get started using jQuery!
Remember, just validating the email isn’t enough. You need to check other possibilities too!
In addition, make sure you are doing your validation on the server after the POST. Javascript can be turned off, and then (if you do validation on the browser) all your validation will do nothing to protect your server, or the public in general.
In summary, you can use
$.post()or$.ajax()in jQuery to pass the data to your server for processing.