Why don't working ajax upload file in laravel - php

I can't upload a file to laravel with ajax form.
in controller i get: file {}, but in $_FILES i get my file with size.
i'am use in my form {{ csrf_field() }}, enctype
<form id="sent" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="message-text" class="col-form-label"></label>
<textarea class="form-control" id="message-text"></textarea>
</div>
<div class="form-group">
<input id="file_v" type="file" class="form-control-file border" name="filename">
</div>
</form>
</div>
<div class="modal-footer">
Cancel
<input type="submit" name="upload" id="upload" class="btn" value="upload">
and ajax
$('#upload').click(function(event) {
event.preventDefault();
var mes = $('#message-text').val();
var file = $("form input[type=file]").val();
var formData = new FormData();
formData.append('message', mes);
formData.append( 'file', $("#file_v").prop('files')[0]);
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '/sent',
method:'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success:function(data) {
console.log(data);
},
error:function(data){
alert("Get Error!");
}
});
});

Related

how i detect submit btn name using ajax php

I need help!
i need to know how i can detect button name for upload.php file so i can put if(isset($_post['aa'))
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
The Form
<form id="uploadForm" action="upload.php" method="post">
<div class="row">
<div class="col-md-12 mb-1">
<div id="targetLayer">No Image</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input name="text" type="text" class="inputFile form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input name="userImage" type="file" class="inputFile form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group text-center">
<input type="submit" value="Save" name="aa" class="btnSubmit btn btn-success" />
</div>
</div>
</div>
</form>
Submit buttons are not generally/automatically sent in ajax requests.
They aren't added to FormData or .serialize().
In your code, add this field manually.
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var formData = new FormData(this);
formData.append('aa', 'Save');
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
In this form you mentioned that the name of the button is aa
so it will become
if(isset($_POST['aa']) && $_POST['aa'] == 'Save') ...
Here is the screenshot of what it looks like when request is posted.

Laravel 5.8 file upload using PUT method with ajax

I'm trying to update a file using a PUT method with ajax. For whatever reason I can't send a request in my controller. I created a custom validator to check whether a file is missing or a certain input request is missing. It keeps on returning 422 file is missing and name is missing. What do I miss? Here's my code below.
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#news_id').on('submit', function(e) {
e.preventDefault();
var data = new FormData();
var newsletter_name = $('#newsletter_name').val();
var newsletter_file = $('#newsletter_file')[0].files[0];
data.append('newsletter_name', newsletter_name);
data.append('newsletter_file', newsletter_file);
var id = $('#hidden_id').val();
console.log(newsletter_file);
$.ajax({
url: '/admin/newsletter/' + id,
type: 'PUT',
data: data,
contentType: false,
processData: false,
beforeSend: function(data) {
},
success: function(data) {
console.log('success');
},
error: function(data) {
console.log(data)
},
});
});
});
</script>
Here's my html code
<div class="container mt-5">
<div class="col-md-6">
<form action="" method="" enctype="multipart/form-data" id="news_id">
#method('PUT')
<div class="form-group">
<label for="newsletter_name">Name</label>
<input type="text" value="{{$newsletter->newsletter_name}}" name="newsletter_name" id="newsletter_name" class="form-control" placeholder="" aria-describedby="helpId">
<input type="hidden" name="hidden_id" id="hidden_id" value="{{$newsletter->newsletter_id}}">
<input type="hidden" name="_method" value="PUT">
</div>
<div class="input-group mb-3">
<div class="custom-file">
<input name="newsletter_file" type="file" class="custom-file-input" id="newsletter_file" aria-describedby="inputGroupFileAddon03">
<label class="custom-file-label" for="newsletter_file">Choose file</label>
</div>
</div>
<div>
<button class="btn btn-primary btn-block" type="submit">UPDATE</button>
</div>
</form>
</div>
</div>
Add data.append('_method', 'PUT'); then change your request type to type: 'POST'
Because some browser can't send a PUT request, so Laravel can do receive a PUT request by receiving _method data.

Jquery ajax function not working while submitting form

I'm trying to submit a form using ajax and php but for some reason my ajax is not working, when I try to hi the submit button it takes me to the page where my form will be process.
Form
<form id='formData' action="process/profile-settings" method="POST">
<div class="col-md-8">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $user->userName(); ?>" disabled />
</div>
<div class="form-group">
<label>Description/Bio</label>
<input type="text" name="bio" class="form-control" value="" />
</div>
</div>
<button type="submit" class="btn d-block mx-auto" id="save" name="save">Save</button>
</form>
Ajax Code
$('document').ready(function(e) {
console.log('readyyyy');
$("#save").on('submit', function(e) {
e.preventDefault();
console.log('donwwwww');
var data = $("#formData").serialize();
$.ajax({
async: true,
url: 'process/profile-settings.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'post',
success: (response) => {
console.log('Doneeeee');
},
error: function(status, exception) {
alert('Exception:', exception);
}
});
});
e.preventDefault();
});
Note: I've removed my .php extension using .htaccess so didn't added .php in action attribute
I don't know why it is not working, I've tried all the possible methods
Appreciate your help

