AJAX - Complex user activation for login - ajax

Now this may sound complicated but I have a page called activation.php where after the user has registered using my reg.php page, they get sent an email with their activation link - activation.php then a get method of k to make activation.php?k=activation-code-here
I made it so it returns the status of the activation, e.g - success of error.
On my reg.php page, I want to make it so it uses ajax to open a sweetAlert popup saying 'Activation Success'. It will get the popup depending on if the users 'activ_status' changed from 0 to 1 in the database when they access the activation.php page with a correct activation key.
Here is my code :
Activation.php
<?php
include('inc/conf/db_.php');
$result = '';
if(empty($_GET['k']) || (!$_GET['k']))
{
header('Location: login.php');
exit();
$result = 'Hacker Tried Accessing Auth Page';
}
$key = mysqli_real_escape_string($con,$_GET["k"]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if (!empty($key))
{
$query = "SELECT * FROM users WHERE activ_key = '$key'";
$result = mysqli_query($con,$query) or die('error');
if (mysqli_num_rows($result))
{
$row = mysqli_fetch_array($result);
if ($row['activ_status']!='1')
{
$query = "update users set activ_status='1' where activ_key='$key'";
$result = mysqli_query($con,$query) or die('error');
$result = 'Successfuly Activated, Return To Your Other Page.';
}
else
{
$result = "Account Already Activated";
}
}
else
{
$result = 'Invalid Access Token';
}
}
else
{
$result = 'Error';
}
?>
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<br>
<center><div id="result"></center>
<br>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Activation Status</b></h4>
<br>
<center><img src="assets/images/loading.gif"></center>
<br>
<center><div class="alert alert-info"><button type="button" class="close"></button><?php echo $result; ?></div></center>
<?php return $result; ?>
</body>
</html>
My reg.php page
<?php
include('inc/conf/db_.php');
if (session_status() == PHP_SESSION_ACTIVE) {
session_start();
}
if(isset($_SESSION['user_i']) || isset($_SESSION['login'])) {
header('Location: index.php');
exit();
}
else if (session_status() == PHP_SESSION_NONE) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="assets/plugins/bootstrap-sweetalert/sweet-alert.css" rel="stylesheet" type="text/css">
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<center><img src="assets/images/loading.gif" id="loading-image" style="display:none"/></center>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Sign Up</b></h4>
<form id="registered_form" class="form-horizontal m-t-20">
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="email" type="email" required="" placeholder="Email"></div>
<span class="fa fa-envelope form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="username" type="text" required="" placeholder="Username"></div>
<span class="fa fa-user form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="password" type="password" required="" placeholder="Password"></div>
<span class="fa fa-lock form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LeGFxYUAAAAAOqjyovTS3H0D1HS4IBgoHMvG4y_"></div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="checkbox checkbox-primary" style="text-align: center;"> <input type="checkbox" name="checkbox" value="agree"> <label for="checkbox-signup"> I accept Terms and Conditions </label></div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12"> <button class="btn btn-primary w-md waves-effect waves-light" type="submit" id="reg_button" style="width: 100%;" >Register</button></div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12 text-center"> Already have an account?</div>
</div>
</form>
</div>
</div>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.validate.js"></script>
<script src="assets/plugins/bootstrap-sweetalert/sweet-alert.min.js"></script>
<script>
$(document).ready(function()
{
jQuery.validator.addMethod("noSpace", function(value, element)
{
return value.indexOf(" ") < 0 && value != "";
}, "Spaces are not allowed");
$("#registered_form").submit(function()
{
if ($("#registered_form").valid())
{
$('#loading-image').show();
var data1 = $('#registered_form').serialize();
$.ajax({
type: "POST",
url: "inc/pgs/register.php",
data: data1,
success: function(msg)
{
$('#loading-image').hide();
console.log(msg);
if(msg == '')
{
swal({
title: "Registration Success!",
text: "Your registration was successful! Check your email and click on your activation link to be able to access your account. NOTE: Keep this page open",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
else
{
swal("Registration Error!", msg, "error");
}
}
});
$.ajax({
type: "GET",
url: "activation.php",
data: data1,
success: function(msg)
{
if(msg == 'Successfuly Activated, Return To Your Other Page.')
{
swal({
title: "Activation Success",
text: "You can now login!",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
}
});
}
return false;
});
});
</script>
</body>
</html>
<?php } ?>
I found a piece of code that might help me. It doesn't seem to be loading the modal up though:
$.ajax({
url: 'activation.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
if(data == 'Successfuly Activated, Return To Your Other Page.')
{
swal("Activation Completed!", "You can now login using the link at the bottom of the page - Already have an account?", "success")
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
ajaxCall();
},
});

Please clearly explain the problem you are having that is preventing the code from working as you intend.
If my interpretation is correct, you want to update the registration page that user keeps open while activating in another window, and then reflect the change on the registration page using AJAX. In fact, in this case you want to send data from the server to your client (you want something to change when a change happens on the server in the database). In this case, a simple solution is to repeatedly request the status (for instance every 2 seconds) using setTimeout. Other solutions exist but are probably overkill, such as long polling or web sockets.

Related

Laravel 8 Dynamic Dependent Input

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

Laravel Ajax Add To Cart Not working 500 internal error

I have code I am working on. I will list the page, the route, and the controller code. When I inspect and click on the add to cart button I get 500 internal server error and I cannot figure out what I did. It should be giving a message checking to see if the item is already in the cart and if not send a message saying item is in the cart but I can't get past the 500 internal server error.
Page
#extends('layouts.frontend.frontend')
#section('title')
Distinctly Mine - {{$products->name}}
#endsection
#section('content')
<div class="py-3 mb-4 shadow-sm babyblue border-top">
<div class="container">
<h6 class="mb-0">Collections / {{$products->category->name}} / {{$products->name}}</h6>
</div>
</div>
<div class="container">
<div class="card-shadow shadow-sm product_data">
<div class="card-body">
<div class="row">
<div class="col-md-4 border-right">
<div class="img-hover-zoom img-hover-zoom--xyz card-img-top">
<img src="{{ asset('backend/uploads/products/'.$products->image) }}" class="w-100 h-100" alt="{{$products->name}}">
</div>
</div>
<div class="col-md-8">
<h2 class="mb-0">{{ $products->name}}</h2>
<hr>
<label for="" class="me-3">Price: ${{$products->original_price}}</label>
<p class="mt-3">{!! $products->small_description !!}</p>
<hr>
#if($products->qty > 0)
<label for="" class="badge bg-success text-dark fw-bold">In Stock</label>
#else
<label for="" class="badge bg-danger text dark fw-bold">Out of Stock</label>
#endif
<div class="row mt-2">
<div class="col-md-2">
<input type="hidden" value="{{$products->id}}" class="prod_id">
<label for="Quantity">Quantity</label>
<div class="input-group text-center mb-3" style="width:130px">
<button type="button" class="input-group-text decrement-btn">-</button>
<input type="text" name="quantity" value="1" class="form-control qty-input" />
<button type="button" class="input-group-text increment-btn">+</button>
</div>
</div>
<div class="col-md-10">
<br />
<button type="button" class="btn btn-warning text-dark fw-bold ms-3 float-start"><i class=" me-1 fa fa-heart text-danger me-1"></i>Add To Wishlist</button>
<button type="button" class="btn btn-success ms-3 float-start text-dark fw-bold addToCartBtn"><i class="me-1 fa fa-shopping-cart text-dark me-1"></i>Add to Cart</button>
</div>
<hr>
<h2>Description</h2>
{{$products->description}}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function (){
$('.addToCartBtn').click(function (e){
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
dataType: "dataType",
success: function (response){
alert(response.status);
}
});
});
$('.increment-btn').click(function (e){
e.preventDefault();
var inc_value = $('.qty-input').val();
var value = parseInt(inc_value,10);
value = isNaN(value) ? 0 :value;
if(value < 10)
{
value++;
$('.qty-input').val(value);
}
});
$('.decrement-btn').click(function (e){
e.preventDefault();
var dec_value = $('.qty-input').val();
var value = parseInt(dec_value,10);
value = isNaN(value) ? 0 :value;
if(value > 1)
{
value--;
$('.qty-input').val(value);
}
});
});
</script>
#endsection
Route
Route::middleware(['auth'])->group(function (){
Route::post('/add-to-cart',[CartController::class,'addProduct']);
});
Controller
<?php
namespace App\Http\Controllers\Frontend;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class CartController extends Controller
{
public function addProduct(Request $request)
{
$product_id = $request->input('product_id');
$product_qty = $request->input('product_qty');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->name." Already Added to cart"]);
}else{
$cartItem = new Cart();
$cartItem->prod_id = $product_id;
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status'=>$prod_check->name." Added to cart"]);
}
}
}
else{
return response()->json(['status'=> "Login To Continue"]);
}
}
}

