How To insert data in mysql database using ajax in codeigniter? - php

I am trying to validate my form and insert the data in mysql database using ajax.Neither on submit validation is happening nor data is being inserted.I am making this in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
View :
<script type="text/javascript">
function validate_name(first_name){
if(first_name.trim() == '' || first_name.length == 0){
$('.first_name').show();
$('.first_name').text('Please enter your name');
return false;
} else {
$('.first_name').hide();
return true;
}
}
function validate_email(email_id){
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
if(email_id.trim() == '' || email_id.length == 0){
$('.email-id').show();
$('.email-id').text('Please enter email address');
return false;
}else if(!pattern.test(email_id)) {
$('.email-id').show();
$('.email-id').text('Please enter valid email address');
return false;
} else {
$('.email-id').hide();
return true;
}
}
function validate_inquiry_form(first_name,email_id){
var username_validate = validate_name(first_name);
var email_validate = validate_email(email_id);
if(username_validate == true && email_validate == true){
return true;
} else {
return false;
}
}
$('#submit_enquiry').click(function(){
var first_name = $("input[name=first_name]").val();
var last_name = $("input[name=last_name]").val();
var dob = $("input[name=dob]").val();
var gender = $("input[name=gender] :radio:checked").val();
var email_id = $("input[name=email_id]").val();
var password = $("input[name=password]").val();
var address = $("input[name=address]").val();
var phone = $("input[name=phone]").val();
var zipcode = $("input[name=zipcode]").val();
var validate_form = validate_inquiry_form(first_name,email_id);
if(validate_form == true){
$.ajax({
url:'<?php echo base_url(); ?>member/register',
type:'POST',
data:{
first_name : first_name ,last_name : last_name ,dob : dob ,male : male ,female : female , email_id : email_id ,password : password ,phone : phone , address : address , zipcode : zipcode
},
success: function(data) {
console.log(data);
}
});
} else {
return false;
}
return false;
});
</script>
<form id="registration-form">
<div class="register">
<div class="row">
<div class="col1">
<label for="first_name">First Name<span>*</span></label> <br/>
<input type="text" name="first_name"/>
<li class="first_name error"></li>
</div>
<div class="col2">
Last Name<br/>
<input type="text" name="last_name"/>
</div>
</div>
<div class="row">
<div class="col1">
Date Of Birth <br/>
<input type="text" name="dob"/>
</div>
<div class="col2">
Gender
<br/>
<input type="radio" name="gender" value="Male" /> Male
<input type="radio" name="gender" value="Female" /> Female
</div>
</div>
<div class="row">
<div class="col1">
Email<br/>
<input type="text" name="email_id"/>
<li class="email-id error"></li>
</div>
<div class="col2">
Password<br/>
<input type="password" name="password"/>
</div>
</div>
<div class="row">
<div class="col">
Address<br/>
<textarea name="address" rows="2" ></textarea>
</div>
</div>
<div class="row">
<div class="col1">
Zipcode<br/>
<input type="text" name="zipcode"/>
</div>
<div class="col2">
Phone<br/>
<input type="text" name="phone"/>
</div>
</div>
<div class="row">
<div class="col3">
<input class="" type="button" id="submit_enquiry" name="submit_enquiry" value="Submit Enquiry" />
</div>
</div>
</div>
</form>
Controller:
public function register_user()
{
$register_user = $this->member_model->add_user();
if($register_user)
{
return true;
}
else
{
return false;
}
}
Model :
public function add_user()
{
$add_user = array(
'mem_name'=> $this->input->post('first_name'),
'mem_lastname'=> $this->input->post('last_name'),
'mem_dob'=> $this->input->post('dob'),
'mem_gender'=> $this->input->post('gender'),
'mem_email'=> $this->input->post('email_id'),
'mem_address'=> $this->input->post('address'),
'mem_zipcode'=> $this->input->post('zipcode'),
'mem_phone'=> $this->input->post('phone'),
'mem_password'=> $this->input->post('password'),
);
$insert = $this->db->insert('membership', $add_user);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Please help me ....

change in this in your ajax add apostrophe (')
data:{
'first_name' : first_name ,'last_name' : last_name ,'dob' : dob , etc...
},
add this in your controler member
function register(){
$add_user = array(
'mem_name'=> $this->input->post('first_name'),
'mem_lastname'=> $this->input->post('last_name'),
'mem_dob'=> $this->input->post('dob'),
'mem_gender'=> $this->input->post('gender'),
'mem_email'=> $this->input->post('email_id'),
'mem_address'=> $this->input->post('address'),
'mem_zipcode'=> $this->input->post('zipcode'),
'mem_phone'=> $this->input->post('phone'),
'mem_password'=> $this->input->post('password'),
);
$this->member_model->add_user($add_user);
}
in your member_model
function add_user($add_user){
$insert = $this->db->insert('membership', $add_user);
}

You can use jquery validate and use ajay on submit handler. Please try following code:
$(function () {
$("#FormId").validate({
errorElement: 'span', errorClass: 'help-block',
rules: {
Tag: {
required: true
},
Table: {
required: true
},
Field: {
required: true
},
},
messages: {
Tag: {
required: "Tag is required."
},
Table: {
required: "Table is required."
},
Field: {
required: "Field is required."
},
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').children('span.help-block').remove();
},
errorPlacement: function (error, element) {
error.appendTo(element.closest('.form-group'));
},
submitHandler: function (form) {
$("#saveButton").button('loading');
$.post('', $("#FormId").serialize(), function (data) {
//Write your code here
});
}
});
});```

Related

how to fix csrf in one page php ajax codeigniter problem

I'm using codeigniter 3 and I've got issue here, how to fix my code if i use CSRF. because I want only have one page action to view in codeigniter.
Here's my controller code :
public function index()
{
# code untuk menampilkan Database Rotator
$this->data['partial_head'] = '
<!-- DataTables -->
<link rel="stylesheet" href="'.base_url('assets').'/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="'.base_url('assets').'/plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
<link rel="stylesheet" href="'.base_url('assets').'/plugins/datatables-buttons/css/buttons.bootstrap4.min.css">';
$this->data['partial_body'] = '
<!-- DataTables & Plugins -->
<script src="'.base_url('assets').'/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="'.base_url('assets').'/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="'.base_url('assets').'/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="'.base_url('assets').'/plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<!-- jquery-validation -->
<script src="'.base_url('assets').'/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="'.base_url('assets').'/plugins/jquery-validation/additional-methods.min.js"></script>
<!-- Custom JS -->
<script src="'.base_url('assets').'/dist/js/customJs/rotator-admin.js"></script>
';
$this->data['content'] = 'rotator/index';
$this->template->_render_page('layout/main',$this->data);
}
public function get_dataTable()
{
# code untuk menampilkan tabel ajax
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$query = $this->model->getAllData('rotator');
$data = [];
$no = 1;
foreach($query->result() as $row) {
$data[] = array(
$no++,
'+'.htmlentities($row->nomor_hp, ENT_QUOTES, "UTF-8"),
htmlentities($row->pesan, ENT_QUOTES, "UTF-8"),
htmlentities($row->jml_perulangan, ENT_QUOTES, "UTF-8").' kali',
($row->status_aktif==1)?
'<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input btn-aktif" name="aktif" id="'.encryptor('encrypt', $row->id_rotator).'" checked>
<label class="custom-control-label label-aktif" for="'.encryptor('encrypt', $row->id_rotator).'">Aktif</label>
</div>':'<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input btn-aktif" name="aktif" id="'.encryptor('encrypt', $row->id_rotator).'">
<label class="custom-control-label label-aktif" for="'.encryptor('encrypt', $row->id_rotator).'">Non Aktif</label>
</div>',
'<i class="fas fa-edit"></i>
<i class="fas fa-trash"></i>'
);
}
$result = array(
'draw' => $draw,
'recordsTotal' => $query->num_rows(),
'recordsFiltered' => $query->num_rows(),
'data' => $data
);
echo json_encode($result);
exit();
}
public function getByDataId($id = null)
{
# code untuk menampilkan Data Himpunan jika tombol edit di klik
$where = ['id_rotator' => encryptor('decrypt', $id)];
$hasil = $this->model->whereData($where, 'rotator')->row();
$data = [
'handphone' => $hasil->nomor_hp,
'pesan' => $hasil->pesan,
'isAktif' => $hasil->status_aktif,
'diulang' => $hasil->jml_perulangan,
'id' => $id
];
echo json_encode($data);
}
public function tambah_data()
{
# code untuk menambahkan data baru
$this->form_validation->set_rules('handphone', 'Nomor Handphone', 'trim|required|is_numeric|is_unique[rotator.nomor_hp]');
$this->form_validation->set_rules('pesan', 'Pesan', 'trim|required');
$this->form_validation->set_rules('diulang', 'Jumlah Perulangan', 'trim|required|is_numeric');
$this->form_validation->set_rules('isAktif', 'is Aktif', 'trim|numeric');
if ($this->form_validation->run() == FALSE) {
echo json_encode([
'alert_error' => validation_errors()
]);
} else {
$nomorHp = $this->input->post('handphone', true);
$pesan = $this->input->post('pesan', true);
$perulangan = $this->input->post('diulang', true);
$isAktif = !empty($this->input->post('isAktif', true)) ? 1 : 0;
$data = [
'nomor_hp' => $nomorHp,
'pesan' => $pesan,
'status_aktif' => $isAktif,
'jml_perulangan' => $perulangan,
];
if ($this->model->insertData($data, 'rotator')) {
echo json_encode([
'alert_success' => 'Data berhasil ditambahkan!',
'status' => TRUE
]);
} else {
echo json_encode([
'alert_success' => 'Data gagal ditambahkan!',
'status' => FALSE
]);
}
}
}
public function edit_data()
{
# code untuk mengubah Data
$this->form_validation->set_rules('handphone', 'Nomor Handphone', 'trim|required|is_numeric');
$this->form_validation->set_rules('pesan', 'Pesan', 'trim|required');
$this->form_validation->set_rules('diulang', 'Jumlah Perulangan', 'trim|required|is_numeric');
$this->form_validation->set_rules('isAktif', 'is Aktif', 'trim|numeric');
if ($this->form_validation->run() == FALSE) {
echo json_encode([
'alert_error' => validation_errors()
]);
} else {
$nomorHp = $this->input->post('handphone', true);
$pesan = $this->input->post('pesan', true);
$perulangan = $this->input->post('diulang', true);
$isAktif = !empty($this->input->post('isAktif', true)) ? 1 : 0;
$data = [
'nomor_hp' => $nomorHp,
'pesan' => $pesan,
'status_aktif' => $isAktif,
'jml_perulangan' => $perulangan,
];
$id = $this->input->post('idRotator', true);
if($this->model->updateData(['id_rotator' => encryptor('decrypt', $id) ], $data, 'rotator')){
echo json_encode([
'alert_success' => 'Data berhasil diubah!',
'status' => TRUE
]);
} else {
echo json_encode([
'alert_error' => 'Data Gagal diubah!',
'status' => FALSE
]);
}
}
}
public function hapus_data($id = null)
{
# code untuk menghapus Data Himpunan
$where = ['id_rotator' => encryptor('decrypt', $id)];
$this->model->deleteData($where, 'rotator');
echo json_encode([
'status' => TRUE
]);
}
public function aktif_handphone($id = null)
{
# code untuk mengaktifkan handphone
$this->form_validation->set_rules('aktif', 'Aktif Handphone', 'trim|is_numeric');
if ($this->form_validation->run() == FALSE) {
echo json_encode([
'alert_error' => validation_errors()
]);
} else {
$data = [
'status_aktif' => $this->input->post('aktif',true)
];
if($this->model->updateData(['id_rotator' => encryptor('decrypt', $id)], $data, 'rotator')){
echo json_encode([
'alert_success' => 'Data berhasil diubah!',
'status' => TRUE
]);
}
}
}
Here's my table in view code:
<table class="table table-bordered table-sm table-striped table-hover" id="dataTable"
width="100%" cellspacing="0">
<thead>
<tr>
<th>No.</th>
<th>Nomor HP</th>
<th>Pesan</th>
<th>Jumlah Diulang</th>
<th>Status</th>
<th width="12%">#</th>
</tr>
</thead>
</table>
Here's my modal in view code:
<!-- modal -->
<div class="modal fade" id="exampleModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
<button type="button" class="close btn-tutup" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form class="form-horizontal" action="" id="myForm" method="post" accept-charset="utf-8">
<div class="modal-body">
<div class="form-group row">
<label for="handphone" class="col-sm-4 col-form-label">Nomor Hp</label>
<div class="col-sm-8 inputan">
<input id="handphone" name="handphone" type="text" pattern="\d*" maxlength="13"
onkeypress="return isNumber(event)" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="pesan" class="col-sm-4 col-form-label">Pesan Untuk Admin</label>
<div class="col-sm-8 inputan">
<textarea name="pesan" id="pesan" cols="30" rows="3" class="form-control"
style="resize: none;" maxlength="256"></textarea>
</div>
</div>
<div class="form-group row">
<label for="diulang" class="col-sm-4 col-form-label">Diulang Sebanyak</label>
<div class="col-sm-4 inputan">
<input id="diulang" name="diulang" type="text" pattern="\d*" maxlength="2" minlength="1"
min="1" max="10" onkeypress="return isNumber(event)" class="form-control">
</div>
<span class="col-sm-4 col-form-label">(x) kali</span>
</div>
<div class="form-group row">
<div class="col-4"></div>
<div class="col-8 inputan">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="isAktif" id="checkbox_0" type="checkbox" class="custom-control-input"
value="1" required="required">
<label for="checkbox_0" class="custom-control-label">is Aktif</label>
</div>
</div>
</div>
<input id="idRotator" name="idRotator" type="hidden">
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default btn-tutup" data-dismiss="modal">Tutup</button>
<button type="submit" class="btn btn-primary">Simpan</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
and here's my script code:
//tampilkan data di datatables
$(document).ready(function() {
resetForm()
table = $('#dataTable').DataTable({
"ajax": {
url: 'rotator/get-dataTable',
type: 'POST'
},
})
})
$(function () {
// validasi form sebelum di kirim
$('#myForm').validate({
rules: {
handphone: {
required: true,
},
pesan: {
required: true,
},
diulang: {
required: true,
min: 1,
max: 10
},
isAktif: {
required: false
}
},
messages: {
handphone: {
required: "Pastikan masukan nomor telp dengan kode negara, misal 62xxxxxxxxxxx"
},
pesan: {
required: "Inputan pesan tidak boleh kosong!"
},
diulang: {
required: "Input angka 1 sampai 10",
min: "Input angka minimal 1",
max: "Input angka maksimal 10"
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.inputan').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
},
// jika form di submit
submitHandler: function() {
var data = $('#myForm').serialize()
$('.btn-simpan').text('simpan...') //ganti text button
$('.btn-simpan').attr('disabled', true) //set button disable
var url
if (save_method == 'add') {
url = "rotator/tambah-data"
} else {
url = "rotator/edit-data"
}
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'JSON',
success: function(data) {
if (data.status) {
toastr.success(data.alert_success)
$('#exampleModal').modal('hide')
reload_table()
resetForm()
} else {
var messages = data.alert_error.split("\n")
for(var i=0; i<messages.length - 1; i++)
toastr.error(messages[i])
}
$('.btn-simpan').text('Simpan') //ganti text button
$('.btn-simpan').attr('disabled', false) //set button enable
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error('Error ' + save_method + ' data')
$('.btn-simpan').text('Simpan') //ganti text button
$('.btn-simpan').attr('disabled', false) //set button enable
}
})
}
})
})
//fungsi jika tombol tutup di klik
$('.btn-tutup').on("click", function(e) {
e.preventDefault()
resetForm()
})
//fungsi jika tombol tambah di klik
$('.btn-tambah').on('click',function (e) {
e.preventDefault()
$('.modal-title').text('Tambah Data')
resetForm()
save_method = 'add'
})
//fungsi jika tombol edit di klik
$('#dataTable').on('click', '.btn-edit', function() {
$('.modal-title').text('Edit Data')
var url = "rotator/getByDataId/"
var id = this.id
save_method = 'update'
resetForm()
$.ajax({
url: url + id,
type: 'POST',
dataType: 'JSON',
success: function(data) {
$.each(data, function() {
$('[name="handphone"]').val(data.handphone)
$('[name="pesan"]').text(data.pesan)
$('[name="diulang"]').val(data.diulang)
if(data.isAktif>0){
$('input[name=isAktif]').attr('checked', 'checked')
} else {
$('input[name=isAktif]').removeAttr('checked')
}
$('[name="idRotator"]').val(data.id)
$('[name="idRotator"]').attr('readonly', true)
//console.log(data)
})
},
error: function(jqXHR, textStatus, errorThrown) {
//toastr.error('Gagal baca data dari ajax')
return false
}
})
})
//fungsi jika tombol hapus di klik
$('#dataTable').on('click', '.btn-hapus', function() {
var url = "rotator/hapus-data/"
var id = this.id
Swal.fire({
title: 'Yakin akan menghapus data?',
icon: 'question',
showDenyButton: true,
showCancelButton: false,
confirmButtonText: `Ya, Hapus`,
denyButtonText: `Tidak`,
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: url + id,
type: 'POST',
dataType: 'JSON',
success: function(data) {
Swal.fire('Dihapus!', 'data berhasil dihapus.', 'success')
reload_table()
resetForm()
},
error: function(xhr, ajaxOptions, thrownError) {
Swal.fire('Hapus Gagal!', 'Coba lagi', 'error')
}
})
} else if (result.isDenied) {
Swal.fire('Aman..!', 'Data tidak jadi dihapus.', 'info')
}
})
})
//fungsi untuk aktivasi handphone
$('#dataTable').on('click', '.btn-aktif', function() {
var url = "rotator/aktif-handphone/"
var id = this.id
var aktif = $('input#'+ id +':checked').val() ? '1' : '0'
$.ajax({
url: url + id,
type: 'POST',
dataType: 'JSON',
data : {aktif:aktif},
success: function(data) {
toastr.success(data.alert_success)
reload_table()
},
error: function(xhr, ajaxOptions, thrownError) {
toastr.error(data.alert_error)
return false
}
})
})
//fungsi untuk reload dataTabel
function reload_table() {
table.ajax.reload(null, false)
}
//fungsi untuk cek hanya angka yang diinput
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false
}
return true
}
//fungsi untuk reset form
function resetForm() {
$('#myForm').find('input:checkbox').removeAttr('checked') //kosongkan chekbox
$('#myForm').find('input:text').val('') //kosongkan form input
$('#myForm').find('textarea').text('') //kosongkan text area
}
if I try to setting my $config['csrf_protection'] = TRUE; will be error and showing notification, Where location we must locate <?= $this->security->get_csrf_token_name(); ?> and <?php echo $this->security->get_csrf_hash(); ?> to fix all ajax using csrf in one page..?
i come across this issue and if are you use multi form see this answer
https://stackoverflow.com/a/69407364/6559546

Validation in AJAX Form Codeigniter

I've made a form in Ci which submits the data to the Db. I've been trying to implement validation in the form, For eg Name : more than 3+ Letters, email '#' Etc.
I never could seem to make it work, tried using Jquery validation with different sources , the form basically submits without Validation, Any pointers to where i'm going wrong?
The code below is just a snippet without any validation codes attached to it.
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "<?php echo $row_company->company_name; ?> "</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#click_form').click(function () {
var url = "<?php echo site_url('enquiry/ajax_post_form') ?>";
var data = $("#reg_form").serialize();
$.post(url, data, function (data) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}, "json");
});
});
</script>
</div>
</div>
</div>
</div>
Controller
public function ajax_post_form() {
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags');
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['message'] = 'Data Inserted Successfully';
echo json_encode($user_data);
}
Model
function form_insert($user_data){
$this->db->insert('pp_enquiry', $user_data);
}
**Validation **
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var email = document.getElementById("email1").value;
var mobile = document.getElementById("mobile").value;
//Check input Fields Should not be blanks.
if (name == '' || email == '' || mobile == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var email1 = document.getElementById("email");
var mobile = document.getElementById("mobile");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Must be 3+ letters' || email1.innerHTML == 'Invalid email' || mobile.innerHTML == 'Invalid website') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
Please check here is the working example of your above code. I think you missed something in your code.
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = 'https://www.example.com';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
console.log(data);
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "Company Name"</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
</div>
</div>
</div>
</div>
You need to run the validation process as explained in the manual: https://www.codeigniter.com/user_guide/libraries/form_validation.html#the-controller
if ($this->form_validation->run() == FALSE)
You can find below mentioned solution.
PHP Validation
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags|valid_email|min_length[3]');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags|min_length[10]|max_length[12]');
if ($this->form_validation->run() == FALSE) {
$data['status'] = false;
$data['error'] = validation_errors();
} else {
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['status'] = true;
$data['message'] = 'Data Inserted Successfully';
}
echo json_encode($data);
jQuery Validation
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = '<?php echo site_url('enquiry/ajax_post_form') ?>';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
// Code if required before Send
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
Let me know if it not works.

Insert in database ONLY after checking username & Email availability

I am working on a sign up form, user shouldn't be allowed to register if username/email is taken.
so before inserting user info and accepting the sign up, I am checking 2 major conditions
1. If username is taken
2. If email is registered before
and then only the registration can go through.
I am using Ajax to send the data to php, but the data won't be inserted in the db for some reason (NO ERRORS SHOW!)
Where am I going wrong?
HTML code:
<form method="post" role="form" id="register-form" autocomplete="off" action="includes/check_signup.php">
<div class="form-header">
<h3 class="form-title"><i class="fa fa-user"></i><span class="glyphicon glyphicon-user"></span> Sign Up</h3>
<div class="pull-right">
<h3 class="form-title"><span class="glyphicon glyphicon-pencil"></span></h3>
</div>
</div>
<div class="form-body">
<!-- json response will be here -->
<div id="errorDiv"></div>
<!-- json response will be here -->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
<input name="name" type="text" id="name" class="form-control" placeholder="Name" maxlength="40" autofocus="true" onBlur="checkname();">
</div>
<span class="help-block" id="error error-username"></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></div>
<input name="email" id="email" type="text" class="form-control" placeholder="Email" maxlength="50" onBlur="checkemail();">
</div>
<span class="help-block" id="error error-email"></span>
</div>
<div class="row">
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
</div>
<span class="help-block" id="error"></span>
</div>
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input name="cpassword" type="password" class="form-control" placeholder="Retype Password">
</div>
<span class="help-block" id="error"></span>
</div>
</div>
</div>
<div class="form-footer">
<button type="submit" class="btn btn-info" id="btn-signup" name="signup">
<span class="glyphicon glyphicon-log-in"></span> Sign Me Up
</button>
</div>
<p id='result'></p>
</form>
Ajax code:
//check username availability
function checkname() {
jQuery.ajax({
url: "includes/check_signup.php",
data:'username='+$("#name").val(),
type: "POST",
success:function(data){
$("#error").html(data);
},
error:function (){}
});
}
function checkemail()
{
jQuery.ajax({
url: "includes/check_signup.php",
data:'email='+$("#email").val(),
type: "POST",
success:function(data){
$("#error").html(data);
},
error:function (){}
});
}
$('document').ready(function()
{
// name validation
var nameregex = /^[0-9a-zA-Z]+$/;
$.validator.addMethod("validname", function( value, element ) {
return this.optional( element ) || nameregex.test( value );
});
// valid email pattern
var eregex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$.validator.addMethod("validemail", function( value, element ) {
return this.optional( element ) || eregex.test( value );
});
$("#register-form").validate({
rules:
{
name: {
required: true,
validname: true,
minlength: 4
},
email : {
required : true,
validemail: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password: {
required: true,
minlength: 5,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
},
messages:
{
name: {
required: "Username is required",
validname: "Username can be a combination of Alphabets & Numbers",
minlength: "your username is too short"
},
email : {
required : "Email is required",
validemail : "Please enter valid email address",
remote : "Email already exists"
},
password:{
required: "Password is required",
minlength: "Password at least have 5 characters"
},
cpassword:{
required: "Retype your password",
equalTo: "Password did not match !"
}
},
errorPlacement : function(error, element) {
$(element).closest('.form-group').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').find('.help-block').html('');
},
submitHandler: submitForm
});
});
$('#register-form').submit(function(){
return false;
});
$('#btn-signup').click(function(){
$.post(
$('#register-form').attr('action'),
$('#register-form :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
PHP code:
<?php
function name (){
global $connection;
if(isset($_POST['username']))
{
$name=$_POST['username'];
$checkdata="SELECT * FROM users WHERE userName='$name' ";
$query=mysqli_query($connection, $checkdata);
if(mysqli_num_rows($query)>0)
{
echo "User Name is taken";
return true;
}
exit();
}
}
function email () {
global $connection;
if(isset($_POST['email']))
{
$emailId=$_POST['email'];
$checkdata=" SELECT * FROM users WHERE userEmail='$emailId' ";
$query=mysqli_query($connection, $checkdata);
if(mysqli_num_rows($query)>0)
{
echo "Email Already Exist";
return true;
}
exit();
}
}
function insert_db (){
global $connection;
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$pass = trim($_POST['cpassword']);
$full_name = strip_tags($name);
$user_email = strip_tags($email);
$user_pass = strip_tags($pass);
// sha256 password hashing
$hashed_password = hash('sha256', $user_pass);
$query = "INSERT INTO users(userName,userEmail,userPassword) VALUES('$name', '$email', '$hashed_password')";
$result = mysqli_query ($connection, $query);
if ($result) {
echo "You have been registered";
return true;
} else {
die ("error". mysqli_error ($connection));
}
}
if (name()) {
} elseif (email()) {
} else {
insert_db;
}
Maybe because you're closing php tag and the code after it's never going to be executed.
<?php include "config.php"; ?> function name (){
You're exiting the script when calling function name() when there is no result in db, just use a return false; instead of exit();
if(mysqli_num_rows($query)>0)
{
echo "User Name is taken";
return true;
}
return false;
Remove all the exit() from the script first of all, and replace it with return false.
if (name()) { #this will return false
} elseif (email()) { #after you removed exit() this should return false
} else {
insert_db(); #fix the call
}

AJAX Can't be Executed in CodeIgniter Form Submission

I'm new in AJAX programming and working on a project that should use AJAX.
I'm using PHP with CodeIgniter framework, and I want to create forms that when submitted, it will return a success message without reloading the page, that's why I chose ajax. But from the code that I have made, it works without reading the AJAX, it move to another page and of course, no success message to be displayed
So my main problem is my AJAX form submission can't be executed and I don't understand why.
Any help would be appreciated.
Here is my controller.php
public function index()
{
$this->form_validation->set_rules('advice', 'Advice', 'required');
$data["CatId"]=$this->viewbook_model->getCategory();
$this->ckeditor->basePath = base_url().'assets/ckeditor/';
$this->ckeditor->config['toolbar'] = array(
array( 'Source', '-', 'Bold', 'Italic', 'Underline', '-','Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo','-','NumberedList','BulletedList' )
);
$this->ckeditor->config['language'] = 'it';
$this->ckeditor->config['width'] = '730px';
$this->ckeditor->config['height'] = '300px';
//Add Ckfinder to Ckeditor
$this->ckfinder->SetupCKEditor($this->ckeditor,'../../assets/ckfinder/');
if($this->session->userdata('is_logged_in')){
$this->load->model('feedback_model');
$data['feedback'] = $this->feedback_model->get_subject();
$advice_list = $this->feedback_model->get_subject();
$x = 0;
foreach($advice_list AS $al)
{
$data['feedback'][$x] = array(
'CategoryAdviceId' => $al['CategoryAdviceId'],
'CategoryAdviceName' => $al['CategoryAdviceName']
);
$x++;
}
$data['booklist'] = $this->feedback_model->find($this->session->userdata('username'));
$book_list = $this->feedback_model->find('username');
$y = 0;
foreach($book_list AS $bl)
{
$data['booklist'][$y] = array(
'AssetTitle' => $bl['AssetTitle'],
'bi' => $bl['bi']
);
$y++;
}
$data['adviceid'] = $this->feedback_model->get_adviceId();
$adviceid_list = $this->feedback_model->get_adviceId();
$x = 0;
foreach($adviceid_list AS $adv)
{
$data['adviceid'][$x] = array(
'AdviceId' => $adv['AdviceId']
);
$x++;
}
$page_content["page_title"] = "Send Feedback";
$page_content["title"] = "Suggestion and Feedback";
$page_content["icon_title"] = "home";
$menu_params["current_navigable"] = "Feedback";
$menu_params["sub_current_navigable"] = "";
$page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
$page_content["content"] = $this->load->view("feedback", $data, true);
$page_content["navmenu"] = $this->load->view("nav_menu", $data, true);
$this->load->view("template/main_template", $page_content);
}else{
redirect('login/restricted');
}
}
//this is the function that sent data to model and return json to view for display success message
function insert_to_db()
{
$this->feedback_model->insert_into_db();
echo json_encode('true');
}
this is my form code in view.php
<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">
<div class="control-group">
<!--FEEDBACK TYPE-->
<label class="span2 control-label" >Feedback for</label>
<div class="controls with-tooltip">
<select class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($x = 0 ; $x < count($feedback) ; $x++)
{ ?>
<option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
<?php
} ?>
</select>
</div>
</div>
<!--SUBJECT-->
<div class="control-group">
<label for="limiter" class="control-label">Subject</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.." />
<p class="help-block"></p>
</div>
</div>
<div id="emptybox"></div>
<!--CHOOSE BOOK-->
<div id="showupbox" style="display: none;">
<div class="control-group">
<label class="control-label">Choose Book</label>
<div class="controls">
<select class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($y = 0 ; $y < count($booklist) ; $y++)
{ ?>
<option value="<?php echo $booklist[$y]['bi']?> - <?php echo $booklist[$y]['AssetTitle']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
<?php
} ?>
</select>
</div>
</div>
</div>
<!--ADVICE-->
<div class="control-group">
<label for="limiter" class="control-label" >Suggestion</label>
<div class="controls">
<?php echo $this->ckeditor->editor("Advice",""); ?>
</div>
</div>
<!--Type Advice ID-->
<div class="control-group hidden">
<label for="limiter" class="control-label" >Sugg</label>
<div class="controls">
<?php
for($x = 0 ; $x < count($adviceid) ; $x++)
{ ?>
<input type="text" class="span5" maxlength="50" id="TypeAdviceId" name="TypeAdviceId" value="<?php echo $adviceid[$x]['AdviceId']?>"/>
<?php
} ?>
<p class="help-block"></p>
</div>
</div>
<div class="control-group hidden">
<label for="limiter" class="control-label" >Sugg</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="NoBook" name="NoBook" value="-"/>
<p class="help-block"></p>
</div>
</div>
<!--div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<strong>Success!</strong> Thanks for your feedback!
</div-->
<div class="bton1">
<button class="btn btn-primary round" type="submit" id="btnSubmit">Submit</button>
<button class="btn btn-primary round" type="refresh">Reset</button>
</div>
</form>
this is my script and AJAX code:
$(document).ready(function() {
//this is for CKEDITOR validation
for(var name in CKEDITOR.instances) {
CKEDITOR.instances["Advice"].on("instanceReady", function() {
// Set keyup event
this.document.on("keyup", updateValue);
// Set paste event
this.document.on("paste", updateValue);
});
function updateValue() {
CKEDITOR.instances["Advice"].updateElement();
$('textarea').trigger('keyup');
}
}
//this is my form validation
$("#feedback_form").validate({
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:{
required: function(element){
return $("#CategoryAdviceSelect").val()==1;
}
}
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required",
},
errorElement: "span",
errorPlacement: function (error, element) {
if ($(element).attr('name') == 'Advice') {
$('#cke_Advice').after(error);
} else {
element.after(error);
}
},
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
//this is my ajax submission
$("#btnSubmit").click(function() {
var formURL = $(this).attr("action");
var methodtype = $(this).attr("method");
$.ajax({
url : formURL,
type: methodtype,
data : {
CategoryAdviceSelect:CategoryAdviceSelect,
Subject:Subject,
Advice:Advice,
BookSelect:BookSelect,
TypeAdviceId:TypeAdviceId,
NoBook:NoBook
},
ajaxOptions: {
dataType: 'json'
},
success : function(data){
setTimeout(function() {location.reload(true)}, 1700);
$('#success .success-content span').html('Thankyou for your <b>feedback</b>');
$('#success').fadeIn();
setTimeout(fade_out, 1200);
}
});
return false;
});
});
instead of form tag just use: (in codeigniter)
<?php $attr = array('id'=>'feedback_form', 'name'=>'feedback_form', 'class'='form-horizontal', 'novalidate'=>'novalidate');?>
<?php echo form_open('feedback/feedback/insert_to_db', $attr);?>
change in ajaxfunction (change button click event to form submit event)
$("#feedback_form").submit(function(e) {
e.preventDefault();
var formURL = $(this).attr("action");
var methodtype = $(this).attr("method");
$.ajax({
url : formURL,
type: methodtype,
data : {
CategoryAdviceSelect:CategoryAdviceSelect,
Subject:Subject,
Advice:Advice,
BookSelect:BookSelect,
TypeAdviceId:TypeAdviceId,
NoBook:NoBook
},
ajaxOptions: {
dataType: 'json'
},
success : function(data){
setTimeout(function() {location.reload(true)}, 1700);
$('#success .success-content span').html('Thankyou for your <b>feedback</b>');
$('#success').fadeIn();
setTimeout(fade_out, 1200);
}
});
return false;
});

Multi Stage Contact Form - PHP

http://webexpedition18.com/download/signup_form_WebExpedition18/
Hi Guys,
The above multi-stage contact form works great for my own project. It looks great and does the trick but i am stumped when trying to get the information submitted via email.
So i have a nice looking form but it wont send any information so is pretty useless to me. Even when i just upload the untouched demo files from the tutorial site, it still doesn't work.
Here's the html i have:
<div id="container">
<form action="contact.php" method="post">
<div id="first_step">
<div class="form">
<label for="full-name">Full Name:</label> <input id="username"
name="full-name" style="margin-bottom:10px;" type="text" value=
""> <label for="telephone">Telephone:</label> <input id=
"username" name="telephone" style="margin-bottom:10px;" type=
"text" value=""> <label for="email-address">Email
Address:</label> <input id="username" name="email-address"
style="margin-bottom:10px;" type="text" value="">
</div>
<div class="clear"></div><input class="submit" id="submit_first"
name="submit_first" type="submit" value="Next">
</div>
<div class="clear"></div>
<div id="second_step">
<div class="form">
<label for="company-name">Company Name (if you have
one):</label> <input id="username" name="company-name" style=
"margin-bottom:10px;" type="text" value=""> <label for=
"existing-website">Existing Website (if you have one):</label>
<input id="username" name="existing-website" style=
"margin-bottom:10px;" type="text" value=""> <label for=
"existing-domain">What domain would you like the new website to
be on?</label> <input id="username" name="existing-domain"
style="margin-bottom:10px;" type="text" value="">
</div>
<div class="clear"></div><input class="submit" id="submit_second"
name="submit_second" type="submit" value="Next">
</div>
<div class="clear"></div>
<div id="third_step">
<div class="form">
<label for="which-package">Which package would you
like?:</label>
<p><label><input id="RadioGroup1_0" name="RadioGroup1" type=
"radio" value="Standard"> Standard</label> <label><input id=
"RadioGroup1_1" name="RadioGroup1" type="radio" value=
"Business"> Business</label> <label><input id="RadioGroup1_2"
name="RadioGroup1" type="radio" value="Professional">
Professional</label></p><label for="which-template">Which
template would you like?:</label>
<p><label><input id="RadioGroup2_0" name="RadioGroup2" type=
"radio" value="1"> 1</label> <label><input id=
"RadioGroup2_1" name="RadioGroup2" type="radio" value=
"2"> 2</label> <label><input id="RadioGroup2_2"
name="RadioGroup2" type="radio" value="3">
3</label></p>
<div class="clear"></div>
</div>
<div class="clear"></div><input class="submit" id="submit_third"
name="submit_third" type="submit" value="Next">
</div>
<div class="clear"></div>
<div id="fourth_step">
<div class="form">
<h2>All done ...</h2>
<p style="margin-top:30px;">Press 'Submit' and we'll send you
everything you need to get you up and running.</p>
</div>
<div class="clear"></div><input class="send submit" id=
"submit_fourth" name="submit_fourth" type="submit" value="Submit">
</div>
</form>
</div>
</div>
The submit button just doesn't do anything. I have tried a number of different php form handler codes in my contact.php file but i still get nothing.
Any help is hugely appreciated guys. I'm getting really desperate now after 6 hours trying with this.
Thank you.
The JS file that comes with the demo is:
$(function(){
//original field values
var field_values = {
//id : value
'username' : 'username',
'password' : 'password',
'cpassword' : 'password',
'firstname' : 'first name',
'lastname' : 'last name',
'email' : 'email address'
};
//inputfocus
$('input#username').inputfocus({ value: field_values['username'] });
$('input#password').inputfocus({ value: field_values['password'] });
$('input#cpassword').inputfocus({ value: field_values['cpassword'] });
$('input#lastname').inputfocus({ value: field_values['lastname'] });
$('input#firstname').inputfocus({ value: field_values['firstname'] });
$('input#email').inputfocus({ value: field_values['email'] });
//reset progress bar
$('#progress').css('width','0');
$('#progress_text').html('0% Complete');
//first_step
$('form').submit(function(){ return false; });
$('#submit_first').click(function(){
//remove classes
$('#first_step input').removeClass('error').removeClass('valid');
//ckeck if inputs aren't empty
var fields = $('#first_step input[type=text], #first_step input[type=password]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
if( $('#password').val() != $('#cpassword').val() ) {
$('#first_step input[type=password]').each(function(){
$(this).removeClass('valid').addClass('error');
$(this).effect("shake", { times:3 }, 50);
});
return false;
} else {
//update progress bar
$('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
//slide steps
$('#first_step').slideUp();
$('#second_step').slideDown();
}
} else return false;
});
$('#submit_second').click(function(){
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#third_step').slideDown();
} else return false;
});
$('#submit_third').click(function(){
//update progress bar
$('#progress_text').html('100% Complete');
$('#progress').css('width','339px');
//prepare the fourth step
var fields = new Array(
$('#username').val(),
$('#password').val(),
$('#email').val(),
$('#firstname').val() + ' ' + $('#lastname').val(),
$('#age').val(),
$('#gender').val(),
$('#country').val()
);
var tr = $('#fourth_step tr');
tr.each(function(){
//alert( fields[$(this).index()] )
$(this).children('td:nth-child(2)').html(fields[$(this).index()]);
});
//slide steps
$('#third_step').slideUp();
$('#fourth_step').slideDown();
});
$('#submit_fourth').click(function(){
//send information to server
alert('Sent. Thank you!');
});
});
And the php is used within my contact.php file was:
<?php
$errors = '';
$myemail = 'yourname#website.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact form handler</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>
$('form').submit(function(){ return false; }); tells that submit should return false

Categories