Codeigniter Ajax Crud using DataTables - Insert _ Add Data - codeigniter

There is this codeigniter tutorial from weblesson youtube page About working with Datatables and Codeigniter.
But i'm having some difficulties inserting data into the database.
Controller:
function user_action(){
if($_POST["action"] == "Add")
{
$insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post("last_name"),
'image' => $this->upload_image()
);
$this->load->model('crud_model');
$this->crud_model->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
View Class:
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<label>Select User Image</label>
<input type="file" name="user_image" id="user_image" />
</div>
<div class="modal-footer">
<input type="submit" name="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
When i ran this code, i got the following errors:
Error message
And when i did
if(isset($_POST["action"]) && $_POST["action"] == "Add")
i got an empty alert box

In controller,at your constructor load url helper. and save file as Main.php with code::
function __construct()
{
$this->load->helper('url');
}
function user_action(){
if($_POST["action"] == "Add")
{
$insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post("last_name"),
'image' => $this->upload_image()
);
$this->load->model('crud_model');
$this->crud_model->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
at your view define a input of type hidden with name action and value add.And define action of your form.As follows..
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" action="<?php echo base_url('main/user_action');?>">
<input type="hidden" name="action" value="add">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<label>Select User Image</label>
<input type="file" name="user_image" id="user_image" />
</div>
<div class="modal-footer">
<input type="submit" name="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
Hope it will works..

I did fix the problem but don't know if it's the best way to do it
what i did was change this two codes:
controller:
public function user_action(){
if(isset($_POST["action"]) && $_POST["action"] == "Add")
{
$insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post("last_name"),
'image' => $this->upload_image()
);
$this->load->model('crud_model');
$this->crud_model->insert_crud($insert_data);
echo 'Data Inserted';
}
and Ajax:
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
$('#user_image').val('');
return false;
}
if(firstName != '' && lastName != '')
{
$.ajax({
url:"<?php echo base_url() . 'main/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Bother Fields are Required");
}
});
for controller:
where it say:
if(isset($_POST["action"]) && $_POST["action"] == "Add")
remove it
In in the Ajax Code:
create a link variable to get the action attribute of the form like so:
var link = $('#user_form').attr('action');
and parse it to to the ajax url.
And that's it!

I did fix the problem but don't know if it's the best way to do it
<div class="modal-footer">
<input type="hidden" name="action" class="btn btn-success" value="Add">
<input type="submit" name="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
This is a hidden field that we have used to describe database operations like insert, update, delete

Related

Image doesnt save (Laravel & Vue Js)

Template
<form #submit.prevent=" addUser()">
<div class="form-group">
<label for="addUser">Password</label>
<input type="tex" class="form-control" id="name" placeholder="Name" name="name" v-model="form.name"
:class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="tex" class="form-control" id="email" placeholder="Email" name="email" v-model="form.email"
:class="{ 'is-invalid': form.errors.has('email') }">
<has-error :form="form" field="email"></has-error>
</div>
<div class="form-group">
<label for="picture">Picture</label>
<input type="file" class="form-control" id="image" placeholder="Picture" name="image" >
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
JavaScript
import Form from 'vform'
export default {
name: "Users",
data() {
return {
form: new Form({
name: '',
email: '',
})
}
},
methods: {
addUser() {
this.form.post('/addUser').
then((response) => {
console.log('I clicked');
})
}
}
}
Laravel
$this->validate($request,[
'name'=> 'required',
'email'=> 'required '
]);
$newUser = New NewUser();
$newUser->name = $request->name;
$newUser->email = $request->email;*/
if($request->hasFile('image')){
$imageN = $request->image;
$request->image->storeAs('public/upload',$imageN);
}
$newUser->save();
The image file is not being save because it is never being send with the request to laravel.
You could either add the image to the new Form() or check out the following post on how to upload an image: How do I upload image in vuejs?

Uploading pdf file in laravel vuejs Axios

