I am developing an application where i display/edit/delete data from Mysql table using laravel and datatables. I get this error when trying to add or edit data and update it in Mysql table:
Here is code:
<!DOCTYPE html>
<html>
<head>
<title>Datatables Server Side Processing in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Datatables Server Side Processing in Laravel</h3>
<br />
<div align="right">
<button type="button" name="add" id="add_data" class="btn btn-success btn-sm">Add</button>
</div>
<br />
<table id="student_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th><button type="button" name="bulk_delete" id="bulk_delete" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-remove"></i></button></th>
</tr>
</thead>
</table>
</div>
<div id="studentModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="student_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Data</h4>
</div>
<div class="modal-body">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span id="form_output"></span>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="student_id" id="student_id" value="" />
<input type="hidden" name="button_action" id="button_action" value="insert" />
<input type="submit" name="submit" id="action" value="Add" class="btn btn-info" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getdata') }}",
"columns":[
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "action", orderable:false, searchable: false},
{ "data":"checkbox", orderable:false, searchable:false}
]
});
$('#add_data').click(function(){
$('#studentModal').modal('show');
$('#student_form')[0].reset();
$('#form_output').html('');
$('#button_action').val('insert');
$('#action').val('Add');
$('.modal-title').text('Add Data');
});
$('#student_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('ajaxdata.postdata') }}",
method:"POST",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#student_form')[0].reset();
$('#action').val('Add');
$('.modal-title').text('Add Data');
$('#button_action').val('insert');
$('#student_table').DataTable().ajax.reload();
}
}
})
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url:"{{route('ajaxdata.fetchdata')}}",
method:'get',
data:{id:id},
dataType:'json',
success:function(data)
{
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#student_id').val(id);
$('#studentModal').modal('show');
$('#action').val('Edit');
$('.modal-title').text('Edit Data');
$('#button_action').val('update');
}
})
});
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
if(confirm("Are you sure you want to Delete this data?"))
{
$.ajax({
url:"{{route('ajaxdata.removedata')}}",
mehtod:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
})
}
else
{
return false;
}
});
$(document).on('click', '#bulk_delete', function(){
var id = [];
if(confirm("Are you sure you want to Delete this data?"))
{
$('.student_checkbox:checked').each(function(){
id.push($(this).val());
});
if(id.length > 0)
{
$.ajax({
url:"{{ route('ajaxdata.massremove')}}",
method:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
});
}
else
{
alert("Please select atleast one checkbox");
}
}
});
});
</script>
</body>
</html>
Controller:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Student;
use Yajra\DataTables\DataTables;
class AjaxdataController extends Controller
{
function index()
{
return view('student.ajaxdata');
//http://127.0.0:8000/ajaxdata
}
function getdata()
{
$students = Student::select('id', 'first_name', 'last_name');
return DataTables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-edit"></i> Edit<i class="glyphicon glyphicon-remove"></i> Delete';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
function postdata(Request $request)
{
$validation = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
]);
$error_array = array();
$success_output = '';
if ($validation->fails())
{
foreach($validation->messages()->getMessages() as $field_name => $messages)
{
$error_array[] = $messages;
}
}
else
{
if($request->get('button_action') == "insert")
{
$student = new Student([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name')
]);
$student->save();
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
if($request->get('button_action') == 'update')
{
$student = Student::find($request->get('student_id'));
$student->first_name = $request->get('first_name');
$student->last_name = $request->get('last_name');
$student->save();
$success_output = '<div class="alert alert-success">Data Updated</div>';
}
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}
function fetchdata(Request $request)
{
$id = $request->input('id');
$student = Student::find($id);
$output = array(
'first_name' => $student->first_name,
'last_name' => $student->last_name
);
echo json_encode($output);
}
function removedata(Request $request)
{
$student = Student::find($request->input('id'));
if($student->delete())
{
echo 'Data Deleted';
}
}
function massremove(Request $request)
{
$student_id_array = $request->input('id');
$student = Student::whereIn('id', $student_id_array);
if($student->delete())
{
echo 'Data Deleted';
}
}
}
web.php:
Route::get('ajaxdata', 'AjaxdataController#index')->name('ajaxdata');
Route::get('ajaxdata/getdata', 'AjaxdataController#getdata')->name('ajaxdata.getdata');
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
Route::get('ajaxdata/fetchdata', 'AjaxdataController#fetchdata')->name('ajaxdata.fetchdata');
Route::get('ajaxdata/removedata', 'AjaxdataController#removedata')->name('ajaxdata.removedata');
Route::get('ajaxdata/massremove', 'AjaxdataController#massremove')->name('ajaxdata.massremove');
Only delete is working. Also i want to use select-checkbox attribute of datatable but it doesn't work, like this one link for the line color on selection but with multiple selections.
Thanks to #Alaksandar Jesus Gene i solved this issue by changing the post request by a get request for the postdata function inside web.php file and inside the view related script code. Now that it works my second concern still unresolved.
Can u try this
$(document).on('click', '.edit', function () {
data = {};
data.id = $(this).attr("id");
data.first_name = "User"; //$('#first_name').val();
data.last_name = "hello"; //$('#last_name').val();
data.student_id = $(this).attr("id");
data.action = 'Edit';
data.button_action = 'update';
$('#form_output').html('');
$.ajax({
url: "{{route('ajaxdata.fetchdata')}}",
method: 'post',
data: data,
dataType: 'json',
success: function (data) {
// $('#studentModal').modal('show');
// $('.modal-title').text('Edit Data');
console.log("data", data);
},
error: function(err){
console.log("err", err);
}
})
});
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
The router expects post request but you are sending GET request. Please change the method as shown
Related
i am a begineer of laravel and ajax i can do the system well in core php. i just converted to laravel.
i creating simple crud using laravel with ajax but i don't know how call the path through ajax request. what i tried so fat i attached below.pls give me the solution for it.
Screen shot of folder structure
this is view part. i name it
list.blade.php
div class="row">
<div class="col-sm-4">
<form class="card" id="frmProject">
<div class="form-group" align="left">
<label class="form-label">First name</label>
<input type="text" class="form-control" placeholder="first_name" id="first_name" name="first_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Last name</label>
<input type="text" class="form-control" placeholder="last_name" id="last_name" name="last_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Address" id="address" name="address" size="30px" required>
</div>
<div class="card" align="right">
<button type="button" id="save" class="btn btn-info" onclick="addProject()">Add</button>
</div>
</form>
</div>
Ajax Call
function addProject() {
if ($("#frmProject").valid())
{
var _url = '';
var _data = '';
var _method;
if (isNew == true) {
_url = '/student';
_data = $('#frmProject').serialize();
_method = 'POST';
}
else {
_url = '/student',
_data = $('#frmProject').serialize() + "&project_id=" + project_id;
_method = 'POST';
alert(project_id);
}
$.ajax({
type: _method,
url: _url,
dataType: 'JSON',
data: _data,
beforeSend: function () {
$('#save').prop('disabled', true);
$('#save').html('');
$('#save').append('<i class="fa fa-spinner fa-spin fa-1x fa-fw"></i>Saving</i>');
},
success: function (data) {
$('#frmProject')[0].reset();
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Add');
get_all();
var msg;
console.log(data);
if (isNew)
{
msg="Brand Created";
}
else{
msg="Brand Updated";
}
$.alert({
title: 'Success!',
content: msg,
type: 'green',
boxWidth: '400px',
theme: 'light',
useBootstrap: false,
autoClose: 'ok|2000'
});
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
}
Student Controller
class StudentController extends Controller
{
public function index()
{
$data['students'] = Student::orderBy('id','desc')->paginate(5);
return view('student.list',$data);
}
public function create()
{
}
public function store(Request $request)
{
$student = new Student([
'first_name' => $request->post('first_name'),
'last_name'=> $request->post('lastname'),
'address'=> $request->post('address')
]);
]);
$student->save();
return Response::json($student);
}
routes
Route::get('/', [App\Http\Controllers\StudentController::class, 'index']);
Route::get('student', [App\Http\Controllers\StudentController::class, 'index']);
Route::post('student', [App\Http\Controllers\StudentController::class, 'store'])->name('student.store');
$(document).ready(function() {
$(".btn-submit").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("#email").val();
var pswd = $("#pwd").val();
var address = $("#address").val();
$.ajax({
url: "url",
type:'POST',
data: {_token:_token, email:email, pswd:pswd,address:address},
success: function(data) {
printMsg(data);
}
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
console.log(msg.success);
$('.alert-block').css('display','block').append('<strong>'+msg.success+'</strong>');
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
Please use csrf token
guys, I am trying to submit my form using ajax but I don't know exactly what happened it's not posting the values to my table in the database, This is the first time I am using ajax for form submit can anyone help me what mistake I have done.
Here is my view code:
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script type='text/javascript' src="<?php echo base_url(); ?>assets/theme1/js/jquery-2.1.3.min.js"></script>
<!-- <script type="text/javascript"> -->
<script type = "text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: 'json',
data: { organisation_name: organisation_name },
success: function(res) {
if (res) {
// Show Entered Value
jQuery("div#result").show();
jQuery("div#value").html(res.organisation_name);
}
}
});
});
});
</script>
<div class="modal fade" id="createGroup" tabindex="-1" role="dialog" aria-labelledby="createGroup" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" id="modal-content">
<form action="" id="user-groups-create" class="form-horizontal" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Create a New Organisation</h4>
</div>
<div class="modal-body" id="modal-body">
<div class="form-group">
<label for="group_name" class="col-sm-4 control-label">New Organisation Name : </label>
<div class="col-md-8">
<input type="text" id="organisation_name" name="organisation_name" class="form-control" placeholder="Organisation Name" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" value="submit" class="btn btn-primary submit" id="submit">Create Organisation</button>
</div>
</form>
</div>
</div>
</div>
Here is my controller's method createOrg:
public function createOrg() {
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('organisation_name', 'organisation_name', 'required|min_length[5]|max_length[15]');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', 'Organisation name need to be more than 3 characters and less than 15.');
redirect('Organisation', $error);
} else {
//Setting values for tabel columns
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
//Loading View
redirect('Organisation');
}
}
Here is my Model's method orgInsert:
function orgInsert($data) {
// Inserting in Table(organisation)
$this->db->insert('organisation', $data);
}
Can anyone help me what mistake I have done and I have checked my code properly I didn't find exactly where I have done a mistake and I want my modal popup should be there after submitting it until a user clicks on the close button. when I try to keep alert after jQuery.ajax({ it is not coming alert.. and I can able to get the value from var organisation_name in alert...
Thanks in advance.
Hope this will work you :
$('#user-groups-create').on('submit',function(e){
var organisation_name = $("#organisation_name").val();
$.ajax({
type: "POST",
url: "<?=site_url('Organisation/createOrg');?>",
dataType: 'json',
data: {'organisation_name': organisation_name},
success: function(res) {
if (res)
{
alert(res);
window.location.href = "<?=site_url('Organisation');?>";
$("div#result").show();
$("div#value").html(res.organisation_name);
}
},
});
e.preventDefault();
});
Your controller's method createOrg should be like this :
public function createOrg()
{
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
echo json_encode($data);
exit;
}
}
Working by changing the script to like this
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: "html",
data: {organisation_name: organisation_name},
success: function(data) {
alert('success');
}
});
});
});
</script>
I am making an admin panel in codeigniter. I have a table games. It has an image inside it. I want to upload that image using ajax. But for some reason, the image is not being uploaded and error occurs no file selected.
Controller
public function ajax_add() {
$this->_validate();
$config = [
'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
];
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$file = $this->upload->data();
$file_name = $file['file_name'];
if ($file_name == '') {
$data['error_string'][] = 'Please upload an image.';
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
} else {
$data['inputerror'][] = 'image';
$data['error_string'][] = $this->upload->display_errors();
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id'),
'image' => $file_name
);
$insert = $this->game->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update() {
$this->_validate();
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id')
);
$this->game->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
HTML
<div class="container">
<h1 style="font-size:20pt">Games</h1>
<h3>Game Data</h3>
<br />
<button class="btn btn-success" onclick="add_game()"><i class="glyphicon glyphicon-plus"></i> Add Game</button>
<button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
<br />
<br />
<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th style="width:125px;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
Javascript
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function () {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('game/ajax_list') ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [-1, -3], //last column
"orderable": false, //set not orderable
},
],
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_game()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Game'); // Set Title to Bootstrap modal title
}
function edit_game(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url: "<?php echo site_url('game/ajax_edit/') ?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data)
{
$('[name="id"]').val(data.id);
$('[name="title"]').val(data.title);
$('[name="iframe"]').val(data.iframe);
$('[name="status"]').val(data.status);
$('[name="category_id"]').val(data.category_id);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Game'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null, false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
if (save_method == 'add') {
url = "<?php echo site_url('game/ajax_add') ?>";
} else {
url = "<?php echo site_url('game/ajax_update') ?>";
}
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function (data)
{
if (data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
}
});
}
function delete_game(id)
{
if (confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url: "<?php echo site_url('game/ajax_delete') ?>/" + id,
type: "POST",
dataType: "JSON",
success: function (data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
</script>
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Game Form</h3>
</div>
<div class="modal-body form">
<?php
$attributes = array(
'id' => 'form',
'class' => 'form-horizontal'
);
echo form_open_multipart('#', $attributes);
?>
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title</label>
<div class="col-md-9">
<input name="title" placeholder="Title" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Iframe</label>
<div class="col-md-9">
<textarea name="iframe" placeholder="Iframe" class="form-control" type="text"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select name="category_id" class="form-control">
<option value="">--Select Category--</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<?php echo form_upload(['name' => 'image']); ?>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Status</label>
<div class="col-md-9">
<select name="status" class="form-control">
<option value="">--Select Status--</option>
<option value="0">Inactive</option>
<option value="1">Active</option>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
Noticed several required condition you missed in code
First in your ajax_add method
if ($this->upload->do_upload()) this should contain image field name like
if ($this->upload->do_upload('image')){// as your file upload field name is "image"
}
Then for ajax upload your client side code some params are missing
contentType: false,
processData: false,
so your ajax method should (in save method) looks like
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
contentType: false,
processData: false
.....
processData this is important when file upload via ajax
In addition to the suggestions from Rejoanul, you may want to check that you are not uploading a file that is too large.
Apparently if the file you are attempting to upload is larger than the maxsize, the FILES variable will be empty.
https://stackoverflow.com/a/21633123/2153218
Try to change This line in your controller
$img = "img"; // input name="img"
$this->upload->do_upload($img);
Try this
$config = array( 'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
'overwrite' => TRUE, );
get_instance()->load->library('upload', $this->config);
if($this->upload->do_upload('image')) {
echo "file upload success";
} else {
echo $this->upload->display_errors();
}
I want to insert row in database using ajax jquery post method for that i am using the below code in Codeigniter, but my data is not inserted in a database.
Please help to sort out my issue.
View:
$("#Submit_Course_Goal").on("click", function (e) {
e.preventDefault();
var dataString = $("form#courseGoalForm").serializeArray();
alert("datastring"+dataString);
$.ajax({
type: "post",
url: "<?php echo base_url();?>create_course/create_course_goal",
cache: false,
data: dataString,
success: function(data){
alert("data"+data);
},
error: function(){
alert('Error while request..');
}
});
});
<form name="courseGoalForm" id="courseGoalForm" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="c_id" value="<?=$result;?>" />
<textarea data-focus="false" rows="8" name="description1"> </textarea>
<textarea data-focus="false" rows="8" name="description2"> </textarea>
<textarea data-lang="en" rows="8" name="description3"> </textarea>
<input type="submit" name="submit" value="Save" class="btn btn-primary btn btn-success" id="Submit_Course_Goal" />
</form>
Model:
public function create_course_goal($data,$id) {
$this->load->database();
$this->db->where('id', $id);
$this->db->update('course', $data);
$course_id=$id;
if ($this->db->affected_rows() > 0) {
return $course_id;
}
else
{
return false;
}
}
Controller:
public function create_course_goal(){
$course_goal1=$this->input->post('description1');
$course_goal2=$this->input->post('description2');
$course_goal3=$this->input->post('description3');
$id=$this->input->post('c_id');
$data=array('course_goal1'=>$course_goal1,'course_goal2'=>$course_goal2,'course_goal3'=>$course_goal3);
$result_course = $this->course_model->create_course_goal($data,$id);
if($result_course!='false')
{
return true;
}
else
{
return false;
}
}
have you tried this !
var dataString = $("#courseGoalForm").serialize();
instead of
var dataString = $("form#courseGoalForm").serializeArray();
Try these codes.
("#Submit_Course_Goal").on("click", function (e) {
e.preventDefault();
var description1 = $("#description1").val();
var description2 = $("#description2").val();
var description3 = $("#description3").val();
$.ajax({
type: "post",
url: "<?php echo base_url();?>create_course/create_course_goal",
cache: false,
data: {
desc1 : description1,
desc2 : description2,
desc3 : description3
},
success: function(data){
console.log(data);
},
error: function(){
alert('Error while request..');
}
});
});
<!-- Form -->
<form name="courseGoalForm" id="courseGoalForm" action="" method="post" enctype="multipart/form-data" onclick="return false">
<input type="hidden" name="c_id" value="<?=$result;?>" />
<textarea data-focus="false" rows="8" name="description1" id="description1"> </textarea>
<textarea data-focus="false" rows="8" name="description2" id="description2"> </textarea>
<textarea data-lang="en" rows="8" name="description3" id="description3"> </textarea>
<input type="submit" name="submit" value="Save" class="btn btn-primary btn btn-success" id="Submit_Course_Goal" />
</form>
<!-- Controller -->
<?php
public function create_course_goal(){
$data=array(
'ID' => $this->input->post('c_id'),
'course_goal1'=> $this->input->post('desc1'),
'course_goal2'=> $this->input->post('desc2'),
'course_goal3'=> $this->input->post('desc3')
);
$result = $this->course_model->create_course_goal($data);
if ($result) {
echo 'success';
}else echo 'fail';
}
/*MODEL*/
function create_course_goal($data = array())
{
return $this->db->insert('course',$data);
}
?>
Try this.
Controller.
public function create_course_goal(){
$data=array(
'ID' => $this->input->post('c_id'),
'course_goal1'=> $this->input->post('description1'),
'course_goal2'=> $this->input->post('description2'),
'course_goal3'=> $this->input->post('description3')
);
$result = $this->course_model->create_course_goal($data);
if ($result) {
echo 'success';
}else echo 'fail';
}
Model
function create_course_goal($options = array())
{
if(isset($options['course_goal1']))
$this->db->set('course_goal1',$options['course_goal1']);;
if(isset($options['course_goal2']))
$this->db->set('course_goal2',$options['course_goal2']);;
if(isset($options['course_goal3']))
$this->db->set('course_goal3',$options['course_goal3']);;
$this->db->where('ID',$options['ID']);
$this->db->update('course');
return $this->db->affected_rows();
}
Note : course_goal1, course_goal2, course_goal3 should be same as in database. and course should be database table's name.
This was for update database if you want to insert new data use this model
function addNewData($data = array())
{
return $this->db->insert('course',$data);
}
Note 2 : in your database 'id' should be primary and auto incrementing
your table name should be 'course'
and row names should be 'course_goal1', 'course_goal2', 'course_goal3'
Have you tried removing method='post' from the Form and submit your data with ajax
I'km trying the autocomplete by selecting data from DB and getting back the response as json but all I got is internal server error, could it be a problem of csrf token?
this is the script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('input:text').bind({
});
$("#auto").autocomplete({
minLength:2,
source: '{{ URL('getdata') }}'
});
});
</script>
and this in the controller:
public function getData(){
$term = Input::get('term');
$data = DB::table('items')->distinct()->select('item_name')->where('word', 'LIKE', $term.'%')->groupBy('word')->take(10)->get();
foreach ($data as $v) {
$return_array[] = array('value' => $v->word);
}
return Response::json($return_array);
}
Problem was in getData function, this one works.
public function getData(){
$term = Input::get('term');
$data = DB::table('items')->distinct()->select('item_name')->where('item_name', 'LIKE', $term.'%')->groupBy('item_name')->take(10)->get();
foreach ($data as $v) {
$return_array[] = array('value' => $v->item_name);
}
return Response::json($return_array);
}
inspector.js:44 GET http://127.0.0.1:8000/product/autocomplete?terms=d 500 (Internal Server Error) #
*This is my Controller,
public function autosearch(Request $request){
// dd($request->all());
$query = $request->get('term','');
$allproducts = Product::where('product_title','LIKE','%'.$query.'%')->get();
$data = array();
foreach($allproducts as $product)
{
$data[] = array('value'=>$product->product_title,'id'=>$product->id);
}
if(count($data))
{
return $data;
}
else{
return ['value'=>"No Result Found",'id'=>''];
}
}
This is my script tag:
<script>
$(document).ready(function(){
var path = "{{route('autosearch')}}"
$('#search_text').autocomplete({
source:function(request,response)
{
$.ajax({
url:path,
dataType:"JSON",
data:{
term:request.term
},
success:function(data)
{
response(data);
}
});
},
minLength:1,
});
});
</script>
This is my HTML Form:
<div class="col d-none d-xl-block">
<label class="sr-only" for="searchproduct">Search</label>
<div class="input-group">
<input id="search_text" type="search" name="search" class="form-control py-2 pl-5 font-size-15 border-right-0 height-40 border-width-2 rounded-left-pill border-primary typeahead" placeholder="Search for Products" aria-label="Search for Products" aria-describedby="searchProduct1" autocomplete="off" required>
<div class="input-group-append">
<button class="btn btn-primary height-40 py-2 px-3 rounded-right-pill" type="submit" id="searchProduct1">
<span class="ec ec-search font-size-24"></span>
</button>
</div>
</div>
</div>