laravel 422 (Unprocessable Entity) ajax file upload - javascript

I am using Laravel 6 and i would also like to say that i am not that much experienced working on Laravel.
I have searched SO and google as well but not got any solution to this problem. Below are the files and code
PordController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Prod;
use App\Section;
use Illuminate\Support\Facades\Validator;
class ProdsController extends Controller
{
function __construct () {
$this->middleware('role:admin');
}
public function index(Request $request)
{
$tasks = Prod::orderBy('id', 'desc')->get();
$section = Section::all();
$arr['tasks'] = $tasks;
$arr['sections'] = $section;
return view('admin.pords',$arr);
}
public function store(Request $request)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
if ($files = $request->file('fileUpload')) {
$destinationPath = public_path('images'); // upload path
$profileImage = rand() .".". $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
}
$task = Prod::create($request->all());
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function show($id)
{
$task = Prod::find($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$task = Prod::find($id);
$task->name = $request->input('name');
$task->save();
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function destroy($id)
{
$task = Prod::destroy($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
}
prods_add.blade.php
<!-- Add Task Modal Form HTML -->
<div class="modal fade" id="addTaskModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="frmAddTask" enctype="multipart/form-data" method="POST">
<div class="modal-header">
<h4 class="modal-title">
add
</h4>
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" id="add-error-bag">
<ul id="add-task-errors">
</ul>
</div>
<div class="form-group">
<label>
name
</label>
<input class="form-control" id="name" name="name" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
desc
</label>
<input class="form-control" id="desc" name="description" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
member
</label>
<input class="form-control" id="member" name="member" required="" type="number">
</input>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>
isfiles allow
</label>
<input class="form-control" type="checkbox" id="isfile" name="isfile" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
camera allow
</label>
<input class="form-control" type="checkbox" id="isvideo" name="isvideo" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
mic allow
</label>
<input class="form-control" type="checkbox" id="ismic" name="ismic" value="true" checked>
</input>
</div>
</div>
</div>
<div class="form-group">
<label>
sections
</label>
<select id="section_id" name="section_id" class="form-control">
#foreach ($sections as $section)
<option value="{{$section->id}}">{{$section->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<div class="form-group">
<label for="file"> <div class="btn btn-primary btn-sm float-left">
<span>Choose file</span>
</div></label>
<input style="color:black" type="file" class="form-control-file" id="file" name="fileUpload">
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-default" data-dismiss="modal" type="button" value="cancel">
<button class="btn btn-info" id="btn-add" type="button" value="add">
add
</button>
</input>
</div>
</form>
</div>
</div>
</div>
pords.js
$(document).ready(function() {
$("#btn-add").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var car = 0;
var car1 = 0;
var car2 = 0;
var x = document.getElementById("isfile").checked;
if(x === true){
car = 1;
}
if(document.getElementById("isvideo").checked === true){
car1 = 1;
}
if(document.getElementById("ismic").checked === true){
car2 = 1;
}
console.log($("#file").get(0).files[0]);
var filess = $("#file").get(0).files[0];
$.ajax({
type: 'POST',
url: '/admincp/prods',
data: {
name: $("#frmAddTask input[name=name]").val(),
description: $("#frmAddTask input[name=description]").val(),
display: 1,
sessionid: 'sadasdasdasdasd',
password: 'sadasdasdasdasd',
fileUpload: filess,
img: "path",
member: $("#frmAddTask input[name=member]").val(),
isfile: car,
isvideo: car1,
ismic: car2,
section_id: $("#frmAddTask select[name=section_id]").val(),
},
processData: false,
dataType: 'json',
success: function(data) {
$('#frmAddTask').trigger("reset");
$("#frmAddTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#add-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#add-task-errors').append('<li>' + value + '</li>');
});
$("#add-error-bag").show();
}
});
});
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/admincp/prods/' + $("#frmEditTask input[name=id]").val(),
data: {
name: $("#frmEditTask input[name=name]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditTask').trigger("reset");
$("#frmEditTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-task-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/admincp/prods/' + $("#frmDeleteTask input[name=id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteTask .close").click();
window.location.reload();
pushnotify('تم الحذف بنجاح ');
},
error: function(data) {
console.log(data);
}
});
});
});
function addTaskForm() {
$(document).ready(function() {
$("#add-error-bag").hide();
$('#addTaskModal').modal('show');
});
}
function editTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditTask input[name=name]").val(data.task.name);
$("#frmEditTask input[name=id]").val(data.task.id);
$('#editTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
function deleteTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#frmDeleteTask #delete-title").html("Delete Task (" + data.task.name + ")?");
$("#frmDeleteTask input[name=id]").val(data.task.id);
$('#deleteTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
The error in js file because without fetching the image value works great
When I add a value the image gets the error

The problem could be here:
$task = Prod::create($request->all());
try to make
public function store(Request $request)
{
dd($request->all());
}
and in network see the response.
also, when you make Prod::create($request->all());
it request everything like __token and so on

Related

Edit function in datatables and laravel

Hi im doing an App with Datatables and i have a problem when i want to try to edit a record in the datatables this is my js function in app.blade.php
$(document).on('click', '.editButton', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
the console.log(result) is empty and console.log(message) is undefined
this is the edit function in the controller
public function edit(Request $request)
{
$result = Message::where('id', $request->id)->first();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
i want to edit the message with a modal, but the js fuction doesnt work properly, the var message is undefined
this is my route file
Route::middleware('auth')
->namespace('Admin')
->name('admin.')
->prefix('admin')
->group(function () {
Route::get('/', 'HomeController#index')->name('home');
Route::resource('/user', 'UserController');/* ->except(['edit', 'update']); */
Route::resource('/user/{user:id}/messages', 'MessagesController');
/* Route::resource('user.messages', MessagesController::class); */
});
Route::get('messages', 'Admin\MessagesController#getMessages')->name('get.messages');
Auth::routes();
this is my table structure
enter image description here
and its my form for edit the message
<div id="modalEdit" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal Header</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="update">
<div class="modal-body">
<div class="form-group">
<label for="text">Testo</label>
<input type="text-area" class="form-control text" id="text" name="text">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url">
</div>
<div class="form-group">
<label for="note">Note</label>
<input type="text" class="form-control" id="note" name="note">
</div>
<div class="form-group">
{{-- <label for="tipes">Tipo</label>
<input type="text" class="form-control" id="tipes" name="tipes"> --}}
<label for="tipes">Tipo</label>
<select name="tipes" id="tipes">
<option value="A">A</option>
<option value="B">B</option>
</select>
</div>
<div class="form-group">
<label for="start_time">Inizio</label>
<input type="date" class="form-control" id="start_time" name="start_time">
</div>
<div class="form-group">
<label for="end_time">Fine</label>
<input type="date" class="form-control" id="end_time" name="end_time">
</div>
<div class="form-group">
<label for="active">Attivo</label>
{{-- <input type="text" class="form-control" id="active" name="active"> --}}
<label for="active">Attivo</label>
<select name="active" id="active">
<option value="1">Si</option>
<option value="0">No</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
public function edit(Request $request,$id)
{
$result = Message::where('id', $id)->get();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
you need to pass $id parameter into function edit! try it! may be it works
$(document).ready(function() {
$('.editbutten').on('click', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
});

How to send ID of a row throught submit form / button?

I'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');

Unable to send "multipart/form-data" form data with jquery-validation.js submitHandler function

//Here is my multipart/form-data form
<form id="addNewRoomForm" enctype="multipart/form-data">
<div class="form-group">
<label for="room_title">Room Title</label>
<input type="text" class="form-control" id="room_title" name="room_title" placeholder="Enter Room Title">
</div>
<div class="form-group">
<label for="room_category">Room Category</label>
<select class="form-control" id="room_category" name="room_category">
<option value=""></option>
<option value="1">Standard Room</option>
<option value="2">Family Room</option>
</select>
</div>
<div class="form-group">
<label for="room-images">Room Images</label>
<div class="input-images"></div><!--Here im using image-uploader.js Plugin By Christian Bayer-->
</div>
<div class="form-group">
<label for="room_description">Room Description</label>
<textarea class="form-control" id="room_description" name="room_description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success btn-icon-split" id="addRoomBtn">
<span class="icon text-white-50">
<i class="fas fa-arrow-right"></i>
</span>
<span class="text">Add Room</span>
</button>
</form>
//Here is my ajax form submission for the above form which is working fin
$("#addNewRoomForm").on('submit', function(e){
var process_url = "<?php echo base_url();?>";
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: process_url + 'admin/rooms/process_add_room',
data: formData,
// dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
alert("sending...");
},
success: function(msg){
alert(msg)
}
});
});
// but when I using the same code inside the jquery-validation.js submitHandler function, it is showing the "message : Undefined_index: room_title" in alert function. below are the codes showing error:
$('#addNewRoomForm').validate({ // initialize the plugin
rules: {
room_title: {
required: true,
},
room_category: {
required: true,
}
},
messages: {
room_title: {
required: "Please Enter Room Title",
},
room_category: {
required: "Select Room Category",
}
},
highlight: function (input) {
console.log(input);
$(input).addClass('is-invalid');
},
unhighlight: function (input) {
$(input).removeClass('is-invalid');
},
errorPlacement: function (error, element) {
// $(element).parents('.input-group').append(error);
$(element).parents('.form-group').append(error);
},
submitHandler: function (form) {
var process_url = "<?php echo base_url();?>";
// e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: process_url + 'admin/rooms/process_add_room',
data: formData,
// dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
alert("sending...");
},
success: function(msg){
alert(msg)
}
});
return false;
}
});
I want to submit the multipart/form-data with jquery-validation. I've tried all the ways now want your help.

