AJAX contact form in CodeIgniter
Few questions:
I'm using CI and JQuery AJAX.
In my code below, I assemble dataString
, which by default, is appended to the URL as a query string.
I've changed the AJAX "type" to POST, so my question is - how do I access dataString
in my CI app?
It would seem I still have to use
$name=$this->input->post('name')
Which to me, makes setting dataString
redundant?
--
I've tried searc开发者_如何学Pythonhing but can't really find anything concrete.
Would it be possible to still make use of CIs validation library and AJAX?
if($this->form_validation->run() == FALSE)
{
// what can i return so that my CI app shows errors?
}
Normally you would reload the contact form or redirect the user. In an ideal world I would like the error messages to be shown to the user.
Jquery:
$(document).ready(function($){
$("#submit_btn").click(function(){
var name = $("input#name").val();
var company = $("input#company").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var dataString = 'name=' + name + '&message=' + message + '&return_email=' + email + '&return_phone=' +
phone + '&company=' + company;
var response = $.ajax({
type: "POST",
url: "newsite/contact_ajax/",
data: dataString
}).responseText;
//$('#contact').hide();
//$('#contact').html('<h5>Form submitted! Thank you!</h5><h4>We will be in touch with you soon.</h4>');
//$('#contact').fadeIn('slow');
return false;
});
});
hope i've been clear enough - if anyone has a decent example of a CI contact form that would be great. there's mixed stuff on the internet but nothing that hits all the boxes.
thanks
As I wrote in the comments, you don't need to set a dataString
since jQuery can do it for you:
$(document).ready(function($){
$("#submit_btn").click(function(){
var response = $.ajax({
type: "POST",
url: "newsite/contact_ajax/",
data: $(your_form_id).serialize()
}).responseText;
//$('#contact').hide();
//$('#contact').html('<h5>Form submitted! Thank you!</h5><h4>We will be in touch with you soon.</h4>');
//$('#contact').fadeIn('slow');
return false;
});
});
If you use the jQuery $.post() function, you can explicitly name the post variables, then access them in your controller the way you suggested in your question.
$.post("<?php echo site_url("newsite/contact_ajax/";?>",
{my_name:name,my_company:company,my_email:email,my_phone:phone,my_message:message},
function(){
//callback function
},
html
);
In Your controller:
$this->input->post('my_name');
$this->input->post('my_company');
//etc
精彩评论