codeigniter and ajax contact form - php

I'm trying to use ajax within my contact form in a codeigniter app. I have it to where the ajax call is made, but no post data is being sent to the server. I can't figure out why. Please help.
I do have some returns in there, but they do nothing. Also, $this->input->post('name') is null.
Form view
<?php
echo form_open('welcome/submit_contact');
echo form_error('name');
echo form_label('Name', 'name'"');
echo form_input('name', set_value('name'), 'id="name);
echo form_error('email');
echo form_label('Email', 'email');
echo form_input('email', set_value('email'), 'id="email"');
echo form_error('phone');
echo form_label('Phone', 'phone');
echo form_input('phone', set_value('phone'), 'id="phone"');
#echo '<h5>Do not start with "1" and no dashes.</h5>';
echo form_error('message');
echo form_label('Message', 'message');
echo form_textarea('message', set_value('message'), 'id="message"');
$submitData = array(
'name' => 'submit',
'value' => 'Submit',
'id' => 'button'
);
echo form_submit($submitData);
echo form_close();
?>
<script type="text/javascript">
$(function() {
$('form').click(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('welcome/submit_contact'); ?>",
type: "post",
data: form_data,
success: function(msg) {
$('form').prepend('<h5 class="good">Message sent!</h5>');
$('h5.good').delay(3000).fadeOut(500);
alert(msg);
}
});
// prevents from refreshing the page
return false;
});
});
</script>
Controller function
function submit_contact()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 class="bad">', '</h4>');
$name = $this->input->post('name');
echo "name = ".$name;
$this->form_validation->set_rules('name', 'Name', 'trim|required|alpha_dash|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('phone', 'Phone' , 'trim|integer|exact_length[10]|xss_clean');
$this->form_validation->set_rules('message', 'Message', 'trim|required|max_length[1000]|xss_clean');
// there are validation errors
if($this->form_validation->run() == FALSE)
{
return "error";
}
else // there are no validation errors
{
/*************************
need to actually send the email
*************************/
return null;
}
}
EDIT: I've updated the code in my question. Basically now if there are validation errors, how would I get them to display on the form? I'm assuming I would return a value from my controller and then have a statement in my ajax success that if msg == "error" display the errors elseif msg == null, display success message. But how would i tell my view to display those errors based on an ajax success variable?

i think you should put id on input and textarea not on label i.e.
$data = array
(
"name"=>'message',
"value"=>'message',
"id"=>'message'
)
form_textarea($data);
if you set the id on the label then jquery will pick up nothing from what the user inserted and also codeigniter validation won't work correctly. This is why your post result to be NULL
the same for other input field
EDIT
you are asking data via ajax so return a nice json object (remove all your debug prints first):
// there are validation errors
if($this->form_validation->run() == FALSE)
{
echo(json_encode("validate"=>FALSE));
}
else // there are no validation errors
{
/*************************
need to actually send the email, then send you mail
*************************/
echo(json_encode("validate"=>TRUE));
}
then test it on your ajax success function to display positive or negative message
<script type="text/javascript">
$(function() {
$('form').click(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('welcome/submit_contact'); ?>",
type: "post",
data: form_data,
dataType: "json"
success: function(msg)
{
if(msg.validate)
{
$('form').prepend('<h5 class="good">Message sent!</h5>');
$('h5.good').delay(3000).fadeOut(500);
}
else
//display error
}
});
// prevents from refreshing the page
return false;
});
});
</script>

Related

Ajax form with codeigniter validation

