Codeigniter form_open_multipart showing 403 Forbidden (CSRF) - codeigniter

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.

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource in my application

I have been bulding small system using api my api url is: 'https://www.domstol.no/api/episerver/v3/beramming' and my website url is: https://konkurs.app/ and I am using bellow code to get access of data.
My Form:
<form id="mainForm" action="https://www.domstol.no/api/episerver/v3/beramming">
<div class="row align-middle align-items-center">
<div class="col-lg-4 col-md-4 mb-1">
<fieldset>
<div class="input-group">
<label class="d-block w-100"> Start From
<input type="date" class="form-control" name="From"></label>
</div>
</fieldset>
</div>
<div class="col-lg-4 col-md-4 mb-1">
<fieldset>
<div class="input-group">
<label class="d-block w-100"> Start To
<input type="date" class="form-control" name="To"></label>
</div>
</fieldset>
</div>
<div class="col-lg-4 mb-1">
<fieldset>
<div class="input-group">
<label class="d-block w-100"> Court
<input type="text" class="form-control" name="Court"></label>
</div>
</fieldset>
</div>
<div class="col-lg-4 mb-1">
<fieldset>
<div class="input-group">
<label class="d-block w-100"> Case Number
<input type="text" class="form-control" name="CaseNumber"></label>
</div>
</fieldset>
</div>
<div class="col-lg-4 mb-1">
<fieldset>
<div class="input-group">
<label class="d-block w-100"> Case About
<input type="text" class="form-control" name="CaseAbout"></label>
</div>
</fieldset>
</div>
<div class="col-lg-4 mt-1 mb-1">
<fieldset>
<div class="input-group">
<input type="submit" class="btn btn-primary btn-block" value="Filter Domstol">
</div>
</fieldset>
</div>
</div>
</form>
And my ajax function is here:
$("#mainForm").submit(function( event ) {
event.preventDefault();
event.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
var From = $("input[name='From']",this).val();
var To = $("input[name='To']",this).val();
var Court = $("input[name='Court']",this).val();
var CaseNumber = $("input[name='CaseNumber']",this).val();
var CaseAbout = $("input[name='CaseAbout']",this).val();
$.ajax({
type: 'POST',
url: url,
contentType: "application/json;charset=utf-8",
dataType:"json",
beforeSend: setHeader,
data: JSON.stringify({
"To":"2022-10-03",
"From":"2022-10-03",
"Court":"",
"CaseAbout":"konkurs",
"CaseNumber":""
}),
success: data => {
console.log(data)
},
error: (xhr, textStatus, error) => {
console.log(error)
},
});
function setHeader(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,POST");
xhr.setRequestHeader("Access-Control-Allow-Headers", "Content-type, X-Auth-Token, Origin, Authorization");
}
});
Bye the way i am using laravel 8, and yes dont ask me to install cors middleware i have already tried with it. If i try with postman i got result but from my application i got: "No 'Access-Control-Allow-Origin' header is present on the requested resource in my application"

Delete form data after data is displayed or submission of the form

