I'm trying to do multi upload photos to the form in Codeigniter 3. When I want to upload photos, clicking upload sends me the entire form and adds only one photo. If anyone could give me tips on how to do this, I would be grateful. I could do it as two separate forms but then it doesn't work as I would like.
My form view
<form method='post' action='<?php echo base_url();?>ads/create' enctype='multipart/form-data'>
<div class="form-group row">
<label for="email" class="col-4 col-form-label text-uppercase text-right">Tytuł :</label>
<div class="col-8">
<input type="text" class="form-control" name="title" value="<?php echo set_value('title'); ?>">
</div>
</div>
<div class="form-group row">
<label for="message" class="col-4 col-form-label text-uppercase text-right">Opis ogłoszenia:</label>
<div class="col-8">
<textarea name="description" id="message" cols="70" rows="5"
class="form-control" ><?php echo set_value('description'); ?></textarea>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-4 col-form-label text-uppercase text-right">Osoba do kontaktu:</label>
<div class="col-8">
<input type="text" class="form-control" name="contact" value="<?php echo set_value('contact'); ?>">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-4 col-form-label text-uppercase text-right">Adres email:</label>
<div class="col-8">
<input type="text" class="form-control" name="email" <?php if ( logged_in() == true )
{ echo "value='".$user->email."' disabled"; } ?> >
</div>
</div>
<div class="form-group row">
<label for="phone" class="col-4 col-form-label text-uppercase text-right">Numer telefonu:</label>
<div class="col-8">
<input type="text" class="form-control" name="phone" value="<?php echo set_value('phone'); ?>">
</div>
</div>
<div class="form-group row">
<label for="message" class="col-4 col-form-label text-uppercase text-right">Zdjęcia:</label>
</div>
<hr>
<input type='file' name='files[]' multiple=""> <br/><br/>
<input id="submit" type='submit' value='Upload' name='upload' />
<strong><?php if(isset($totalFiles)) echo "Successfully uploaded ".count($totalFiles)." files"; ?></strong>
<div class="form-group row">
<div class="col-12 text-center">
<button class="btn btn-primary w-50 mt-3">Dodaj</button>
</div>
</div>
<?php echo form_close(); ?>
And my controller
public function create()
{
$user_id = $this->session->userdata( 'id' );
$where = array( 'id' => $user_id);
$user = $this->Site_model->get_single('users', $where);
$data['user'] = $user;
if ( !empty( $_POST ) )
{
if ( $this->form_validation->run( 'site_ads_create' ) == true )
{
if ( logged_in() == true )
{
$data = array(
'email' => $this->session->userdata( 'email' ),
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'category_id' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 1,
);
}
else
{
$data = array(
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'category_id' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'email' => $this->input->post( 'email' , true ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 0,
);
}
$count = count($_FILES['files']['name']);
for($i=0;$i<$count;$i++){
if(!empty($_FILES['files']['name'][$i])){
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
$config['upload_path'] = 'images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = '5000';
$config['file_name'] = $this->input->post( 'title' , true );
$this->load->library('upload',$config);
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$data['totalFiles'][] = $filename;
}
}
}
$this->Site_model->create( 'ads' , $data );
$ad_id = $this->Site_model->last_id();
if ($this->input->post('promo' , true ) == 'tak' )
{
$this->session->set_userdata('promo_id', $ad->id);
redirect( 'ads/promo' );
}
$this->session->set_flashdata( 'alert' , 'Ad has been added.' );
//refresh();
}
else
{
$this->session->set_flashdata( 'alert' , validation_errors() );
//refresh();
}
}
$data['cities'] = $this->Site_model->get_cities('cities', 'name', 'asc');
$data['categories'] = $this->Site_model->get_categories();
$this->load->view( 'create' , $data );
}
You should change
if($this->upload->do_upload('file')){
into
if($this->upload->do_upload('files')){
Future reference Check the link to learn how to upload multiple files in codeigniter
Multiple upload in codeigniter
in this example you you have single image upload and multiple image upload different folders.
if ($param =="upload") {
$config['upload_path'] = './uploads/user_profil/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 15000;
$config['file_name'] = $this->input->post('user_profile')."_profil_image_".mt_rand(100000,900000);
$this->load->library('upload', $config, 'user_profile'); // Create custom object for cover upload
$this->user_profile->initialize($config);
if ( !empty($this->user_profile->do_upload('user_profil_image') ) )
{
$error = array('error' => $this->user_profile->display_errors());
$file_name_profile_picture = $this->input->post('user_profil_image_actual');
$upload_data = $this->user_profile->data();
$file_name_profile_picture = $upload_data['file_name'];
}
else
{
$file_name_profile_picture ="";
}
//map photos
$config_galery['upload_path'] = './uploads/map_profile/';
$config_galery['allowed_types'] = 'gif|jpg|png';
$config_galery['max_size'] = 15000;
$config_galery['file_name'] = $this->input->post('name')."_user_profilm_map_".mt_rand(100000,900000);
$this->load->library('upload', $config_galery, 'map_profile'); // Create custom object for cover upload
$this->map_profile->initialize($config_galery);
if ( !empty($this->map_profile->do_upload('map_profile_image')) )
{
$error = array('error' => $this->map_profile->display_errors());
$map_profile_image =$this->input->post('map_profile_image_actual');
$upload_data1 = $this->map_profile->data();
$map_profile_image = $upload_data1['file_name'];
} else {
$map_profile_image="";
}
if(!empty($_FILES['userfile']['name'])){
$b = $this->doupload_gallery();
$galery_photo_links = json_encode(json_decode($b, true));
} else {
// default empty state
$galery_photo_links ="[]";
}
if (!empty($this->input->post('profile_qr_id'))) {
$data_update_qr_status = array(
'statusi' => 1,
'table_name' => "table_name_db"
);
$this->db->where('profile_qr_id', $this->input->post('profile_qr_id'));
$this->db->update('table_name', $data_update_qr_status);
}
$this->db->insert('table_name', $data);
// ridirect
redirect(base_url('admin/uploads_view'), 'refresh');
}
Related
I want to store the image file with the id as a name .
So I tried the following code :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->passes()) {
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_photo' =>$request->casting_photo];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
But it gives me the 500 (Internal Server Error)
EDIT
if ($validator->passes()) {
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
'casting_photo'=> $input['casting_photo'] ];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
I tried that and the same error occurs.
EDIT2
$fileName = $request->get('id') . '.' . $request->file('casting_photo')->extension();
$request->file('casting_photo')->storeAs('castingimages', $fileName);
But in databse I finf the image stored with just the extension like .png
EDIT3
<form id="castingform" method="post" action="castings" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="id" />
<div class="form-group col-md-6">
<label for="casting_name">Nom</label>
<input type="text" class="form-control" id="casting_name" name="casting_name" placeholder="Nom" >
<span class="text-danger">{{ $errors->first('casting_name') }}</span>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="casting_photo" class="custom-file-input" id="casting_photo">
<div class="input-group-prepend">
<span class="text-danger">{{ $errors->first('casting_photo') }}</span>
</div>
<label class="custom-file-label" for="casting_photo">Choose file</label>
</div>
</div>
<button type="submit" id="createBtn" class="btn btn-success">Sign in</button>
</form>
You are accessing unknown id from request
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
it should be
$request->casting_photo->storeAs(public_path('castingimages'),$request->id.'.'.$request->casting_photo->extension() );
Updated
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
$casting=Casting::create($data);
$casting->casting_photo=$casting->id.'.'.$request->casting_photo->extension() );
$casting->save();
I’m working on category and sub_catengory with laravel select menu related to shopping site using Mass Assignment, I’m having trouble to retrieve from the database from the select menu. I'm getting error said
Undefined variable: categories_dropdown (View:
add_product.blade.php file.
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label for="Category" class="col-sm-3 text-right control-label col-form-label font-
weight-bold">Category: <span class="red_star">∗</span></label>
<div class="col-sm-9">
<select name="category" id="category" class="custom-select">
<?php echo $categories_dropdown; ?>
</select>
</div>
</div>
</div>
ProductController.php
public function store(){
$data = request()->validate([
'sku' => 'required',
'product_name' => 'required',
'description' => 'required',
'brand' => 'required',
'category_id' => 'required',
'sub_categories' => 'required',
'size' => '',
'status' => '',
'product_code' => '',
'care' => '',
]);
Product::create($data);
$categories = Category::where(['parent_id'=>0])->get();
$categories_dropdown = "<option value='' selected disabled>Select</option>";
foreach($categories as $cat){
$categories_dropdown .= "<option value='".$cat->id."'>".$cat->name."</option>";
$sub_categories = Category::where(['parent_id'=>$cat->id])->get();
foreach ($sub_categories as $sub_cat) {
$categories_dropdown .= "<option value = '".$sub_cat->id."'> -- ".$sub_cat->name."</option>";
}
}
//Categories drop down end
return view('admin.products.add_product')->with(compact('categories_dropdown'));
}
product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $guarded = [];
}
what did I missed it!
many thanks.
You have to change this
return view('admin.products.add_product',compact('categories_dropdown'));
I am always using this when I pass data to view:
...
return view('admin.products.add_product')->with([
'categories_dropdown' => $categories_dropdown
]);
The image failed to upload.
link
https://comedoruniversitariouncp.000webhostapp.com/products/create
The project works in local server,
the error appears when i upload to a server
create.blade.php
<form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label class="col-form-label col-sm-2">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name">
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2">Price</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="price" step="0.1">
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2">Amount</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="amount" >
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2">Image</label>
<div class="col-sm-10">
<input type="file" class="form-control-file" name="image">
</div>
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
ProductController.php
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'amount' => 'required',
'image' => 'required|image'
]);
$image = $request->file('image');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
Product::create([
'name' => $request->name,
'price' => $request->price,
'amount' => $request->amount,
'image' => $new_name
]);
return redirect()->route('products.index')->with('message', 'Product created successfully');
}
As you mention about works on local but not remote. I assumed that the upload_max_filesize is greater than the size your upload file, and both on local and remote are not the same.
You may use The Storage Facade as a convenient way to interact with your local filesystems.
use Illuminate\Support\Facades\Storage;
//...
$new_name = rand() . '.' . $image->getClientOriginalExtension();
Storage::disk('public')->putFileAs('images', request->file('image'), $new_name);
//...
Docs
You should try this
Try with adding mimetypes in validation of image.
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'amount' => 'required',
'image' => 'required|mimes:jpeg,bmp,png'
]);
$image = $request->file('image');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
Product::create([
'name' => $request->name,
'price' => $request->price,
'amount' => $request->amount,
'image' => $new_name
]);
return redirect()->route('products.index')->with('message', 'Product created successfully');
}
You Should Try code this,
you may change a part code :
$image->move(public_path('images'), $new_name);
to be code :
$image->move(public_path('images'.$new_name));
this is code, 100% work to me.
I have users table and profiles table, now i want let users to update their info in single form.
Logic
name & email will update in users table
rest of the fields will update in profiles table
Code
blade (form)
{{ Form::model($user, array('route' => array('profileupdate', $user->id), 'method' => 'PUT','files' => true)) }}
<div class="row">
<div class="col-md-6">
<label for="name">Name</label>
{{Form::text('name', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6">
<label for="email">Email</label>
{{Form::text('email', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="about">About</label>
{{Form::textarea('about', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<div class="row">
<div class="col-md-6">
<label for="phone">Phone</label>
{{Form::text('phone', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6">
<label for="website">Website</label>
{{Form::text('website', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="state">State</label>
{{Form::text('state', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="city">City</label>
{{Form::text('city', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-12 mt-3">
<label for="photo">Photo</label>
{{Form::file('photo', array('class' => 'search-field'))}}
</div>
</div>
</div>
<div class="col-md-12">
{{ Form::submit('Update', array('class' => 'btn btn-success mt-5')) }}
</div>
</div>
{{Form::close()}}
Screenshot (code above)
controller
public function update(Request $request, $id)
{
$user = User::find($id);
$user = User::where('id',$id)->first();
$user->name = $request->input('name');
$user->save();
$profile = Profile::find($id);
$profile = Profile::where('id',$id)->first();
$profile->user_id = $request->input('user_id');
$profile->about = $request->input('about');
$profile->website = $request->input('website');
$profile->phone = $request->input('phone');
$profile->state = $request->input('state');
$profile->city = $request->input('city');
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$filename = 'photo' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($photo)->resize(1300, 362)->save($location);
$profile->photo = $filename;
$oldFilename = $profile->photo;
$profile->photo = $filename;
Storage::delete($oldFilename);
}
$profile->save();
return redirect()->route('profile', $user->id)->with('success', 'Your info are updated');
}
PS: please don't go with my controller method, I just put data that
way so you can know what field belongs to what table.
Question
Any idea how i can save my data in 2 tables at the same time?
And I get this Error
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message
You need to check whether save in both or not
public function update(Request $request, $id)
{
$user = User::find($id);
$user = User::where('id',$id)->first();
$user->name = $request->input('name');
if($user->save())
{
$profile = Profile::find($id);
$profile = Profile::where('id',$id)->first();
$profile->user_id = $request->input('user_id');
$profile->about = $request->input('about');
$profile->website = $request->input('website');
$profile->phone = $request->input('phone');
$profile->state = $request->input('state');
$profile->city = $request->input('city');
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$filename = 'photo' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($photo)->resize(1300, 362)->save($location);
$profile->photo = $filename;
$oldFilename = $profile->photo;
$profile->photo = $filename;
Storage::delete($oldFilename);
}
$profile->save();
return redirect()->route('profile', $user->id)->with('success', 'Your info are updated');
}
return redirect()->back()->with('error','Something went wrong');
}
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException this exception comes when you are trying to access post method by hiiting the url in browser.
Since you can't insert into multiple tables in one MySQL command, there is no way to accomplish your requirement. But You can however use a Single Transaction.
DB::transaction(function() {
// first update
User::whereId($id)->update([
'name' => $reqquest->name,
'email' => $request->email,
..........
]);
// second update
Profile::whereId($id)->update([
'about' => $request->website,
'mobile' => $request->mobile,
..........
..........
]);
}
I have written registraion form in codeigniter. it submits the information to database however it does not show the validation errors, error message and success message. But when i write console.log(response); it shows these messages in console. Where is the problem?
Here is my view:
<div id="messages"></div>
<?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
<?= form_open_multipart('user/register', $attributes); ?>
<div class="form-group">
<input name="username" type="text" class="form-control" placeholder="Имя пользователя">
</div>
<div class="form-group">
<input name="mail" type="email" class="form-control" placeholder="Электронный адрес">
</div>
<div class="form-group">
<input name="password" type="password" class="form-control" placeholder="Пароль">
</div>
<div class="form-group">
<input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon btnsubmitforreg">
<span class="rex-btn-text">регистрация</span>
<span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
</button>
</div>
</form>
Here is my controller:
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|alpha_dash|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|md5|min_length[3]'
),
array(
'field' => 'password2',
'label' => 'Confirm Password',
'rules' => 'trim|required|md5|matches[password]'
),
array(
'field' => 'mail',
'label' => 'email',
'rules' => 'trim|required|valid_email|is_unique[instructors.mail]'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_message('is_unique', 'The {field} already exists');
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run() == FALSE)
{
// fails
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} else {
//insert the user registration details into database
$data = array(
'instructors_slug' => $this->input->post('username'),
'mail' => $to_email,
'password' => $this->input->post('password')
);
// insert form data into database
if ($this->user_model->insertUser($data)) {
if ($this->user_model->sendEmail($to_email)) {
// successfully sent mail
echo '<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>';
}
else
{
// error
echo '<div class="alert alert-danger text-center">'.$to_email.' gondermir '.$this->email->print_debugger().'</div>';
}
}
else
{
// error
echo '<div class="alert alert-danger text-center">daxil elemir</div>';
redirect('user/register');
}
}
echo json_encode($validator);
and here is my register.js ajax file:
$(document).ready(function() {
$("#registrationform").unbind('submit').bind('submit', function() {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
console.log(response);
if(response.success == true) {
$("#messages").html(response.messages);
$("#registrationform")[0].reset();
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
}
else {
$.each(response.messages, function(index, value) {
var element = $("#"+index);
$(element)
.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
$(element).after(value);
});
}
} // /success
}); // /ajax
return false;
});
});
In your code you have not added ID in every field. You need to add id as describe below.
<?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
<?= form_open_multipart('user/register', $attributes); ?>
<div class="form-group">
<input name="username" id="username" type="text" class="form-control" placeholder="Имя пользователя">
</div>
<div class="form-group">
<input name="mail" id="mail" type="email" class="form-control" placeholder="Электронный адрес">
</div>
<div class="form-group">
<input name="password" id="password" type="password" class="form-control" placeholder="Пароль">
</div>
<div class="form-group">
<input name="password2" id="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon btnsubmitforreg">
<span class="rex-btn-text">регистрация</span>
<span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
</button>
</div>
</form>
Also in you ajax success function you can check status like given below.
from if(response.success == true){ to if(response.success){
Let me know if it not works.
You should get the idea from this answer.
For Getting validation error to the view from ajax.
This is the Ajax Script to send the sample email for validation:
$.ajax({
type: 'POST',
url: URL,
data: {
email: email
},
success: function(data) {
// Your error message
// Now you can show that anywhere you want inside the view.
}
});
Now I am Setting Rules Using an Array
I have added my validation inside the config folder with form_validation.php
email_verification' => array(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[100]|valid_email|is_unique[your_table.email_column_name]',
'errors' => array(
'required' => 'Email is required.',
'valid_email' => 'Plese Enter Valid Email',
'is_unique' => 'That Email is already taken. Try Again With New Email.'
)
)
)
And Here is the controller:
public function check_email_validation(){
$emial = $this->input->post();
$this->form_validation->set_error_delimiters('<span class="error">', '</div>');
//Now Chaeck for valid email here
if (($this->form_validation->run('email_verification') == FALSE)){
// sending error message to the view.
echo form_error('email');
} else {
unset($_POST);
echo '<span style="color:green;" id="emailIsValid">Email Is Valid</span>';
}
//echo "<span style='color:green;'>Email Is Valid</span>";
}