I have created a project for bookshop and in the section of employee information I want to upload a PDF file using code given below.it give me the below error.I have been trying since few days but I could not get the solution if there is any sample way please guide me
any help will be highly appreciated
The given data was invalid.","errors":{"file":["The file field is
required.
controller code is
public function store(Request $request)
{
$DocumentType= new DocumentType();
$this->validate($request,[
'name'=>'required',
'file' => 'required',
]);
$DocumentType->name = $request->input('name');
$fileName = time().'.'.$request->file->extension();
$request->file->move(public_path('Files'), $fileName);
$DocumentType->file = $name;
$DocumentType->save();
return response()->json($DocumentType);
}
Vue code is
<template>
<div class="container">
<div
class="modal fade"
id="addNew"
tabindex="-1"
role="dialog"
aria-labelledby="addNewLabel"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-show="!editMode" id="addNewLabel">ثبت اسناد جدید</h5>
<h5 class="modal-title" v-show="editMode" id="addNewLabel">تمدید اسناد</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" style="margin-right: 317px;">×</span>
</button>
</div>
<form
#submit.prevent="editMode ? updateDocumentType() : createDocumentType()"
enctype="multipart/form-data"
>
<div class="modal-body">
<div class="form-group">
<input
v-model="form.name"
placeholder="نام"
type="text"
name="name"
class="form-control"
:class="{ 'is-invalid': form.errors.has('name') }"
/>
<has-error :form="form" field="name"></has-error>
</div>
<div class="form-group">
<label for="file" class="col-sm-4 control-label">File</label>
<div class="col-sm-12">
<input
type="file"
class="form-input"
:class="{ 'is-invalid': form.errors.has('file') }"
id="file"
name="file"
/>
<has-error :form="form" field="file"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">لغو</button>
<button
v-show="editMode"
:disabled="form.busy"
type="submit"
class="btn btn-success"
>تمدید</button>
<button
v-show="!editMode"
:disabled="form.busy"
type="submit"
class="btn btn-primary"
>ثبت</button>
</div>
</div>
</form>
</div>
</div>
</div>
</template>
</div>
<script>
createDocumentType() {
// axios.get("api/getAllDocumentTypeDocumentType").then(response => {
// let data = response.data;
if (this.form.name == "") {
toast.fire({
type: "warning",
icon: "warning",
html: "<h5>نام لازم است.</h5>"
});
}
// else if (this.form.file == "") {
// toast.fire({
// type: "warning",
// icon: "warning",
// html: "<h5>لطفا،اسناد را انتخاب نماید.</h5>"
// });
// }
else {
this.form
.post("api/DocumentType")
.then(() => {
// the below function will be use to reload the page
// this.$emit("refreshPage");
$("#addNew").modal("hide");
toast.fire({
icon: "success",
type: "success",
html: "<h5> اسنادموافقانه اجاد گردید</h5>"
});
Fire.$emit("refreshPage");
this.form.reset();
// this.$Progress.finish();
})
.catch(er => {
console.log(er);
});
}
}
</script>
Migration table code
public function up()
{
Schema::create('document_types', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('file')->nullable();
$table->softDeletes();
$table->timestamps();
});
}
Code in API route
Route::apiResources(['DocumentType'=>'API\DocumentTypeController']);
Route::get('getAllDocumentType','API\DocumentTypeController#getAll');
The given data was invalid.","errors":{"file":["The file field is required. This error is because there is no existing file in your payload upon submission of your form.
in your form, bind data to your input file like what you did to your input name. like this
<input
type="file"
v-model="form.file"
class="form-input"
:class="{ 'is-invalid': form.errors.has('file') }"
id="file"
name="file"
/>
Or, attach an event to this file input and process the file provided. like this
<input
type="file"
class="form-input"
:class="{ 'is-invalid': form.errors.has('file') }"
id="file"
name="file"
#change="selectFile"
/>
Then in your methods, create also a selectFile function
methods: {
selectFile(file) {
if(file == "") return false
this.form.file = file.target.files
console.log(this.form.file)
}
}

how to import excel file in mysql using laravel 5.7 with vue JS