I use the same form to view details of a record that is in the database and make form submission. But an error occurs when I view a log and then register other data. In this case the new registration is registered three times in the database. And the reason this happens is that the form data is cached when I view or register a record. All the solutions I searched on the internet didn't work for me.
This is my form
<div id="form" style="display: none;" class="col-md-12">
<div class="row">
<h5 class="title">Add</h5>
<div class="float-right" style="margin-left: 80%">
<button class="btn btn-secondary" id="close_form">Close</button>
</div>
</div>
<form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fas fa-minus"></i></button>
</div>
</div>
<div class="card-body">
<fieldset disabled>
<div class="row">
<div class="form-group col-md-3">
<label for="inputCity">Código do documento:</label>
<input type="text" class="form-control" id="id_docs" name="id_docs">
</div>
<div class="form-group col-md-8">
<label for="inputCity">Status</label>
<input type="text" class="form-control" id="status" name="status">
</div>
</div>
</fieldset>
<div class="form-group">
<label>Assunto</label>
<textarea class="form-control" id="assunto" name="assunto" required></textarea>
</div>
<div class="form-group">
<label for="inputAddress2">Proveniencia</label>
<input type="text" class="form-control" id="prov" placeholder="Proveniencia" name="prov" required>
</div>
<div class="form-group col-md-4">
<label for="inputCity">Correspondência</label>
<input type="date" class="form-control" id="corre" name="corre">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" id="img_cad" style="margin-left: 10px;">
<span class="control-label col-md-4"><b class="span_doc">File:</b></span><br><br>
<input type="file" id="image" aria-describedby="inputGroupFileAddon01" name="image">
<span id="store_image"></span>
</div><br>
<br>
<input type="hidden" name="action" id="action" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="hidden" name="hidden_id_docs" id="hidden_id_docs" />
<button type="submit" name="action_button" id="action_button" class="btn btn-warning">Save</button>
</div>
</div>
</form>
</div>
This is the function to view the details of a record on the form
$(document).on('click', '.edit', function(){
var id_scr = $(this).attr('id_scr');
$('#div_table').hide();
$.ajax({
url:"/scr/"+id_scr+"/edit",
cache: false,
dataType:"json",
success:function(html){
$('#action_button').text("Edit Data");
$('#assunto').val(html.data.assunto);
$('#prov').val(html.data.prov);
$('#corre').val(html.data.corre);
$('#status').val(html.data.descricao);
$('#cod_cadastro').val(html.data.cod_cadastro);
$('#hidden_id').val(html.data.id);
$('#hidden_id_docs').val(html.data.id_docs);
$('#id_docs').val(html.data.id_docs);
$('.title').text("Details...");
$('.span_doc').text("Alter Doc");
$('#action').val("Edit");
$('#form').show();
}
})
});
To clear the form data after viewing a record, I created thisTo clear the form data after viewing a record, I created this function:
$(document).on('click', '#close_form', function(){
$('#sample_form')[0].reset();
$('#form').hide();
$('#div_table').show();
});
And finally, this is the function for registering a new record
$('#sample_form').on('submit', function(event){
event.preventDefault();
$('.progress').show();
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('scr.store') }}",
method:"POST",
data: new FormData(this),
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
alert('SUCCESSFULLY SAVED');
$('#sample_form')[0].reset();
$('#formModal').modal('hide');
location.reload(); //**This is the only way I found to clear the form after submitting the data**
}
})
}
})
You could try this method :
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
Or you could just call this method in your submit method

Cannot save value using ajax in laravel

I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());

Values from fields does not pass throug ajax to php

