I am learning laravel, when I want to update an object and I use ajax to send data to update action with put method (routing also to set) but my update action side is not receiving it request that ajax send like so
! Code
<form id="formEdit" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="card-body">
<div class="form-group">
<label for="name">Name</label>
<input value="{{$role->name ?? ''}}" type="text" class="form-control" id="name" name="name" placeholder="Enter name">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="float-right btn btn-primary">Lưu lại</button>
</div>
</form>
```
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function sendAjax(url, formData, type, method = 'post'){
var result = $.ajax({
url: url,
method: method,
typeData: 'json',
data: formData,
processData: false,
contentType: false,
async: false
});
return resultAjax(result, type);
}```
```
<script>
$('#formEdit').submit(function(event){
event.preventDefault();
var eleValidate = ['name'];
var data = new FormData($('#formEdit')[0]);
var url = "{{route('role.update', $role->id)}}";
var result = sendAjax(url, data, 'edit', 'put');
if(result){
renderError(result, eleValidate);
}else{
removeError(eleValidate, 'formEdit');
}
});
</script>
```
Route::put('/role/update/{id}', 'update')->name('role.update');
public function update(Request $request, $id)
{
if($request->ajax()){
$role = RoleModel::find($id);
dd($request);
}
}
Payload
dd($request)
Related
I need to send my Front-end data to my server. To do that I create code something like this. But I can't find out send my data to the server using ajax (multipart/form-data)
My HTML Part -
<form id="frmCustomer">
<div>
<label class="form-label" for="customerID">Customer ID</label>
<input class="form-control" id="customerID" name="id" type="text">
</div>
<div>
<label class="form-label" for="customerName">Customer Name</label>
<input class="form-control" id="customerName" name="name" type="text">
</div>
<div>
<label class="form-label" for="customerAddress">Customer Address</label>
<input class="form-control" id="customerAddress" name="address" type="text">
</div>
<div>
<label class="form-label" for="customerSalary">Customer Salary</label>
<input class="form-control" id="customerSalary" name="salary" type="text">
</div>
<div class="form-group">
<label for="inputNICImageCreateAccount"> <i class="tags icon"></i> Image Of Your NIC</label>
<input class="form-control-file" id="inputNICImageCreateAccount" type="file" name="file">
</div>
<div class="btn-group mt-3">
<button class="btn btn-primary" id="btnSave" type="button">Register Customer</button>
<button class="btn btn-info" id="btnSearch" type="button">Search</button>
<button class="btn btn-danger" id="btnRemove" type="button">Remove</button>
<button class="btn btn-warning" id="btnGetAll" type="button">Get All</button>
</div>
</form>
My Ajax Part -
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'multipart/form-data',
async: true,
data:,
success: function (data) {
console.log(data)
}
})
})
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
var data = new FormData();
data.append('customerID',customerID);
data.append('customerName',customerName);
data.append('customerAddress',customerAddress);
data.append('customerSalary',customerSalary);
data.append('NICImage',NICImage);
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'multipart/form-data',
async: true,
data:data,
processData: false,
success: function (data) {
console.log(data)
}
});
});
keys setting with FormData should match with your API endPoint parameter names.
to pass data in JSON format rather the Formdata,
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
var formData = {
customerID : customerID,
customerName : customerName,
customerAddress : customerAddress,
customerSalary : customerSalary
};
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'application/json',
async: true,
data : JSON.stringify(formData),
processData: false,
success: function (data) {
console.log(data)
}
});
});
type:'post',
url:url,
dataType:'json',
data:new FormData($('#frmCustomer')[0]),
processData: false,
contentType: false,
cache:false,
async:false,
I'm trying to submit a form with ajax but I'm getting an error The POST method is not supported for this route. Supported methods: GET, HEAD. I have seen a lot of questions and answers on Stackoverflow and other sources but didn't get a solution, how can I fix this?
Blade file
<form method="POST" enctype="multipart/form-data">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<div class="form-group" >
<label for="title">Title</label>
<input type="text" name="title" >
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" name="description">
</div>
<button type='submit' id="btn" >submit
</form>
Javascript
<script>
$(document).ready(function(){
$("#btn").click(function(event){
event.preventDefault();
var url = '{{ route('review.store') }}';
var form = $('form')[0];
var formData = new FormData(form);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success:function(data){
if($.isEmptyObject(data.error)){
$("#msg").html("successfull");
$("#msg").fadeOut(3000);
}
}
});
});
});
</script>
Route
Route::post('review', 'ProductReviewController#store')->name('review.store');
You cannot use single quote ' inside '' in javascript. Enclosed your data in double quotes ""
Change
var url = '{{ route('review.store') }}';
to
var url = "{{ route('review.store') }}";
Hi I am trying to send form data using ajax to my controller in Laravel. In my controller I am trying to return $request->all() to see if the form data is present. I am getting an error 500 internal server error and I am not sure why. I have setup my Exceptions/Handler.php to receive errors and also checked the error log.
Here is my HTML and Ajax:
<div class="container">
<div class="row">
<h1>Create your post</h1>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="post">Post</label>
<textarea name="post" rows="8" cols="80" id="post" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="image">Add image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<input type="submit" name="submit" value="Submit Post" id="submit" class="btn btn-primary">
</div>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click", function(e){
e.preventDefault();
var formData = new FormData();
var fileData = $('#image').prop('files')[0];
var title = $('#title').val();
var post = $('#post').val();
formData.append('fileData', fileData);
formData.append('title', title);
formData.append('post', post);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
}
});
$.ajax({
url:'/post/create/create',
type: "POST",
data: {
formData: formData
},
dataType: 'json',
success:function(response){
toastr.success(response.response);
},
error: function(error){
toastr.error(error.error)
}
});
});
});
</script>
Here is my controller:
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200)
}
missing ;
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200); //<--here
}
Apparently in the DOM have changed the values, even changed the ID of the form with the idea that the script no longer has effect but when you click Publish, nothing happens. Searching I tried to use "prop" instead of "attr" but it still does not work. I think it's because of the "e.preventDefault ()". But I do not know how to disable it. This is my code.
As you can see once the request is sent, the input and the "send" button are deactivated and when the values are received, they change the id of the form, the id and name of the button and it is renamed "Publish".
<script>
jQuery(function($){
var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
$('[id^="form-search"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
});
</script>
Here my html
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<button id="search" name="search" class="btn btn-success boton">Search</button>
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
Here a fiddle showing that happened (check DOM).
JSFiddle.net
//var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
// when the action is plugin url.
$(document).on('submit','[id^="form-search"]', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
// when the action point to publish.php === This is what you need
$(document).on('submit','[id^="form-publish"]', function(e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type : 'POST',
url : url,
data : $(this).serialize(),
cache: false,
beforeSend: function(){
// do your pre-processing
}
}).done(function(data) {
// do your post processing.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<input type ="submit" id="search" name="search" class="btn btn-success boton">Search</button>
<!-- change the button type to submit type -->
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.
Undefined Index :- File
Here's my code.
HTML
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
Ajax
$("#add_product").click(function(e) {
e.preventDefault();
product_name = $("product_name").val();
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $("#add_new_product").serialize(),
success: function(response) {
//
alert(response);
}
})
});
PHP
if (0 < $_FILES['file']['error']) {
echo ":!";
} else {
echo "ASa";
}
What am I missing here?
Can you try using FormData():
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The above is a sample code, but you may use it to modify it.
you can use FormData
$("#add_product").click(function(e) {
e.preventDefault();
var fdata = new FormData()
fdata.append("product_name", $("product_name").val());
if ($("#file")[0].files.length > 0)
fdata.append("file", $("#file")[0].files[0])
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: fdata,
contentType: false,
processData: false,
success: function(response) {
//
alert(response);
}
})
});
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
We need to acknowledge first is that we need to APPEND both Form Input Data and Form File(s) into a single FormData variable.
Here is my solution in which I have enabled Multi File option so that this solution can fit for all examples.
It is Important to include name attribute in the input controls to make it work properly on server side in most of cases. If you are using C# then you can use simply Request.Form["nameAttribute"] to simply get the function. It is similar for Java and other languages.
My Sample Code is
$(document).ready(function () //Setting up on Document to Ready Function
{
$("#btnUpload").click(function (event) {
//getting form into Jquery Wrapper Instance to enable JQuery Functions on form
var form = $("#myForm1");
//Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
var params = form.serializeArray();
//Getting Files Collection
var files = $("#File1")[0].files;
//Declaring new Form Data Instance
var formData = new FormData();
//Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
//Now Looping the parameters for all form input fields and assigning them as Name Value pairs.
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
//disabling Submit Button so that user cannot press Submit Multiple times
var btn = $(this);
btn.val("Uploading...");
btn.prop("disabled", true);
$.ajax({
url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc
method: "post",
data: formData,
contentType: false,
processData: false,
success: function () {
//Firing event if File Upload is completed!
alert("Upload Completed");
btn.prop("disabled", false);
btn.val("Submit");
$("#File1").val("");
},
error: function (error) { alert("Error"); }
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" id="myForm1">
<p><textarea id="TextArea1" rows="2" cols="20" name="TextArea1"></textarea></p>
<p><input id="File1" type="file" multiple="multiple" /></p>
<input id="btnUpload" type="button" value="Submit" />
</form>
For a working example (asp.net C# with handlers) you can visit sample code on https://github.com/vibs2006/HttpFileHandlerFormDataSample