Is there is a way to keep my modal open in Laravel after submit and save the values to db?

I am uploading a file in Laravel 8 with having one bootstrap modal which works dynamically . everything is working fine but I want to improve my output more:
1) Update one of my forms through a modal without refreshing the page?
2) keep the modal open if the validation fails and print the errors to modal instead of my redirect page?
I will appreciate your time helping me.
my form for updating the file
<form action="{{ route('storefile' , $requisition->id) }}" method="POST"
enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col-sm-12">
<label for="title"> Account Status: </label>
<select class="form-control" name="acc_status">
<option value="0" {{ $requisition->acc_status == 0 ? 'selected' : '' }}> Inactive
</option>
<option value="1" {{ $requisition->acc_status == 1 ? 'selected' : '' }}> Active
</option>
</select>
</div>
<div class="col-sm-12 pt-4">
<label for="title"> Account document File: </label>
<div>
#if (!empty($requisition->acc_document))
<label class="badge-success">
{{ $requisition->acc_document }}
</label>
#else
<label class="badge-danger">
Nothing uploaded </label>
#endif
</div>
<input type="file" name="acc_document" class="form-control" id="acc_document" />
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-6 text-left">
<input type="submit" value="Upload document" class="btn btn-primary">
</div>
</div>
</div>
</div>
</form>
my controller and route
public function uploadFile($id) {
$requisition = Requisition::find($id);
return view('requisition.createFile' , compact('requisition'));
}
public function storeFile(Request $request , $id) {
$request->validate([
'acc_status' => 'required',
'acc_document' => 'required|mimes:doc,docx,pdf,txt,zip|max:2000',
]);
$requisition = Requisition::find($id);
$requisition->acc_status = $request->get('acc_status');
$FileName = uniqid() .$request->file('acc_document')->getClientOriginalName();
$path = $request->file('acc_document')->storeAs('uploads', $FileName , 'public');
$requisition->acc_document = '/storage/' . $path;
}
$requisition->save();
//$requisition->update($request->all());
return back()
->with('success', 'Your file has been uploaded successfully.');
}
Route::get('upload/{id}', [RequisitionController::class, 'uploadFile'])->name('upload');
Route::put('requisition/{id}/files', [RequisitionController::class, 'storeFile'])->name('storefile');
and last part my modal and ajax in my index page to upload the file and popup will open
<div class="col-md-6">
<a style="display:inline-block; text-decoration:none; margin-right:10px;"
class="text-secondary" data-toggle="modal" id="mediumButton"
data-target="#mediumModal" title="upload"
data-attr="{{ route('upload' , $requisition->id) }}">
<i class="fas fa-upload"></i>
</a>
</div>
<script>
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
// #if (count($errors) > 0) #endif
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
$("#date-picker").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd'
});
} ,
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
});
});
</script>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-body" id="mediumBody">
<form id="modal-form" method="get">
<div>
<!-- the result of displayed apply here -->
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
what I want to implement looks like enter image description here
There are several ways to do this kind of thing. One way to do it, is to do something like this:
Html:
<div class="modal" id="the-modal">
<form action="{{ $theAction }}" method="POST" id="the-form">
<input type="text" name="input-name" id="the-input">
<button type="submit">
</form>
<p id="the-text"></p>
</div>
In your Controller you will return an error or an 200 response, if everything is ok.
public function theAction(Request $request , $id) {
//Do stuff
if (!$error) {
return response("OK"); //This will return a 200 response
} else {
return response("An error happened", 500); //This will return a 500 error
}
}
Then, in your JS, you'll intercept form submission and then, you're going to be able to separate errors from ok messages:
<script>
$("#the-form").on('submit', function(event) {
event.preventDefault();
let theInput = $("#the-input");
$.ajax({
url: theUrl,
data: {
the-input: theInput
}
// 200 response
success: function(result) {
$("#the-text").empty();
$("#the-text").append(result.repsonse);
} ,
error: function(jqXHR, testStatus, error) {
$("#the-text").empty();
$("#the-text").append(error.response);
}
});
});
</script>
If you want to do all this stuff inside a modal, the concept is just the same: You intercept form submission, send to controller, return separate responses for errors and 200 responses, and then update manually the inputs/texts.
I did't test the code, but the concept should work.

