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

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"

Related

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

How to validate modal form on click with Ajax in Laravel

I have a modal form for login in Laravel project. When I enter false data and click to the button "Log in" the page refreshing and modal is closing. I can see errors only when I open modal again. It's not user-friendly. I want to validate modal with Ajax and show errors if something goes wrong without refreshing page
This is my modal
<form action="/login" method="post">
#csrf
<div class="sign-in-wrapper">
Login with Facebook
Login with Google
<div class="divider"><span>Or</span></div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" name="email" id="email">
<i class="icon_mail_alt"></i>
#error('email')
<strong style="color: red">{{$message}}</strong>
#enderror
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" name="password" id="password" value="">
<i class="icon_lock_alt"></i>
#error('password')
<strong style="color: red">{{$message}}</strong>
#enderror
</div>
<div class="clearfix add_bottom_15">
<div class="checkboxes float-left">
<input id="remember-me" type="checkbox" name="check">
<label for="remember-me">Remember Me</label>
</div>
<div class="float-right"><a id="forgot" href="javascript:void(0);">Forgot Password?</a></div>
</div>
<div class="text-center">
<button type="submit" class="btn_login">Log In</button>
</div>
<div class="text-center">
Don’t have an account? Sign up
</div>
<div id="forgot_pw">
<div class="form-group">
<label>Please confirm login email below</label>
<input type="email" class="form-control" name="email_forgot" id="email_forgot">
<i class="icon_mail_alt"></i>
</div>
<p>You will receive an email containing a link allowing you to reset your password to a new preferred
one.</p>
<div class="text-center"><input type="submit" value="Reset Password" class="btn_1"></div>
</div>
</div>
</form>
Try this
You need to some custom changes yourself in code.
$('#frmLogin').on('submit', function (event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: '/login',
data: formData,
success: function (res) {
console.log(res); // get resposnse from controller in json
if (res.emailError) {
$('.error-email').show().text(res.errorMsg);
} else {
$('.error-email').hide();
}
if (res.passwordError) {
$('.error-password').text(res.errorMsg);
} else {
$('.error-password').hide();
}
},
error: function (data) {
alert(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frmLogin" method="POST">
#csrf
<div class="sign-in-wrapper">
Login with Facebook
Login with Google
<div class="divider"><span>Or</span></div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" name="email" id="email">
<i class="icon_mail_alt"></i>
<strong style="color: red;display: none;" class="error-email">{{$message}}</strong>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" name="password" id="password" value="">
<i class="icon_lock_alt"></i>
<strong style="color: red;display: none;" class="error-password">{{$message}}</strong>
</div>
<div class="clearfix add_bottom_15">
<div class="checkboxes float-left">
<input id="remember-me" type="checkbox" name="check">
<label for="remember-me">Remember Me</label>
</div>
<div class="float-right"><a id="forgot" href="javascript:void(0);">Forgot Password?</a></div>
</div>
<div class="text-center">
<button type="submit" class="btn_login">Log In</button>
</div>
<div class="text-center">
Don’t have an account? Sign up
</div>
</div>
</form>

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());

Cannot get value from summernote ,when using ajax update

when i click edit button (i used modal bootstrap) all value exist except textarea with summernote.
if you input something(in summernote) and cancel it ,your value doesn't disappear ... it should be clear .
forgive me, my english so bad .
here is my modal form :
<div class="modal-dialog modal-lg">
<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">Formulir Berita</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_berita"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-2">Tanggal penulisan</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
<input name="tgl" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Judul</label>
<div class="col-md-9">
<input name="judul" placeholder="Judul" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Penulis</label>
<div class="col-md-9">
<input name="penulis" placeholder="Penulis" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group" id="photo-preview">
<label class="control-label col-md-2">Gambar</label>
<div class="col-md-4">
(Tidak ada gambar)
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" id="label-photo">Unggah Foto </label>
<div class="col-md-7">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Ganti Foto</span>
<span class="fileupload-new">Pilih File</span>
<input name="gambar" type="file" />
</span>
<span class="help-block"></span>
Remove
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Isi</label>
<div class="col-md-9">
<textarea name="isi" class="form-control" id="summernote" >
</textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Simpan</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Batal</button>
</div>
</div>
</div>
</div>
i 've been trying some code :
$('#summernote').summernote('code');
$('#summernote').summernote('reset');// and for resetting modal while Add Data
it doesn't happen anything
my ajax function :
function edit_berita(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('sistem/berita/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data){
// $('#summernote').summernote('code');
$('[name="id_berita"]').val(data.id_berita);
$('[name="tgl"]').datepicker('update',data.tgl);
$('[name="judul"]').val(data.judul);
$('[name="isi"]').val(data.isi);
$('[name="penulis"]').val(data.penulis);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit data'); // Set title to Bootstrap modal title
$('#photo-preview').show(); // show photo preview modal
if(data.gambar)
{
$('#label-photo').text(''); // label photo upload
$('#photo-preview div').html('<img src="'+base_url+'upload/berita/'+data.gambar+'" class="img-responsive" >'); // show photo
$('#photo-preview div').append('<input type="checkbox" name="remove_photo" value="'+data.gambar+'"/> Remove photo when saving'); // remove photo
}
else
{
$('#label-photo').text(''); // label photo upload
$('#photo-preview div').text('(Tidak ada gambar)');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
Text Area doesnot have value. jQuery .html() works in this case
$("textarea#summernote").html(data.isi);
Try to modify the summernote line like this :
$('#summernote').summernote('code', data.isi);
And to clear the content :
$('#summernote').summernote('code', '');
Please try this:
$("textarea#summernote").val(data.isi);
$( '[name="isi"]' ).val(data.isi);
$( '[name="isi"]' ).summernote();

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