how best to send form data through ajax in Laravel - ajax

`I am trying to pass data from my modal form through ajax but I get the error of the route not supporting Post method.
here is my modal form in the blade view:
<form role="form" method="post" id="edit-student-data-form" data-ajax="true">
#csrf
{{ method_field('POST') }}
<div class="pl-lg-6">
<div class="col-lg-5">
<div class="form-group">
<label class="form-control-label" for="post-text">Name: </label>
{{$name}}
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label class="form-control-label">Reg No: </label>
{{$sender}}
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label class="form-control-label">Program: </label>
{{$program}}
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label class="form-control-label" for="input-email">Email: </label>
<input name="email" type="email" id="email" class="form-control form-control-alternative" placeholder="{{$email}}">
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label class="form-control-label" for="input-phone">Phone Number</label>
<input name="phone" type="text" id ="phone" class="form-control form-control-alternative" placeholder="{{$tel}}">
</div>
</div>
</div>
<!-- Submit button -->
<div id="results"></div>
<div class="pl-lg-0 pr-0 text-center">
<button class="btn btn-success btn-sm pl-lg-2 pt-2 pb-2 pr-2"
id="submit" style="color:white">
Submit
</button>
<img style="visibility: hidden" id="loader" src="{{ asset('argon') }}/img/brand/ajax-loader.gif" alt="working.." />
</div>
</form>
here are my routes:
//student routes
Route::middleware(['auth', 'user-role:1'])->group(function(){
Route::get('/student/home', [App\Http\Controllers\StudentController::class, 'index'])->name('home.student');
Route::post('student/update', [App\Http\Controllers\StudentController::class, 'studentupdate'])->name('studentupdate');
});
here is my js code to send the form data using ajax:
> ```
> $.ajaxSetup({
> headers: {
> 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
> }
> });
> $('#edit-student-data-form').on('submit', function(event){
> event.preventDefault();
> console.log("form submitted!") // sanity check
> edit_student();
> });
>
> function edit_student() {
> console.log('create post is working');
> hideshow('loader',1);
> $.ajax({
> url: "student/update",
> type: "POST",
> data:$('#edit-student-data-form').serialize(),
> dataType: "json",
> contentType: false,
> cache: false,
> processData: false,
> success: function (json) {
> if (json.error === true) {
> $('#results').html("<div class='alert-box alert radius text-warning' data-alert>"+json.message+
> "</div>");
> else {
> $('#results').html("<div class='alert-box alert radius text-success' data-alert>"+json.message+
> "</div>");
> }
> resetForm('edit-student-data-form');
> hideshow('loader',0);
> console.log(json.message);
> },
> error: function (xhr, errmsg, err) {
> console.log(xhr.status + ": " + xhr.responseText);
> }
>
> });
> }
> ```
i tried adding the #csrf fieldl to the form and removing the route from the grouped middleware route but could not work still. the error persists`

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"

Uncaught (in promise) Error: Request failed with status code 405 VUEJS

so i'm trying to consume an api form laravel via vue.js this is the login page were i did call axios.post :
<template>
<main>
<section class="login-content">
<div class="container h-100">
<div
class="row align-items-center justify-content-center h-100"
>
<div class="col-12">
<div class="row align-items-center">
<div class="col-lg-6">
<h2 class="mb-2">Sign In</h2>
<p>
To Keep connected with us please login with
your personal info.
</p>
<form>
<div class="row">
<div class="col-lg-12">
<div
class="floating-label form-group"
>
<input
class="floating-input form-control"
type="email"
v-model="data.email"
placeholder=" "
/>
<label>Email</label>
</div>
</div>
<div class="col-lg-12">
<div
class="floating-label form-group"
>
<input
class="floating-input form-control"
type="password"
v-model="data.password"
placeholder=" "
/>
<label>Password</label>
</div>
</div>
<div class="col-lg-6">
<div
class="custom-control custom-checkbox mb-3"
>
<input
type="checkbox"
class="custom-control-input"
id="customCheck1"
/>
<label
class="custom-control-label"
for="customCheck1"
>Remember Me</label
>
</div>
</div>
<div class="col-lg-6">
<a
href="auth-recoverpw.html"
class="text-primary float-right"
>Forgot Password?</a
>
</div>
</div>
<button
type="sumbit"
class="btn btn-primary"
#click="login" :disabled="isLogging" :loading="isLogging"
>
Sign In
</button>
<p class="mt-3">
Create an Account
<router-link to="/" exact
>Sign Up</router-link
>
</p>
</form>
</div>
<div class="col-lg-6 mb-lg-0 mb-4 mt-lg-0 mt-4">
<img
src=" asset (html/assets/images/login/01.png)"
class="img-fluid w-80"
alt=""
/>
</div>
</div>
</div>
</div>
</div>
</section>
</main>
</template>
<script>
export default {
data() {
return {
data: {
email: "",
password: ""
},
isLogging: false
};
},
methods: {
async login() {
if (this.data.email == "") return alert("Email is required")
if (this.data.password == "") return alert("Password is required")
/* if(this.data.password.length<6) return this.e ('Incorrect') */
this.isLogging = true
const axios = require('axios')
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Method": "POST",
"Content-Type": "application/json",
}
axios.post('http://127.0.0.1:8000/?#/login/',{
email: this.email, password: this.password
}, headers)
.then((response)=>{
const data=response.data;
console.log(data);
})
this.isLogging = false
}
},
mounted() {
console.log("Component mounted.");
}
};
</script>
the step of confirmation : email and password are working well but i got the error when i press the button
and this is the login page as u can see : this is the login page as u can see
i was follwing this tuto but like always i had error unlike the man in the tuto this is the link of the tuto
and this is the route :
Route::post('login', 'App\Http\Controllers\Api\AuthController#login');

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

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.

codeigniter upload an image file error

please help me with this error. I have a javascript that i want to append a single image file to my form and i want to send the form data into ajax.
Here is my code:
<form id="frm_product" class="form-horizontal" enctype="multipart/form-data">
<div style="position:relative;">
<input type="file" name="addfiles" id="addfiles">
<span class='label label-info' id="upload-file-info"></span>
</div>
<br>
<div class="form-group">
<label for="cat_name">Product Name: </label>
<input type="text" class="form-control" name="prod_name">
<span class="error prod_name"></span>
</div>
<div class="form-group">
<label for="cat_desc">Description: </label>
<input type="text" class="form-control" name="prod_desc">
<span class="error prod_desc"></span>
</div>
<div class="form-group">
<label for="cat_desc">Price: </label>
<input type="text" class="form-control" name="prod_price">
<span class="error prod_price"></span>
</div>
<div class="form-group">
<label for="cat_desc">Category: </label>
<select class="form-control" name="prod_cat">
<?php foreach($data as $category){ ?>
<option value="<?php echo $category->id; ?>"><?php echo $category->name; ?></option>';
<?php } ?>
</select>
<span class="error prod_cat"></span>
</div>
</form>
here is my ajax code where i want to append a single file:
function submitProduct() {
var formData = new FormData($("#frm_product")[0]);
formData.append('image', $("#addfiles")[0].files);
$.ajax({
url : siteurl+"/product/addproduct",
type: "POST",
data: formData,
dataType: "JSON",
contentType: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function(resp) {
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
else if(resp.status == true) {
$('#addProduct').modal('hide');
$('#frm_product')[0].reset();
alert("Successfully Added");
}
}
});
}
when i do upload file it says error:
you didn't select a file to upload

Resources