I have the following code in my form.
I try to upload the files via ajax using jquery.
Other data fields in the form was submitted fine. But i cant add FILES to the POST request.
Here is my html code:
<div class="form-group">
<div class="col-lg-2">
<label class="lab pull-right">Image:</label>
</div>
<div class="col-lg-2">
<input type="file" name="nimp" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-2">
<label class="lab pull-right">Thumb Image:</label>
</div>
<div class="col-lg-2">
<input type="file" name="ntimp" id="ntimp" required>
</div>
</div>
My JQ Code:
$(document).ready(function(e) {
$('button.submit').click(function(e) {
e.preventDefault();
var a=new FormData();
alert(a);
$('.edit_form_prod_div').hide();
$.ajax({
type:"POST",
url:"ep.php",
data:a,
cahe: false,
processData:false,
contentType: false,
success: function(response){
$('.edit_prod_response').html(response)
},
error:function(response)
{ alert("Error Occures"); }
});
$('.edit_prod_response').show();
});
});
Try This Code
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<input type="file" name="files"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function ()
{
$("#btnSubmit").click(function()
{
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "FileUploadHandler",
data: data,
processData: false, // Importent
contentType: false, // Importent
cache: false,
timeout: 600000,
success: function (data)
{ alert("File Uploaded...!")
}
});
});
</script>
Related
I am trying to use Ajax to Submit a form. But when I do submit the page is reloaded and the url changes. I think that the url changes because of the #Html.AntiForgeryToken();
See my code bellow :
This is how my form looks like :
#model PersonModel
....
<form action="SubmitLead" class="new-lead">
#Html.AntiForgeryToken();
<div class="col-md-12">
<p>
<input type="hidden" value="#Model.TrackingCode" id="hdnTrackingCode" />
My name is #Html.TextBoxFor(model => model.FirstName,
new { #placeholder =
Html.DisplayNameFor(model => model.FirstName) })
#Html.TextBoxFor(model => model.Surname, new { #placeholder = Html.DisplayNameFor(model => model.Surname) })
</p>
</div>
<div class="clearfix"></div>
<div class="col-md-12 text-center">
<button type="submit" id="btnSubmit" class="orange-button">Get Quotes Now</button>
</div>
</form>
#if (Model.Results != null &&
Model.Results.IsSuccessful)
{
<div class="col-md-12 text-center">
<img src="~/Content/Images/Products/new-success.png" height="24px" />
<p id="result"></p>
</div>
}
Please see my script here :
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('.new-lead').submit(function (event) {
$.ajax({
url: '#Url.Action("Lead/SubmitLead")',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function (result) {
var resultMessage = "success";
$('result').html(resultMessage);
}
})
})
})
</script>
Do this way
<form onsubmit="return submit(thi)" class="new-lead">
....
</form>
<script>
function submit(e){
$.ajax({
url: '#Url.Action("Lead/SubmitLead")',
type: 'POST',
data: $(e).serialize(),
dataType: 'json',
success: function (result) {
var resultMessage = "success";
$('result').html(resultMessage);
}
})
return false;
}
</script>
I am trying to send form with upload file and multipart/form-data encoding using AJAX. I am using this form:
{!! Form::model($user, ['method' => 'PATCH', 'url' => ['/administrator/users', $user->id], 'class' => 'form-horizontal', 'files' => 'true', 'id' => 'userEdit']) !!}
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">Avatar:</label>
<div class="col-sm-9">
<img src="/dashboard/assets/img/avatar/{{ $user->profile->avatar }}" class="img-circle m-b" />
<input type="file" name="avatar" />
</div>
</div>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="first_name" value="{{ $user->profile->first_name }}" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Surname:</label>
<div class="col-sm-9">
<input type="text" name="last_name" value="{{ $user->profile->last_name }}" class="form-control" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" data-user-id="{{$user->id}}">Save</button>
</div>
{!! Form::close() !!}
I try to send data with Ajax like this:
$('#editUser').submit('#userEdit', function(event) {
event.preventDefault();
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: new FormData(userEdit),
processData: false,
contentType: false,
mimeType: "multipart/form-data",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
And in result, I cannot read inputs from request in controller. It returns an empty array.
public function update($id, Request $request){
dd($request->all());
}
I think that I'm doing something wrong with sending multipart data. How to send it correctly?
It seems that you aren't adding FormData properly and your event seems to be broken, you should add the data in ajax like this:
$('#editUser').on('submit', function(event) {
event.preventDefault();
var form = $(this); // You need to use standard JS object here
var formData = new FormData(form);
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
Hope this helps!
I've tried everything. The form posts fine when not using Ajax, I switch the places so it would be first, I deleted everything and just gave it an alert to show when clicking submit... I can't pin-point the problem.
The second ajax just won't submit!
$(document).ready(function() {
$('#writeform').submit(function(event) {
var formData = {
'from': $('input[name=from]').val(),
'to': $('input[name=to]').val(),
'textbox': $('input[name=textbox]').val()
};
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
// ajax the login
$(document).ready(function() {
$('#loginform').submit(function(event) {
var formData = {
'username': $('input[name=username]').val(),
'pass': $('input[name=pass]').val()
};
$.ajax({
type: 'POST',
url: 'login.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
function loadLogDiv(){
$("#logfunction").load("login.php");
}
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
loadLogDiv();
setInterval( loadLogDiv, 4000);
});
Heres the page itself:
<div id="loginpage">
<form id="loginform" action="login.php" method="POST">
<div id="username">
<label for="username">User Name</label>
<input type="text" name="username" placeholder="User Name" />
<!-- errors will go here -->
</div>
<div id="pass">
<label for="pass">Password</label>
<input type="password" name="pass" placeholder="Password" />
<!-- errors will go here -->
</div>
<input type="submit">Submit</input>
</form>
<div id="logfunction"></div>
</div>
<div id="footer">
<form id="writeform" action="process.php" method="POST">
<div id="from">
<label for="from">From</label>
<select name="from">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="to">
<label for="to">To</label>
<select name="to">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="textbox">
<label for="textbox">Text</label>
<input type="text" name="textbox" placeholder="text" />
</div>
<input type="submit">Submit</input>
</form>
I'm trying to upload both text and files through a form loaded inside a modal and submit it using ajax (I'm using Laravel 5.2) and I can't figure out why it doesn’t working. I have tried many solutions found here and through a search engine.
A simple form (this form is loaded in a modal)
<form id="registerForm" enctype="multipart/form-data" class="form-horizontal" role="form" method="POST">
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" id="name">
<div class="form-group">
<label class="control-label col-md-4" for="pwd">Choose File</label>
<div class="col-md-6">
<input type="file" class="form-control" id="fileProfPic" name="prof_pic">
</div>
</div>
<button type="submit" id="registerButtonModal" class="btn btn-primary"><i class="fa fa-btn fa-user"></i>Register</button>
</form>
.js
$("#registerButtonModal").click(function(){
$('#registerForm').submit(function (e) {
e.preventDefault();
var formData = new FormData($('#registerForm')[0]);
$.ajax({
url: 'register',
type: 'POST',
data: formData,
success: function(msg){
alert(msg);
}
contentType: false,
processData: false
});
});
});
route
Route::post('register',[
'uses' => 'AdminController#postRegister',
'as' => 'postRegister']);
controller //just trying to make it work
public function postRegister(Request $request)
{
return "success";
}
Your problem is likely due to the fact your AJAX should be returning a JSON response with your controller.
Try the following:
public function postRegister(Request $request)
{
return response()->json(['success' => 'success']);
}
With the above you will now have access to the object within your view.
Also, remember to pass your CSRF token in your AJAX. I usually add this in my view when i use AJAX and I pass that variable to data as seen below:
<script>
var token = '{{ Session::token() }}';
</script>
$.ajax({
url: 'register',
type: 'POST',
data: {variable1: variable1, variable2: variable2, _token: token},,
success: function(msg){
alert(msg);
}
contentType: false,
processData: false
});
I can not get the formData from the file upload
form.blade.php
<form method="POST" class="form-horizontal" enctype="multipart/form-data" id="modal-file-upload">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="folder" value="" id="modal-file-upload-folder">
<div class="modal-header">
<h4 class="modal-title">Upload New File</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="file" class="col-sm-3 control-label">
File
</label>
<div class="col-sm-8">
<input multiple="true" accept="image/*" required="true" id="fileToUpload" type="file" name="file[]">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="close_upload_view()">Cancel</button>
<button class="btn btn-primary" id="btn-upload">Upload File</button>
</div>
</form>
Controller
public function uploadMultiFile(Request $request) {
// getting all of the post data
$data = $request->input('formData');
var_dump($data); current return null
}
<script>
// Confirm file delete
function close_upload_view() {
$("#modal-file-upload").modal("hide");
return false;
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$("#modal-file-upload").submit(function(e){
e.preventDefault();
//var formData = new FormData(document.getElementById('modal-file-upload')[0]);
var fd = new FormData();
var ins=document.getElementById('fileToUpload').files.length;
for(var x=0;x<ins;x++)
{
fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}
var folder = $("input#modal-file-upload-folder").val();
var token = $("input[name=_token]").val();
var dataString = 'formData='+fd+'&folder='+folder+'&token='+token;
$.ajax({
type: "POST",
url: '{!! url() !!}/admin/upload/multifile',
cache: false,
data : dataString,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server it
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
</script>