I have a small contact form that almost works as i should. The file is uploaded and sent correctly, but all the other values from the input fields in the form does not pass throug the script. Does anyone see what I am missing?
Form:
<form id="contactForm" name="sentMessage" novalidate="" method="post" enctype="multipart/form-data">
<input type="hidden" name="path" id="path" value="projectpage">
<div><div class="textwidget custom-html-widget"><div class="moduletable pt-2 pb-2 mb-4">
<div class="custom pl-2 pr-2 pt-4 pb-2 mb-4">
<div class="control-group form-group">
<div class="col"><label for="name">Navn:</label><input id="name" class="form-control" required="" type="text" data-validation-required-message="Skriv inn ditt navn.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="phone">Telefonnummer:</label><input id="phone" class="form-control" required="" type="tel" data-validation-required-message="Skriv inn et telefonnummer.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="email">E-post:</label><input id="email" class="form-control" required="" type="email" data-validation-required-message="Skriv inn en e-postadresse.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="message">Melding:</label><textarea id="message" class="form-control" style="resize: none;" cols="100" maxlength="999" required="" rows="10" data-validation-required-message="Skriv en melding"></textarea>
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="attachment">Vedlegg:</label> <input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
</div>
</div>
<div class="control-group form-group">
<div class="col"><label class="checkbox"> <input id="terms-and-conditions" name="terms-and-conditions" required="" type="checkbox" data-validation-required-message="Kryss av denne boksen hvis du vil fortsette"> Ved avkryssning samtykker du i vår personvernerklæring. </label>
<div class="help-block"></div>
</div>
</div>
<p class="help-block"></p>
<div id="success"></div>
<div class="col"><button id="sendMessageButton" class="btn btn-success" type="submit">Send oss melding</button></div></div>
</div></div></div></form>
JS: I think the problem is here, but I cant figure out what to change or add to make the data from the fields pass through along with the attachment.
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {},
submitSuccess: function($form, event) {
$("#btnSubmit").attr("disabled", true);
event.preventDefault();
var data = new FormData(contactForm);
$.ajax({
url: "/wp-content/themes/bootstrap/mail/contact_me.php",
type: "POST",
method: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function() {
$("#btnSubmit").attr("disabled", false);
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-success').append("<strong>Takk for din interesse. </strong>");
$('#success > .alert-success').append('</div>');
$('#contactForm').trigger("reset");
},
error: function() {
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-danger').append("<strong>Sorry, it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
$('#contactForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
$('#name').focus(function() {
$('#success').html('');
});
PHP:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/* Exception class. */
require 'Exception.php';
/* The main PHPMailer class. */
require 'PHPMailer.php';
$name = strip_tags(htmlspecialchars($_POST['name']));
$from = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$path = strip_tags(htmlspecialchars($_POST['path']));
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->AddReplyTo(($email_address), ($name));
$mail->setFrom('noreply#mydomain.no', 'Kontaktskjema på nettside');
$mail->addAddress('email#gmail.com', 'My NAME');
$mail->Subject = 'Melding fra ' .$name. ' via kontaktskjema';
$mail->Body = "Du har fått en melding via kontaktskjemaet på nettsiden.\n\n"."Her er detaljene:\n\nNavn: $name\n\nE-post: $email_address\n\nTelefon: $phone\n\nMelding:\n$message";
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
return true;
?>
Most of your <input> elements don't have name attributes. So this won't include them:
new FormData(contactForm)
The file input works because it has a name:
<input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
^----- here ------^
Add names to the rest of the inputs that you want included in the FormData object.
Like David said most of your <input> elements dont have name attributes and thats why the FormData method dont include them, you have two work arounds here:
Get all your data into an array using the id of each element and pass this array to your ajax e.g:
let data = {
name : $('#name').val(),
email: $('#email').val(),
.....
};
add the name attribute to each input.
Hope it helps

Display validation error within a popup window (modal)

I want to display the form validation error within the Modal, but the errors are being displayed in a new page
View
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="modelError">hi</div>
<?php echo form_open('welcome/add_data','id="myform"'); ?>
<div class="form-group">
<label for="user_name" class="col-sm-4 control-label">User Name</label>
<div class="col-sm-12">
<input class="form-control" type="text" name="user_name" id="user_name">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Name</label>
<div class="col-sm-12">
<input class="form-control" type="text" name="name" id="name">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="add">Save</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function () {
$(document).on('submit','#myform',function(event){
event.preventDefault();
let name=$("#name").val();
let user_name=$("#user_name").val();
$.ajax({
url:"<?php echo base_url(). 'welcome/add_data';?>",
method: 'POST',
data:new FormData(this),
contentType:false,
processData:false,
success: function(data) {
var myObj = JSON.parse(data);
var msg = '<div class="alert alert-danger alert-dismissable">'+myObj.error+'</div>';
$('#modelError').html(msg);
},
error: function() {
alert('Error get data from ajax');
}
}
});
})
})
</script>
Controller
public function add_data(){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('user_name', 'User Name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->msg['error'] = validation_errors();
echo json_encode($this->msg);
}
else {
$data=array(
'name'=>$this->input->post('name'),
'user_name'=>$this->input->post('user_name'),
);
$this->Test_model->add_data($data);
redirect('welcome',"refresh");
}
}
I expect the errors within the Modal (pop up window), but the errors are displayed in a new page "localhost/ajax/welcome/add_data"
I have tried lots of code snippets from stackoverflow but none of them works.

Resources