AJAX code not working on iPad only

We've created an event check-in page where nonprofits can add volunteers at an event. The page is working great on all platforms besides iPad. (iPhone Safari is working.)
On iPad, clicking id=add-volunteer button has no effect. Desired behavior is that clicking the button adds the volunteer name to the list of registered volunteers and saves the user info on the backend. (Other backend tasks such as sending an invite email should occur on the backend as well.)
HTML
<form id="form-add" method="post">
<input type="hidden" name="csrfmiddlewaretoken">
<div class="row one-margin-bottom center">
<div id="new-volunteers" class="small-12 medium-8 small-centered columns">
<h6 class="left">Add volunteer</h6>
<div class="row">
<div class="input-right small-6 columns">
<input class="center" id="new-firstname" name="user_firstname" placeholder="First name" type="text" required="">
</div>
<div class="input-right small-6 columns">
<input class="center" id="new-lastname" name="user_lastname" placeholder="Last name" type="text" required="">
</div>
<div class="input-right small-12 medium-12 columns">
<input class="lead center" id="new-email" name="user_email" placeholder="Email address" type="email" required="">
</div>
</div>
<div class="no-margin-top qtr-margin-bottom checkbox center">
<input type="checkbox" name="invite-optin" id="invite-optin" class="custom-checkbox" checked="">
<label for="invite-optin">Invite volunteer to openCurrents</label>
</div>
<a id="add-volunteer" class="half-margin-bottom button round small secondary">
Add volunteer
</a>
</div>
</div>
</form>
<form id="form-checkin" method="post">
<input type="hidden" name="csrfmiddlewaretoken">
<div class="row">
<div class="small-12 medium-8 small-centered columns">
<h6 class="left half-margin-bottom">Registered volunteers</h6>
<div class="row">
<div class="left small-8 columns">
<p class="small-text half-margin-top half-margin-bottom"><strong>Name / Email</strong></p>
</div>
<div class="right small-4 columns">
<p class="small-text half-margin-top half-margin-bottom"><strong>Check in</strong></p>
</div>
</div>
</div>
</div>
<div class="row">
<div id="registered-volunteers" class="small-12 medium-8 small-centered columns">
</div>
</div>
</form>
<div class="row">
<a href="/org-admin/" class="button round small secondary">
Back to org home
</a>
</div>
JS
let onCheckClick = function(event) {
let name = event.target.name;
let elem = $(`#${name}`);
let userid = elem.val();
let isChecked = elem.prop("checked");
$.ajax({
url: "{% url 'openCurrents:event_checkin' event_id %}",
type: 'POST',
data : {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[1].value,
userid: userid,
checkin: isChecked
},
dataType : "json",
context: document.body
}).done(function( data ){
// console.log('checkin request:');
// console.log(data);
if (isChecked) {
let dt = new Date();
$(`#vol-status-${userid}`).text(`${dt.toLocaleTimeString()}`);
$(`#vol-status-${userid}`).show();
}
else {
$(`#vol-status-${userid}`).text(`${data.responseText} min.`);
}
}).fail(function (data) {
// console.log('checkin error:')
// console.log(data);
elem.prop('checked', false);
$('#live-dashboard-error').slideDown();
});;
};
$(document).ready(function(){
// bind all existing checkbox to checkin
$("input[name^='vol-checkin']").click(onCheckClick);
$("#add-volunteer").click(function(event){
if ($(this).attr('disabled') === 'disabled') {
$('#live-dashboard-checkin-disabled').slideDown();
return;
}
if ($('#new-firstname').val() == '' || $('#new-lastname').val() == '' || $('#new-email').val() == '') {
$('#vol-error').slideDown();
} else if ( !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($('#new-email').val() )) ) {
$('#vol-error').slideUp();
$('#email-error').slideDown();
} else {
$('#vol-error').slideUp();
$('#email-error').slideUp();
let new_firstname = $('#new-firstname').val();
let new_lastname = $('#new-lastname').val();
let new_email = $('#new-email').val();
let invite_optin = $('#invite-optin').prop('checked');
let process_signup_url;
let form_data = {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
user_firstname: new_firstname,
user_lastname: new_lastname,
user_email: new_email.toLowerCase()
};
if (invite_optin) {
process_signup_url = "{% url 'openCurrents:process_signup' endpoint=True verify_email=True %}"
form_data['org_admin_id'] = {{ user.id }};
}
else {
process_signup_url = "{% url 'openCurrents:process_signup' endpoint=True verify_email=False %}"
}
form_data['signup_status'] = 'vol'
$.ajax({
url: process_signup_url,
type: 'POST',
data: form_data,
dataType : "json",
}).done(function( data ) {
// console.log('signup response:')
// console.log(data);
let userid = data;
let form_data = {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
userid: userid
}
$.ajax({
url: "{% url 'openCurrents:event_register_live' eventid=event.id %}",
type: 'POST',
data: form_data,
dataType : "json",
}).done(function( data ) {
//console.log('register_live response:')
//console.log(data);
// hide any error messages present
$('#vol-exist').slideUp();
$('#live-dashboard-error-register').slideUp();
$('#live-dashboard-error').slideUp();
$('#vol-error').slideUp();
$('#email-error').slideUp();
$('#live-dashboard-not-in-progress').slideUp();
if (data.event_status >= 0) {
$('#registered-volunteers').prepend(`
<div class="row"> \
<div class="left small-9 columns"> \
<p class="half-margin-top"> \
${new_firstname} \
${new_lastname} \
</p> \
</div> \
<div class="right small-3 columns"> \
<input {% if checkin_disabled %}disabled{% endif %} type="checkbox" id="vol-checkin-${userid}" name="vol-checkin-${userid}" value="${userid}" class="hidden checkin-checkbox"/> \
<label class="checkin-checkbox-icon" for="vol-checkin-${userid}"> \
<i class="fa fa-lg fa-check-circle"></i> \
</label> \
</div> \
</div> \
`)
// clear form inputs
$('#new-firstname').val('');
$('#new-lastname').val('');
$('#new-email').val('');
$('#invite-optin').attr("checked", true);
// bind new checkbox to checkin
$(`input[name='vol-checkin-${userid}']`).click(onCheckClick);
if (data.event_status == 1) {
$(`input[name='vol-checkin-${userid}']`).trigger('click')
} else {
$('#live-dashboard-not-in-progress').slideDown();
}
}
else {
$('#new-firstname').val('');
$('#new-lastname').val('');
$('#new-email').val('');
$('#invite-optin').attr("checked", true);
$('#vol-exist').slideDown();
}
}).fail( function (data) {
// console.log('register_live error:')
// console.log(data);
$('#live-dashboard-error').slideDown();
});
}).fail(function (data) {
// console.log('signup error:')
// console.log(data);
$('#live-dashboard-error').slideDown();
});
}
});

Codeigniter form_open_multipart showing 403 Forbidden (CSRF)

I am trying to post data though ajax post but somehow unable to post . am getting 403 forbidden. Fortunately my other ajax posts are submitting properly as they are getting right re-generated token. But in form_open_multipart it's not working.
CI config
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'my_token';
$config['csrf_cookie_name'] = 'my_cookie';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
form_open is working well, but in the case of multi part it's not working well !!!!
my HTML
<?php $parameter = array('id' => 'frm_id', 'class' => 'form-horizontal'); echo form_open_multipart('controller/save',$parameter) ;?>
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-6">
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" id="catId" class="form-control " placeholder="Type Something..." name='name' />
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Description</label>
<div class="col-md-6">
<div>
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Image 1</label>
<div class="col-md-6">
<div>
<input type="file" name="thumb_image">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Image 2</label>
<div class="col-md-6">
<div>
<input type="file" name="banner_image">
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn btn-flat green">Submit</button>
<button type="button" class="btn btn-flat grey-salsa">Cancel</button>
</div>
</div>
</div>
<?php echo form_close() ;?>
My JS
<script type="text/javascript">
var frmSave = $('#frm_id');
frmSave.on('submit', function(event){
event.preventDefault();
$form=$(this);
var fd = new FormData($('#frm_id')[0]);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
dataType: 'json',
data: fd,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data)
}
})
});
</script>
Still I am getting this message
An Error Was Encountered. The action you have requested is not
allowed.
var vl = "; " + document.cookie;
var pr = vl.split("; csrf_cookie=");
var obj; if (pr.length == 2) { obj = pr.pop().split(";").shift(); }
using this variable in the ajax body section like
data : '<?php echo $this->security->get_csrf_token_name(); ?>': obj
Now it's working fine.

Resources