I am trying to make ajax form validation work in codeigniter.
Form and ajax are both in views/products/addproducts,
<script type="text/javascript">
$(document).ready(function(){
$("#submitProducts").click(function(e){
e.preventDefault();
var dataString = $("#add-products-bulk-form").serialize();
var url="products/addproducts";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
dataType: 'json',
data:dataString,
success:function (res) {
res=$.parseJSON(res);
if($.isEmptyObject(res.error)){
alert(res.success);
}else{
console.log("hasn't run form yet");
}
},
})
})
});
</script>
here is my Products controller:
public function addproducts()
{
$data['title'] = "Add Products";
$this->load->view('templates/header', $data);
$this->load->view('products/addproducts');
$this->load->view('templates/footer');
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
if ($this->form_validation->run() === FALSE)
{
echo "did not pass validation";
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
echo "did pass validation";
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}
I don't get any response when I click submit button if I keep the code above way. But if I get rid of line dataType:'json', I will get error
VM1679:1 Uncaught SyntaxError: Unexpected token d in JSON at position 0
at Function.parse [as parseJSON] (<anonymous>)
at Object.success (addproducts:140)
at i (jquery-3.1.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2)
at A (jquery-3.1.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)
If I get rid of both dataType:'json' and res=$.parseJSON(res), when I enter a duplicated product and click submit, and console.log(res), I get the following in the console, It did return the res and the source code of the whole page addproducts.
did not pass validation{"error":"<p>The Part number field must contain a unique value.<\/p>\n"}<!DOCTYPE html>
<html lang="en">
<head>
I did not paste the whole source code here. and res.success will alert undefined.
I have been stuck for days, please help. I will provide more details if needed.
Thanks!
To clean up my earlier comment...
public function addproducts()
{
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
header('Content-Type: application/json');
if ($this->form_validation->run() === FALSE)
{
$this->output->set_status_header(400);
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->output->set_status_header(200);
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}
Now you can use the success callback to listen for a successful response and the error callback to listen for an error response...
<script type="text/javascript">
$(document).ready(function(){
$("#submitProducts").click(function(e){
e.preventDefault();
var dataString = $("#add-products-bulk-form").serialize();
var url="products/addproducts";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
dataType: 'json',
data:dataString,
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseJSON.error);
},
success: function (data, textStatus, jqXHR) {
alert(jqXHR.responseJSON.success);
}
});
});
});
</script>
I realized that I make ajax call with the same controller function, I divided the addproducts function into two functions as follow,and use ajax to call ajax_add_products function. it works now.
public function addproducts()
{
$data['title'] = "Add Products";
$this->load->view('templates/header', $data);
$this->load->view('products/addproducts');
$this->load->view('templates/footer');
}
public function ajax_add_products(){
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
if ($this->form_validation->run() === FALSE)
{
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}

how can i check if i got the value from my ajax to my controller

This is the event that will trigger the login
$('#btnLogin').click(function(){
//var data = $('#loginForm').serialize();
var email = $('#loginEmail').val();
var password = $('#loginPass').val();
var result = '';
if( email.trim() =='' ){
//username.addClass('alert-danger');
alert('email is required');
}else{
//username.removeClass('alert-danger');
result +='1';
}
if( password.trim()==''){
alert('password is required');
}else if(password.length < 8){
alert('password length must be atleast 8 characters');
}else{
//password.removeClass('alert-danger');
result +='2';
}
/*var postData = {
'email' : email,
'password' : password
};*/
if (result=='12') {
$.ajax({
type: "POST",
url: '<?php echo site_url('login/identifying_usertype'); ?>',
data: { email : email, password : password },
dataType: 'json',
success: function(response){
//console.log(response);
//alert(email);
$('#myModal').modal('hide');
},
error: function (XHR, status, error){
console.log('error', error);
}
});
}
});
This is my controller:
public function identifying_usertype()
{
if( $email = $this->input->post('email') )
{
echo json_encode( array('email' => $email) );
}
else
{
echo json_encode( array('error' => 'No email address') );
}
}
Now im getting {"error":"No email address"} on my console there's no error. Is there something I'm missing? on my ajax i added dataType: 'json', i changed the url from base_url to site url
Since you have success: function(response){, the return value of the Ajax is on the variable response and not on email. So doing this will fix your issue:
success: function(response){
email = response;
alert(email);
//$('#myModal').modal('hide');
},
1) The best way to create a link to one of your own controller/methods in CodeIgniter is to use site_url(), not base_url(). With site_url, your url becomes:
url: '<?php echo site_url('login/identifying_usertype'); ?>',
2) jQuery's $.ajax needs you to declare a dataType. Although if you leave it out jQuery will attempt to guess what it is, I've found it's wrong many times. Most people will use 'json':
dataType: 'json',
3) In your controller, if you are declaring that you want a json dataType, then it's really easy to send that back as the response:
echo json_encode( array('email' => $email) );
4) In your ajax success function, you can then do like this:
success: function( response ){
if( response.email ){
console.log(response.email);
}else{
console.log('email not verified');
}
}
5) Lastly, you are not showing code that would create an event to execute your ajax. If you need help with that, let me know and I'll show you.
6) All of the network traffic is available for you to view in your browser's console. Check it, as it is very helpful when creating these ajax requests.
Regarding your comment, how about this in the controller:
public function identifying_usertype()
{
if( $email = $this->input->post('email') )
{
echo json_encode( array('email' => $email) );
}
else
{
echo json_encode( array('error' => 'No email address') );
}
}

user name and password login through ajax.. unable to login