i was creating vue file for inpute Excel or csv file laravel 5.7
i was using Maatwebsite/Laravel-Excel
dont know how to route there things it if my first time to make app like laravel with vue JS
Don't know what to doo
there is Vue file
<template>
<div class="container">
<div class="row mt-5">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Students</h3>
<div class="card-tools">
<button class="btn btn-success" data-toggle="modal" data-target="#exampleModal">Add New <i class="fas fa-user-plus"></i></button>
<button class="btn btn-primary" data-toggle="modal" data-target="#importModel">Import <i class="fas fa-file-excel"></i></button>
<button class="btn btn-warning" data-toggle="modal" data-target="#export">Export <i class="fas fa-file-excel"></i></button>
</div>
</div>
</div>
<!-- /.card -->
</div>
</div><!-- /.row -->
<!-- Modal -->
<div class="modal fade" id="importModel" tabindex="-1" role="dialog" aria-labelledby="importModelLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="importModelLabel">Import Excel</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label>Import</label>
<input type="file" name="excel_file"
class="form-control" :class="{ 'is-invalid': form.errors.has('excel_file') }">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save Student</button>
</div>
</form>
</div>
</div>
</div>
<!--Exit Modal-->
</div>
</template>
<script>
export default {
data(){
return{
form: new Form({
first_name:'',
last_name:'',
email:'',
password:'',
designation:''
})
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
set a post route to import data in web.php file
that will route the things as pr laravelExcel
Route::post('importExcel', 'API/StudentMasterController#import');
in a controller file
public function import()
{
Excel::import(new StudentImport, request()->file('excel_file'));
//return redirect('/')->with('success', 'All good!');
}
and in a APP/import/studentmaster.php file
public function model(array $row)
{
return new Student_master([
'EnrollmentNo' => $row[22],
]);
}
this is vue views and js my code :
<form method="POST" action="#" class="form-horizontal" #submit.prevent="createUpload" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group row"><label for="name" class="col-sm-2 form-control-label">Parameter</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="result_file" ref="myFiles" placeholder="Name Parameter" required="required" #change="previewFiles($event)">
<input type="hidden" name="result_file2" class="form-control" id="title" v-model="datafileupload.result_file3" placeholder="Name Parameter" required="required">
<input type="hidden" name="hasilcek" class="form-control" id="hasilcek" v-model="datafileupload.hasilcek3" placeholder="Name Parameter" required="required">
<input type="hidden" class="form-control" v-model="datapush.filename">
<input type="hidden" class="form-control" v-model="datapush.size">
</div><br><br><br>
<div v-if="this.hasilcekexcel > 0" class="alert alert-warning">File {{ namafile }} exists , do you want to replace it ?</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" #click="doSomethingOnHidden" >Close</button>
<input type="submit" class="btn btn-primary" id="submit_upload2" v-if="this.hasilcekexcel > 0" value="Replace">
<input type="submit" class="btn btn-primary" id="submit_upload" v-if="this.hasilcekexcel == 0" value="Upload">
</div>
</form>
js upload :
createUpload () {
var data = new FormData();
var file = this.$refs.myFiles.files[0];
var size = this.$refs.myFiles.files[0].size;
data.append('filenya', file);
data.append('namasifile', this.datafileupload.result_file3);
data.append('angkacek', this.datafileupload.hasilcek3);
axios.post('excelupload/upload', data)
.then(response => {
this.pesertas.push(response.data.data);
this.showModal =false;
});
},
controller :
$excelupload = new Exceluploads;
$hasilcek = $request->angkacek;
$requestfile = $request->namasifile;
if ($request->filenya != '') {
$input = Input::all();
$size = $request->file('filenya')->getClientSize();
$file = array_get($input,'result_file');
$userID = Auth::user()->id;
$uploaded_by = Auth::user()->name;
$destinationPath = 'excel';
// GET THE FILE EXTENSION
$extension = 'xls';
$fileName = $requestfile.'.'.$extension;
if ($hasilcek > 0) {
File::delete($destinationPath.'/'.$fileName);
$upload_success = $request->filenya->move($destinationPath, $fileName);
return response()->json(['data' => Exceluploads::find($excelupload->id)]);
}else if ($hasilcek == 0) {
$upload_success = $request->filenya->move($destinationPath, $fileName);
$excelupload->filename = $fileName;
$excelupload->directory = $destinationPath.'/'.$fileName;
$excelupload->size = $size;
//1 = not custome
$excelupload->type = 1;
$excelupload->uploaded_by = $uploaded_by;
$excelupload->save();
return response()->json(['data' => Exceluploads::find($excelupload->id)]);
}
}

Error 500 in Laravel ajax

I got this error which I tried to fix with no success
in console
xhr.send( options.hasContent && options.data || null );//error
js
var data_id;
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$(".edit_cost").click(function() {
data_id = $(this).closest('div.portlet').attr('data-id');
});
$(".submit_cost").on('click',function(e) {
e.preventDefault();
var type = $(".cost_form").find('input[name="type"]').val();
var cost = $(".cost_form").find('input[name="cost"]').val();
var revenue = $(".cost_form").find('input[name="revenue"]').val();
var profit = $(".cost_form").find('input[name="profit"]').val();
var data = $("form.cost_form").serialize();
alert(data);
$.ajax({
url: "/partA-edit-cost",
type: "POST",
data: {
// 'types': type,
//'cost': cost,
// 'revenue': revenue,
// 'profit': profit,
// 'data_id': data_id
// 'data' : data
},
error: function(data) {
console.log(data);
},
success: function(log) {
console.log(log);
}
})
});
});
Routes
Route::post('/partA-edit-cost', 'CostController#editCost');
html
#foreach($costs as $widget)
<li data-row="1" data-col="1" data-sizex="3" data-sizey="3">
<div class="portlet portlet-sortable light bordered ui-widget-content ui-resizable" data-id="{{$widget->id }}" data-find="{{$widget->id.$widget->name }}" data-name="{{ $widget->name }}">
<div class="portlet-title ui-sortable-handle">
<div class="caption font-green-sharp">
<i class="fa fa-money"></i>
<span class="caption-subject bold uppercase">{{ $widget->name }}</span>
</div>
<div class="actions">
<a href="javascript:;" class="btn btn-circle btn-default btn-sm remove">
<i class="fa fa-trash-o"></i> Remove </a>
<div class="btn-group">
<button type="button" class="btn btn-primary edit_cost" data-toggle="modal" data-target="#cost"><i class="fa fa-edit" data-button ="{{$widget->id}}"></i>Edit</button>
</div>
<a class="btn btn-circle btn-icon-only btn-default fullscreen" href="javascript:;"></a>
</div>
</div>
<div class="portlet-body">
<div>{!! html_entity_decode($widget->api) !!}</div>
</div>
</div>
</li>
#endforeach
<div class="modal fade bs-example-modal-sm cost" id="cost" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm" id="cost">
<div class="modal-content">
<div class="col-md-12" style="width:500px;">
<div class="portlet box white">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Edit Cost
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="/partA-edit-cost" class="cost_form" method="POST">
<div class="form-actions top">
<button type="submit" class="btn green submit_cost">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
<div class="form-body">
<div class="form-group">
<label class="control-label">Type</label>
<input type="text" name="type" class="form-control type" placeholder="Enter Cost type">
</div>
<div class="form-group">
<label class="control-label">Cost</label>
<input type="text" name ="cost" class="form-control" placeholder="Enter Cost">
</div>
<div class="form-group">
<label class="control-label">Revenue</label>
<input type="text" name="revenue" class="form-control" placeholder="Enter Revenue">
</div>
<div class="form-group">
<label class="control-label">Profit</label>
<input type="text" name="profit" class="form-control" placeholder="Enter Profit">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Cost;
class CostController extends Controller
{
public function editCost(Request $request)
{
$type = $request->get('type');
//$id = $request->get('id');
$cost = COST::where('id', 3);
$cost->type = "type";
$cost->save();
return \Response::json(['id' => $id,'type' => $type],200);
}
}
Disable temporarily stuff inside the editCost method will remove the error
public function editCost(Request $request) {
echo "ok";
}//returns on "ok " to the console;
I think there is any error at $cost = COST::where('id', 3);, try changing it to
$cost = Cost::where('id', 3)->first();
$cost = COST::where('id', 3); results query scope not the Model, therefore you should add first() method, if no result matches your condition it will return null which can also result in the internal error issue since, you are calling $cost->type on the next line.
I hope this helps.
In your code the variable $id is not defined in your return statement ( you have commented it out )
return \Response::json(['id' => $id,'type' => $type],200);
I think the code should look like:
$type = $request->get('type');
//$id = $request->get('id');
$cost = Cost::where('id', 3)->first();
$cost->type = "type";
$cost->save();
return \Response::json(['id' => 3,'type' => $type],200);
If that works you can use the dynamic $id and $type variables

update using modal of bootstrap in codeigniter

I have a problem when updating the password of student, I am using the modal of bootstrap: -> here is the picture updatepassword
here is my modal and the action is studentpasswordupdate/updatepasswordstudent, I retrieve the value using echo $Password in session
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title text-center">Change Password</h4>
</div>
<div class="modal-body"><br>
<form action="<?php echo site_url("studentpasswordupdate/updatepasswordstudent") ?>" method="POST">
<div class="l">
<label class=" input-lg" style="font-size: 28px;">Password:</label> <input class="k" type="text" name="Password" value="<?php echo $Password ?>" >
</div>
<br> <br><br>
<div class="modal-footer">
<button type="submit" name="Submit" class="btn btn-info m" >Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
and here is my controller/method:
class Studentpasswordupdate extends CI_Controller {
//put your code here
function updatepasswordstudent(){
$id = $this->input->post('Id');
$data= array(
'Password' => $this->input->post('Password')
);
$this->db->where('Id', $id);
$this->db->update('studentinformation',$data);
$hasError = $this->db->_error_message();
echo $hasError;
redirect('studentform/index', 'refresh');
}
}
Try this
class Studentpasswordupdate extends CI_Controller {
function updatepasswordstudent()
{
$id = $this->input->post('Id');
$data = array(
'Password' => $this->input->post('Password')
);
$this->db->where('Id', $id);
if (!$this->db->update('studentinformation',$data))
{
$hasError = $this->db->_error_message();
echo $hasError;
}
else{
redirect('studentform/index', 'refresh');
}
}
}
In View
Set name field foe this
<input type="hidden" name="Id" value="<?php echo $Id ?>">

Resources