laravel ajax post serialize not working

<form id="sendmemessage">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="form-group">
<h2 class="open-f bbold green-text contact-t">SEND ME A MESSAGE!</h2>
</div>
<div class="form-group">
<input type="text" name="name" class="form-control input-sm no-radius" aria-describedby="emailHelp" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="email" class="form-control input-sm no-radius" placeholder="Email">
</div>
<div class="form-group">
<input type="text" name="subject" class="form-control input-sm no-radius" placeholder="Subject">
</div>
<div class="form-group">
<textarea class="form-control input-sm no-radius" name="message" rows="5" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-custom pull-right btn-w">Send Message</button>
</div>
<br>
</form>
I am trying to subit the values of the form,i know this is just basic but i dont know why is not working.
below is my ajax,
$("#sendmemessage").submit(function(stay){
$.ajax({
type: 'POST',
url: "{{ url('/') }}/message_me",
data: $(this).serialize(),
success: function (data) {
alert();
},
});
stay.preventDefault();
});
my route
Route::post('message_me','home_controller#message_me');
my controller
class home_controller extends Controller{
public function message_me(){
echo "its here!";
}
}
here are my form details code
$(this).serialize() was inside the ajax object and it refers to ajax not the form.
$("#sendmemessage").submit(function(stay){
var formdata = $(this).serialize(); // here $(this) refere to the form its submitting
$.ajax({
type: 'POST',
url: "{{ url('/') }}/message_me",
data: formdata, // here $(this) refers to the ajax object not form
success: function (data) {
alert();
},
});
stay.preventDefault();
});
Start with replacing
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
with the helper function
{!! csrf_field() !!}
I structure my ajax calls like the following:
$("#sendmemessage").on('submit', function(e) {
e.preventDefault();
var data = $("#sendmessage").serialize();
$.ajax({
type: "post",
url: "/message_me",
data: data,
dataType: "json",
success: function(data) {
console.log('success');
},
error: function(error) {
console.log('error');
}
});
});
Can you access the "message_me" route via the browser? A 500 internal server error should give you clear insight why the request fails.

Ajax POST form to PHP

Trying to post my form using Ajax. Using Apache Cordova but can't seem to send it to my php form. Any ideas of how to get my form to work would be appreciated.
<script type="text/javascript">
$('#userform').submit(function(){
var postData = $(this).serialize();
$.ajax({
type: 'POST',
data: postData,
url: 'http://myurl/dbInsertUserslocal.php',
success: function(data){
console.log(data);
alert('User successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding New User');
}
});
return false;
});
</script>
and my form looks like:
<form id="userform" method="Post">
<div class="row">
<div class="large-4 columns">
<label>First/Last Name
<input type="text" name="firstlast" />
</label>
</div>
</div>
<div class="row">
<div class="large-2 columns">
<label>Title
<select name="title" >
<option value=""></option>
<option value="Inspector">Inspector</option>
<option value="Tech">Technician</option>
<option value="Supervisor">Supervisor</option>
</select>
</label>
</div>
</div>
<div class="row" >
<div class="large-12 columns">
<hr class="intro-divider">
<input type="file" capture="camera" accept="image/*"
id="snap" name="photo">
</div>
</div>
<hr class="intro-divider">
</div>
</div>
<div class="row">
<div class="large-2 columns">
<button class="tiny" type="submit" value="Submit"
id="submit" data-role="button" data-ajax="false">Add User</button>
</div>
</div>
</form>
If you include the file in form, you must use multipart/form-data.
<form id="userform" method="Post" enctype="multipart/form-data">
serialize method can't see the file data.
By using the FormData object instead of serialize method, the javascripts code becomes
$(function(){
$('#userform').submit(function(){
var fd = new FormData( $(this)[0] );
$.ajax({
type: 'POST',
processData: false,
contentType: false,
data: fd,
dataType: "text",
url: 'http://myurl/dbInsertUserslocal.php',
success: function(data){
alert( data );
alert('User successfully added');
},
error: function(){
alert('There was an error adding New User');
}
});
return false;
});
});
However, some devices does not equip the FormData object.
Check
http://caniuse.com/#search=FormData

Categories