Controller code below as show unable to login.
none of the error getting what is the problem i cannot understand how to call through ajax
public function loginn()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
//$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->login($email, $password)) {
$this->welcome();
}
else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
$this->index();
}
}
Below code as shown View page send the post values through ajax.script as below.how to pass the post values to controller using ajax.
<script type="text/javascript">
$(document).ready(function(){
$("#fpassf").click(function(){
//e.preventDefault();
var email = $("#email").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>"+"Index.php/Login_cntrl/loginn",
data: {email:email,password:password},
success:function(data)
{
alert('Successfully login');
},
error:function()
{
alert('fail');
}
});
});
});
the image shown in below
enter image description here
on click on signin image shown in below
enter image description here
It seems that you are using Codeigniter Framework. And Hence I have a doubt with your Ajax URL Path.
You have given
url: "<?php echo base_url() ?>"+"Index.php/Login_cntrl/loginn",
But In codeigniter it should be like
url: "<?php echo base_url() ?>"+"/Login_cntrl/loginn",
OR
url: "<?php echo base_url('Login_cntrl/loginn') ?>",
It can also possible that you are calling this ajax from a script file. Which is not a php file. so the base_url() function will not work there. In that case you have to save base_url into a input variable in a hidden format. and then should be fetch in your ajax code.
<input type="hidden" name="myurl" value="<?php echo base_url();">
and then ajax one
var myurl = $("#myurl").val();
You have to separate your basic login action and ajax login action, because both send different response.
PHP Controller:
public function ajax_login()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->login($email, $password)) {
return $this
->output
->set_status_header(200)
// here you tell to the ajax that the login is successful
->set_output(json_decode(array('status' => 'success', 'message' => 'PUT_YOUR_SUCCESS_MESSAGE_HERE')))
;
} else {
return $this
->output
->set_status_header(200)
// here you tell to the ajax that the login is failed
->set_output(json_decode(array('status' => 'error', 'message' => 'PUT_YOUR_ERROR_MESSAGE_HERE')))
;
}
}
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#fpassf").click(function(){
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "<?php echo base_url('Login_cntrl/ajax_login') ?>",
data: {email:email, password:password},
success: function(data) {
data = JSON.parse(data);
// success in ajax does not mean successfully login, so check again
if (data.status == 'success') {
alert(data.message]); // login success message defined in action
} else {
alert(data.message); // login failed message defined in action
}
},
error: function() {
// error in ajax means HTTP error, not login error
alert('Request failed!');
}
});
});
});
</script>

PHP echo statement not working