Error 500 on return all in Laravel Controller

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
}

I'm trying to upload a file using node and ajax but the ajax call isn't working?

I'm facing error on Upload xml and upload csv am a rookie so please can you provide me a elaborate answer
I've tried debugging the code on clicking upload button till upload function is working fine on jumping to uploadxml() function the data is not sent.
My HTML code
<div class="file-upload">
<form id="file-upload-form">
<div class="upload">
<div class="col-lg-6">
<div class="input-group" id="one">
<input type="text" class="form-control" id="t1" placeholder="Select an xml file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="xmlbtn">Browse</button>
</span>
</div>
<input type="file" accept=".xml" class="hidden" id="xmlPicker" name="xmlFile"/>
</div>
<div class="col-lg-6">
<div class="input-group" id="two">
<input type="text" class="form-control" id="t2" placeholder="Select an csv file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="csvbtn">Browse</button>
</span>
</div>
<input type="file" class="hidden" accept=".csv" id="csvPicker" name="csvFile"/>
</div>
</div>
<div class="uploadfooter">
<button class="btn btn-default center" type="button" id="upload">Upload</button>
</div>
</form>
</div>
My Js
$(document).ready(function () {
$(".ts-sidebar-menu li a").each(function () {
if ($(this).next().length > 0) {
$(this).addClass("parent");
};
})
var menux = $('.ts-sidebar-menu li a.parent');
$('<div class="more"><i class="fa fa-angle-down"></i></div>').insertBefore(menux);
$('.more').click(function () {
$(this).parent('li').toggleClass('open');
});
$('.parent').click(function (e) {
e.preventDefault();
$(this).parent('li').toggleClass('open');
});
$('.menu-btn').click(function () {
$('nav.ts-sidebar').toggleClass('menu-open');
});
$('#zctb').DataTable();
$("#input-43").fileinput({
showPreview: false,
allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
elErrorContainer: "#errorBlock43"
// you can configure `msgErrorClass` and `msgInvalidFileExtension` as well
});
$("#xmlbtn").bind("click", function(){
$("#xmlPicker").trigger("click");
});
$("#xmlPicker").bind("change", function(e){
$("#t1").val($("#xmlPicker")[0].files[0].name);
})
$("#csvbtn").bind("click", function () {
$("#csvPicker").trigger("click");
});
$("#csvPicker").bind("change", function (e) {
$("#t2").val($("#csvPicker")[0].files[0].name)
})
$("#upload").on("click",function () {
var firstfile = $("#t1").val();
var secondfile = $("#t2").val();
if(!firstfile || firstfile != null){
updateXml();
}
if(!secondfile || secondfile != null){
updatecsv();
}
})
function updateXml(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
function updatecsv(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
});
This line here:
var form = $("#file-upload-form").val()
A form does not have a value, its inputs have one. FormData expects a form, so you need to give it a reference to it.
var form = $("#file-upload-form");
var data = new FormData(form[0]); //expects a DOM form

Categories