I'm using Ajax + Datatable + Codeigniter. My target is to insert my form into my DB. However, it is not inserting. My current codes produces successful state alert. However, it is not inserting. Is there anything I missed? Additionally, i checked my image file path and it is still empty after insert. Any help will be appreciated. Thank you.
Views:
<div class="table-responsive">
<br/>
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<br /><br />
<table id="user_datas" class="table table-bordered table-striped">
<thead>
<tr>
<th width="10%">Image</th>
<th width="35%">First Name</th>
<th width="35%">Last Name</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" >
<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">
<input type="text" name="firstname" id="firstname" class="form-control" />
<br />
<input type="text" name="lastname" id="lastname" class="form-control" />
<br />
<input type="file" name="user_image" id="user_image" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Ajax:
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#user_uploaded_image').html('');
})
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"<?php echo base_url() . 'profile/fetch_user'; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var firstName = $('#firstname').val();
var lastName = $('#lastname').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();
if(extension != '')
{
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() . 'profile/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert('Successful');
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Fields are Required");
}
});
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"<?php echo base_url(); ?>profile/fetch_single_user",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#firstname').val(data.firstname);
$('#lastname').val(data.lastname);
$('.modal-title').text("Edit User");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
}
})
});
});
Controller:
function fetch_user(){
$this->load->model("profile_repository");
$fetch_data = $this->profile_repository->make_datatables();
$data = array();
foreach($fetch_data as $row)
{
$sub_array = array();
$sub_array[] = '<img src="'.base_url().'public/assets/upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" />';
$sub_array[] = $row->firstname;
$sub_array[] = $row->lastname;
$sub_array[] = '<button type="button" name="update" id="'.$row->userID.'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row->userID.'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval(isset($_POST["action"]) && $_POST["action"]),
"recordsTotal" => $this->profile_repository->get_all_data(),
"recordsFiltered" => $this->profile_repository->get_filtered_data(),
"data" => $data
);
echo json_encode($output);
}
function user_action(){
if(isset($_POST["action"]) == "Add")
{
$insert_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post("lastname"),
'image' => $this->upload_image()
);
$this->load->model('profile_repository');
$this->profile_repository->insert_crud($insert_data);
echo 'Data Inserted';
}
if(isset($_POST["action"]) == "Edit")
{
$user_image = '';
if($_FILES["user_image"]["name"] != '')
{
$user_image = $this->upload_image();
}
else
{
$user_image = $this->input->post("hidden_user_image");
}
$updated_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'image' => $user_image
);
$this->load->model('profile_repository');
$this->profile_repository->update_crud($this->input->post("user_id"), $updated_data);
echo 'Data Updated';
}
}
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './public/assets/upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
function fetch_single_user()
{
$output = array();
$this->load->model("profile_repository");
$data = $this->profile_repository->fetch_single_user($_POST["user_id"]);
foreach($data as $row)
{
$output['firstname'] = $row->firstname;
$output['lastname'] = $row->lastname;
if($row->image != '')
{
$output['user_image'] = '<img src="'.base_url().'public/assets/upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" /><input type="hidden" name="hidden_user_image" value="'.$row->image.'" />';
}
else
{
$output['user_image'] = '<input type="hidden" name="hidden_user_image" value="" />';
}
}
echo json_encode($output);
}
}
Model:
var $table = "users";
var $select_column = array("userID", "firstname", "lastname", "image");
var $order_column = array(null, "firstname", "lastname", null, null);
function make_query()
{
$this->db->select($this->select_column);
$this->db->from($this->table);
if(isset($_POST["search"]["value"]))
{
$this->db->like("firstname", $_POST["search"]["value"]);
$this->db->or_like("lastname", $_POST["search"]["value"]);
}
if(isset($_POST["order"]))
{
$this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else
{
$this->db->order_by('userID', 'DESC');
}
}
function make_datatables(){
$this->make_query();
if(isset($_POST["length"]) && $_POST["length"] != -1)
{
$this->db->limit($_POST['length'], $_POST['start']);
}
$query = $this->db->get();
return $query->result();
}
function get_filtered_data(){
$this->make_query();
$query = $this->db->get();
return $query->num_rows();
}
function get_all_data()
{
$this->db->select("*");
$this->db->from($this->table);
return $this->db->count_all_results();
}
function insert_crud($data)
{
$this->db->insert('users', $data);
}
function fetch_single_user($user_id)
{
$this->db->where("userID", $user_id);
$query=$this->db->get('users');
return $query->result();
}
function update_crud($user_id, $data)
{
$this->db->where("userID", $user_id);
$this->db->update("users", $data);
}
}
There was a mistake in
if(isset($_POST["action"]) == "Add")
isset function returning boolean, therefore your condition will return
if(true == "Add")
which return false.
your code return successful state because it was successful state for your ajax request (code 200), not your insert function
you should change your user_action to :
if(isset($_POST["action"])){
if($_POST["action"] == "Add")
{
$insert_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post("lastname"),
'image' => $this->upload_image()
);
$this->load->model('profile_repository');
$this->profile_repository->insert_crud($insert_data);
echo 'Data Inserted';
}
else if($_POST["action"] == "Edit")
{
$user_image = '';
if($_FILES["user_image"]["name"] != '')
{
$user_image = $this->upload_image();
}
else
{
$user_image = $this->input->post("hidden_user_image");
}
$updated_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'image' => $user_image
);
$this->load->model('profile_repository');
$this->profile_repository->update_crud($this->input->post("user_id"), $updated_data);
echo 'Data Updated';
}
}
Related
I changed the login by mail to login with phone number in a laravel system, but it does not log in in any way. either it doesn't find it in the database or I'm doing something wrong. I asked chatgpt and searched many forums but still no success. where am i doing wrong?
LoginController
namespace App\Http\Controllers;
use Exception;
use App\Models\User;
use App\Helper\Reply;
use App\Models\Social;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
use App\Events\TwoFactorCodeEvent;
use App\Traits\SocialAuthSettings;
use Froiden\Envato\Traits\AppBoot;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use \Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
use AppBoot, SocialAuthSettings;
protected $redirectTo = 'account/dashboard';
public function checkEmail(LoginRequest $request)
{
exit ;
$user = User::where('mobile', $request->mobile)
->select('id')
->where('status', 'active')
->where('login', 'enable')
->first();
if (is_null($user)) {
throw ValidationException::withMessages([
Fortify::username() => __('messages.invalidOrInactiveAccount'),
]);
}
return response([
'status' => 'success'
]);
}
public function checkCode(Request $request)
{
$request->validate([
'code' => 'required',
]);
$user = User::find($request->user_id);
if($request->code == $user->two_factor_code) {
// Reset codes and expire_at after verification
$user->resetTwoFactorCode();
// Attempt login
Auth::login($user);
return redirect()->route('dashboard');
}
// Reset codes and expire_at after failure
$user->resetTwoFactorCode();
return redirect()->back()->withErrors(['two_factor_code' => __('messages.codeNotMatch')]);
}
public function resendCode(Request $request)
{
$user = User::find($request->user_id);
$user->generateTwoFactorCode();
event(new TwoFactorCodeEvent($user));
return Reply::success(__('messages.codeSent'));
}
public function redirect($provider)
{
$this->setSocailAuthConfigs();
return Socialite::driver($provider)->redirect();
}
public function callback(Request $request, $provider)
{
$this->setSocailAuthConfigs();
try {
try {
if ($provider != 'twitter') {
$data = Socialite::driver($provider)->stateless()->user();
}
else {
$data = Socialite::driver($provider)->user();
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
return redirect()->route('login')->with('message', $errorMessage);
}
$user = User::where(['email' => $data->email, 'status' => 'active', 'login' => 'enable'])->first();
if ($user) {
// User found
DB::beginTransaction();
Social::updateOrCreate(['user_id' => $user->id], [
'social_id' => $data->id,
'social_service' => $provider,
]);
DB::commit();
Auth::login($user, true);
return redirect()->intended($this->redirectPath());
}
else {
return redirect()->route('login')->with(['message' => __('messages.unAuthorisedUser')]);
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
return redirect()->route('login')->with(['message' => $errorMessage]);
}
}
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/login';
}
public function username()
{
return 'mobile';
}
}
Here blade code;
<label for="mobile">#lang('auth.mobile')</label>
<input tabindex="1" type="text" name="mobile"
class="form-control height-50 f-15 light_text" autofocus
placeholder="#lang('auth.mobile')" id="mobile">
<input type="hidden" id="g_recaptcha" name="g_recaptcha">
</div>
#if ($socialAuthSettings->social_auth_enable)
<button type="submit" id="submit-next"
class="btn-primary f-w-500 rounded w-100 height-50 f-18 ">#lang('auth.next') <i
class="fa fa-arrow-right pl-1"></i></button>
#endif
<div id="password-section"
#if ($socialAuthSettings->social_auth_enable) class="d-none" #endif>
<div class="form-group text-left">
<label for="password">#lang('app.password')</label>
<x-forms.input-group>
<input type="password" name="password" id="password"
placeholder="#lang('placeholders.password')" tabindex="3"
class="form-control height-50 f-15 light_text">
<x-slot name="append">
<button type="button" data-toggle="tooltip"
data-original-title="#lang('app.viewPassword')"
class="btn btn-outline-secondary border-grey height-50 toggle-password"><i
class="fa fa-eye"></i></button>
</x-slot>
</x-forms.input-group>
</div>
<div class="forgot_pswd mb-3">
#lang('app.forgotPassword')
</div>
<div class="form-group text-left">
<input id="checkbox-signup" type="checkbox" name="remember">
<label for="checkbox-signup">#lang('app.rememberMe')</label>
</div>
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v2_status == 'active')
<div class="form-group" id="captcha_container"></div>
#endif
#if ($errors->has('g-recaptcha-response'))
<div class="help-block with-errors">{{ $errors->first('g-recaptcha-response') }}
</div>
#endif
<button type="submit" id="submit-login"
class="btn-primary f-w-500 rounded w-100 height-50 f-18">
#lang('app.login') <i class="fa fa-arrow-right pl-1"></i>
</button>
#if ($setting->allow_client_signup)
<a href="{{ route('register') }}"
class="btn-secondary f-w-500 rounded w-100 height-50 f-15 mt-3">
#lang('app.signUpAsClient')
</a>
#endif
</div>
</div>
</div>
</div>
</div>
</section>
</form>
<x-slot name="scripts">
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v2_status == 'active')
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async
defer></script>
<script>
var gcv3;
var onloadCallback = function () {
// Renders the HTML element with id 'captcha_container' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'gcv3'.
gcv3 = grecaptcha.render('captcha_container', {
'sitekey': '{{ $setting->google_recaptcha_v2_site_key }}',
'theme': 'light',
'callback': function (response) {
if (response) {
$('#g_recaptcha').val(response);
}
},
});
};
</script>
#endif
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v3_status == 'active')
<script
src="https://www.google.com/recaptcha/api.js?render={{ $setting->google_recaptcha_v3_site_key }}"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('{{ $setting->google_recaptcha_v3_site_key }}').then(function (token) {
// Add your logic to submit to your backend server here.
$('#g_recaptcha').val(token);
});
});
</script>
#endif
<script>
$(document).ready(function () {
$('#submit-next').click(function () {
const url = "{{ route('check_email') }}";
$.easyAjax({
url: url,
container: '#login-form',
disableButton: true,
buttonSelector: "#submit-next",
type: "POST",
data: $('#login-form').serialize(),
success: function (response) {
if (response.status === 'success') {
$('#submit-next').remove();
$('#password-section').removeClass('d-none');
$("#password").focus();
}
}
})
});
$('#submit-login').click(function () {
const url = "{{ route('login') }}";
$.easyAjax({
url: url,
container: '.login_box',
disableButton: true,
buttonSelector: "#submit-login",
type: "POST",
blockUI: true,
data: $('#login-form').serialize(),
success: function (response) {
if (response.two_factor == false) {
window.location.href = "{{ session()->has('url.intended') ? session()->get('url.intended') : route('dashboard') }}";
} else if (response.two_factor == true) {
window.location.href = "{{ url('two-factor-challenge') }}";
}
}
})
});
#if (session('message'))
Swal.fire({
icon: 'error',
text: '{{ session('message') }}',
showConfirmButton: true,
customClass: {
confirmButton: 'btn btn-primary',
},
showClass: {
popup: 'swal2-noanimation',
backdrop: 'swal2-noanimation'
},
})
#endif
});
</script>
</x-slot>
</x-auth> ```
Custom filter datatables serverside not working in codeigniter 3 but no error, with join table database ... anyone can help me ? thx
MODEL
Rekap_m.php
var $column_order = array(null, 'bidang', 'skpd', 'kode', 'masalah', 'nomor', 'rincian_masalah', 'tahun_cipta', 'rak', 'dos', 'retensi', 'ket');
var $column_search = array('bidang', 'kode', 'nomor', 'skpd');
var $order = array('id_arsip' => 'asc');
private function _get_datatables_query()
{
if ($this->input->post('bidang')) {
$this->db->where('id_bidang', $this->input->post('bidang'));
}
if ($this->input->post('skpd')) {
$this->db->like('skpd', $this->input->post('skpd'));
}
if ($this->input->post('kode')) {
$this->db->like('kode', $this->input->post('kode'));
}
if ($this->input->post('masalah')) {
$this->db->like('masalah', $this->input->post('masalah'));
}
$this->db->select('*');
$this->db->from('arsip');
$this->db->join('bidang', 'bidang.id_bidang = arsip.id_bidang');
$i = 0;
foreach ($this->column_search as $item) {
if (#$_POST['search']['value']) {
if ($i === 0) {
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if (count($this->column_search) - 1 == $i)
$this->db->group_end();
}
$i++;
}
if (isset($_POST['order'])) {
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if (isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if (#$_POST['length'] != -1)
$this->db->limit(#$_POST['length'], #$_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
function count_all()
{
$this->db->from('arsip');
return $this->db->count_all_results();
}
public function get_list_bidangs()
{
$this->db->select('*');
$this->db->from('arsip');
$this->db->join('bidang', 'bidang.id_bidang = arsip.id_bidang');
$this->db->order_by('id_arsip', 'asc');
$query = $this->db->get();
$result = $query->result();
$bidangs = array();
foreach ($result as $row) {
$bidangs[] = $row->bidang;
}
return $bidangs;
}
CONTROLLER
Rekap.php
function __construct()
{
parent::__construct();
check_not_login();
$this->load->model('rekap_m');
}
public function index()
{
$bidangs = $this->rekap_m->get_list_bidangs();
$opt = array('' => 'Semua Bidang');
foreach ($bidangs as $id_bidang) {
$opt[$id_bidang] = $id_bidang;
}
$data['form_bidang'] = form_dropdown('', $opt, '', 'id="bidang" class="form-control"');
$this->template->load('template', 'rekap/rekap_data', $data);
}
function ajax_list()
{
$list = $this->rekap_m->get_datatables();
$data = array();
$no = #$_POST['start'];
foreach ($list as $arsip) {
$no++;
$row = array();
$row[] = $no . ".";
$row[] = $arsip->bidang;
$row[] = $arsip->skpd;
$row[] = $arsip->kode;
$row[] = $arsip->masalah;
$row[] = $arsip->nomor;
$row[] = $arsip->rincian_masalah;
$row[] = $arsip->tahun_cipta;
$row[] = $arsip->rak;
$row[] = $arsip->dos;
$row[] = $arsip->retensi;
$row[] = $arsip->ket;
// add html for action
$data[] = $row;
}
$output = array(
"draw" => #$_POST['draw'],
"recordsTotal" => $this->rekap_m->count_all(),
"recordsFiltered" => $this->rekap_m->count_filtered(),
"data" => $data,
);
// output to json format
echo json_encode($output);
}
public function rekap()
{
$this->load->model('bidang_m');
$data['bidang'] = $this->bidang_m->get()->result();
$this->template->load('template', 'rekap/rekap_data', $data);
}
public function del($id)
{
$this->arsip_m->del($id);
if ($this->db->affected_rows() > 0) {
echo "<script>alert('Data Berhasil dihapus'); </script>";
}
echo "<script>window.location='" . site_url('rekap') . "'; </script>";
}
VIEW
rekap_data.php
<div class="row">
<!-- DataTable with Hover -->
<div class="col-lg-12">
<div class="card mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<div class="col-md-4 offset-md-4">
<form id="form-filter">
<div class="form-horizontal">
<div class="form-group">
<div class="col-sm-9">
<div class="form-group">
<label for="bidang" class="col-sm-4 control-label">Bidang</label>
<?php echo $form_bidang; ?>
</div>
<div class="form-group">
<label for="skpd" class="col-sm-4 control-label">SKPD</label>
<input type="text" class="form-control" id="skpd">
</div>
<div class="form-group">
<label for="kode" class="col-sm-4 control-label">Kode</label>
<input type="text" class="form-control" id="kode">
</div>
<div class="form-group">
<label for="masalah" class="col-sm-4 control-label">Masalah</label>
<textarea class="form-control" id="masalah"></textarea>
</div>
<div class="form-group">
<button type="button" id="btn-filter" class="btn btn-primary">Filter</button>
<button type="button" id="btn-reset" class="btn btn-default">Reset</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="table-responsive p-3">
<table class="table align-items-center table-flush table-hover" id="dataTableHover">
<thead class="thead-light">
<tr>
<th>#</th>
<th>Bidang</th>
<th>SKPD</th>
<th>Kode</th>
<th>Masalah</th>
<th>Nomor</th>
<th>Rincian</th>
<th>Tahun</th>
<th>Rak</th>
<th>Dos</th>
<th>Retensi</th>
<th>Keterangan</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var table;
$(document).ready(function() {
table = $('#dataTableHover').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo site_url('rekap/ajax_list') ?>",
"type": "POST",
"data": function(data) {
data.id_bidang = $('#bidang').val();
data.skpd = $('#skpd').val();
data.kode = $('#kode').val();
data.masalah = $('#masalah').val();
}
},
"columnDefs": [{
"targets": [0],
"orderable": false,
}, ],
});
$('#btn-filter').click(function() {
table.ajax.reload();
});
$('#btn-reset').click(function() {
$('#form-filter')[0].reset();
table.ajax.reload();
});
});
</script>
the code above is the code that I use, there is no error but not working ... is there something wrong with my code, I ask for advice on what corrections if there are errors
Goodtime
I write this code but when i send for database only submit one query "sad" !
çi use
$request->has('happy') or ... no working
Can anyone help me?
for sample
**$request->has('happy') ** submit 'happy' or **$request->has('love') ** submit 'love'
I'm tired of searching
thanks to stackoverflow and members
<form method="post">
{{csrf_field()}}
<button type="submit" value="happy" id="happy" class="border-0 btn-submit">
<img src="/assets/images/reactions/happy.png" />
</button>
<button type="submit" value="angry" id="angry" class="border-0 btn-submit">
<img src="/assets/images/reactions/angry.png" />
</button>
<button type="submit" value="ill" id="ill" class="border-0 btn-submit">
<img src="/assets/images/reactions/ill.png" />
</button>
<button type="submit" value="love" id="love" class="border-0 btn-submit">
<img src="/assets/images/reactions/in-love.png" />
</button>
<button type="submit" value="quiet" id="quiet" class="border-0 btn-submit">
<img src="/assets/images/reactions/quiet.png" />
</button>
<button type="submit" value="sad" id="sad" class="border-0 btn-submit">
<img src="/assets/images/reactions/sad.png" />
</button>
<!-- <input type="text" name="studentName" id="studentName" class="form-control" placeholder="please type in your name"> -->
<input type="hidden" value="{{$article->id}}" id="post_id">
<input type="hidden" name="_token" value="{{csrf_token()}}">
</form>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit").click(function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var sad = $("#sad").val();
var quiet = $("#quiet").val();
var love = $("#love").val();
var ill = $("#ill").val();
var angry = $("#angry").val();
var happy = $("#happy").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: {
post_id: post_id,
sad: sad,
quiet: quiet,
love: love,
ill: ill,
angry: angry,
happy: happy
},
success: function(data) {
alert(data.success);
}
});
});
</script>
</div>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Reaction;
use Illuminate\Support\Facades\Auth;
class AjaxController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequest()
{
return view('ajaxRequest');
}
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequestPost(Request $request, Reaction $reaction)
{
$input = $request->all();
\Log::info($input);
if ($request->ajax()) {
if (!Auth::user()) { // Check is user logged in
$must_login = "you must login";
return response()->json(['success' => $must_login]);
} else {
$date = date('Y-m-d');
$user_id = Auth::user()->id;
$output = "Your reaction Submited";
$post_id = $request->input('post_id');
// Checker
$checker = Reaction::select('*')->where([
['post_id', '=', $post_id],
['user_id', '=', $user_id],
['date', '=', $date]
])->first();
if ($checker == null) {
if ($request->has('sad') == true) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'sad',
'date' => $date,
]);
} elseif ($request->has('love')) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'love',
'date' => $date,
]);
} else {
echo "fuck";
}
return response()->json(['success' => $output]);
} else {
return response()->json(['success' => 'You Befor Submited Your Rection']);
}
}
}
}
}
This should work:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("form").on('submit', function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var reaction = $(".btn-submit").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: { post_id, reaction },
success: function(data) {
alert(data);
}
});
});
public function ajaxRequestPost(Request $request)
{
$data = $request->all();
return response()->json($data);
}
This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing
I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.