I have following form processing php script.
<?php
$G['hotel_email']="xxxx#xxxx.com";
$G['hotel_name']="xxx xxx";
$G['language']="en";
$T['lbl_form_sent_successfully']="H";
# Recipients: comma separated
$G['form_contact_mail_recipients'] = $G['hotel_email'];
$G['form_contact_mail_subject'] = $G['hotel_name'] . ' - Contact Weddings [' . $G['language'] . ']';
# CHECK IF FORM SENT. AJAX. RESPONSE IN JAVASCRIPT TO INTERACT IN THE FORM.
if (!empty($_POST)) {
$js = '';
# ALTERNATIVE CAPTCHA, IT MUST NOT BE FILLED
if (!empty($_POST['title'])) { exit; }
# FORM MAIL TO SENT
unset($_POST['title']);
unset($_POST['submit']);
$message = date("l, F j, Y, g:i a")." [GMT] \n\nFORM DETAILS\n\n\n";
foreach ($_POST as $field => $value) {
$message .= ucfirst(str_replace('_',' ',$field)).': '.$value."\n\n";
}
$message .= "\n\n\n";
mail($G['form_contact_mail_recipients'], $G['form_contact_mail_subject'], $message, "From: ".$_POST['email']."\r\n");
echo "success";
}
?>
The form is being submitted using following JavaScript
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("#ba-form-contact form").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
First_Name: "required",
Surname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
}
},
submitHandler: function() {
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
return false;
}
});
});
</script>
The last echo statement does't work and I don't get any error msg.I do get email with all the info alright.I think nothing work after the mail function, I tried like var_dump, but nothing. What could be the error here?
As per your ajax request, you are not using success method here in ajax request, you need to add success method as:
jQuery.ajax({
url: YourURL,
type: "POST",
data: jQuery("#ba-form-contact form").serialize(),
dataType: "html",
success: function(response) {
alert(response); //this will return the response
},
beforeSend: function()
{
// loading if you need before ajax success
}
});
return false;
Here success: function(response) { will return the success message.
You do not know that it is the echo that does not work.
What you do know is that the script executes, and the jQuery function does not issue output. And that's where half the problem is.
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
The above does not do anything with the output, so logically nothing happens.
Try this:
jQuery.post({
'<?=$_SERVER['REQUEST_URI']?>',
jQuery("#ba-form-contact form").serialize()
}).done(function(retval) {
// Debug (better use console.log actually)
alert(JSON.stringify(retval));
// Do what you want with retval.message (check retval.status also)
alert(retval.message);
});
and in the PHP, which must output nothing else, end with:
header('Content-Type: application/json');
die(json_encode(array(
'status' => 'success',
'message' => 'The mail was sent',
)));
(I have changed from HTML to JSON output since this allows to send more structured data, with negligible additional complexity).

Hide form after submit with ajax

I've created a form using a bit of jquery, ajax and php.
The ajax, validation and php processing works well.
I came up with the following code to hide my form after submitting, but I don't know if this is the good way to do that. I would like your advise.
Below the js script with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
$("#formstatus").hide().html(response).slideToggle(600);
}
});
});
});
</script>
The above code will call the php to validate and populates the div#formstatus to notify the user if the form is sent or not.
Within my process.php, I will hide the form if there are no errors found using echo js script.
// If no errors found echo succes message
if (!($formerrors)) :
//Hide the form
echo '<script type="text/javascript">
$(document).ready(function(){
$("#contact_form").hide();
});
</script>';
// display success message
echo '<div>
Your message has been sent. <br />
Thank you for contacting us!
</div>';
Etc....
To sum up:
Should I use this method to hide my form? (Because it does work)
Note. I'm new to jquery and ajax :)
I think it would be better to return a JSON object which contains the information relevant to the request.
For example:
if (!($formerrors)){
echo json_encode(array(
'success'=> true,
'message'=> 'Your message has been sent. <br> Thank you for contacting us!'
));
}
else{
echo json_encode(array(
'success'=> false,
'message'=> 'Error processing form',
'errors'=> array(
'phone'> 'A phone number is required'
)
));
}
This will be easy to work with on the client side (jQuery will automatically parse the json)
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
if(response.success){
$("#formstatus").hide().text(response.message).slideToggle(600);
}
else{
jQuery.each(response.errors,function(){ ... });
}
}
});
});
});
I think you'll find you have more manageable code if you separate display concerns from functional concerns. For php I agree with Walkerneo.
Javascript AJAX Success Handler
success: function(response) {
var response = $.parseJSON(response);
if(response.status === 'true') {
$("#formstatus").hide().html(response.message).slideToggle(600);
$("#contact_form").hide();
} else {
$("#formstatus").hide().html(response.message).slideToggle(600);
}
}
PHP
if(!$formerrors) {
exit(json_encode(array('status' => 'true', 'message' => 'Your message has been sent. \n Thank you for contacting us!')));
} else {
$message = '<p class="error">' . implode('</p><p>', $formerrors) . '</p>';
exit(json_encode(array('status' => 'false', 'message' => $message)));
}
I recommend avoiding this method. You should instead return information about the status and message to display to the user. For example, here's how you can do it without reloading the page.
demo (non-blank data will be accepted)
We prevent the default event, so that the page doesn't reload. Because of the below HTML changes, we also can make or code more general.
$('form').submit(function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
cache: false,
type: 'POST',
url: 'URLHERE',
data: $(this).serialize(),
dataType: 'jsonp',
success: function(response) {
We display the error or success message here. Depending on the status field, we make the text green or red, and decide whether to hide the form or not.
$("#formstatus").hide().text(response.msg).show(600);
if (response.status === "success") {
$this.hide();
$("#formstatus").css({color: "green"});
}
else {
$("#formstatus").css({color: "red"});
}
}
});
return false;
});
Our PHP simply returns a JSON object.
function callback($data){
$json = json_encode($data);
return $json;
}
if ($valid === true) {
echo callback(
array(
"msg" => "Your message has been sent.\nThank you for contacting us!",
"status" => "success"
)
);
}
else {
echo callback(
array(
"msg" => "Please fill in all fields.",
"status" => "error"
)
);
}
The HTML is also changed to use a submit button, which allows us to target the form instead of the button. The code may now be transported more easily.
<div id="formstatus"></div>
<form>
<input placeholder="First Name" name="name">
<input placeholder="Email" name="email">
<input placeholder="Comment" name="comment">
<input type="submit">
</form>

Categories