Laravel 5 - AJAX image upload with CSRF protection - php

I have a form set up to upload an image. I was previously using DropZone.js which worked fine and sent the CSRF token along with the ajax call. Everything server side is fine, but when trying to do this without DropZone I am getting token mismatch errors.
This is my AJAX call:
$(document).on('submit', ".hidden-image-upload", function(e){
e.preventDefault();
$.ajax({
url:'/project/uploadImage',
data:{
data:new FormData($("#upload_form")[0]),
},
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
And this is the HTML:
<form method="POST" action="http://localhost/project/create" accept-charset="UTF-8" class="hidden-image-upload">
<input name="_token" type="hidden" value="5lgtt8AgbeF3lprptj8HNXVPceRhoJbqBeErBI1k">
<input class="cover-image-upload-button" name="file" type="file">
</form>
How do I go about sorting out my AJAX call / Laravel to work together?

You can send the token in headers using $.ajax.
$(document).on('submit', ".hidden-image-upload", function(e){
e.preventDefault();
$.ajax({
url:'/project/uploadImage',
data:{
data:new FormData($("#upload_form")[0]),
},
headers: {
'X-CSRF-Token': $('form.hidden-image-upload [name="_token"]').val()
}
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
In the worst case, disable CSRF check in that route, just add the route in the array $except inside app/Http/Middleware/VerifyCsrfToken.php

Try this. You must also pass your CSRF Token along with your FormData:
$(document).on('submit', ".hidden-image-upload", function(e){
e.preventDefault();
var data = new FormData($("#upload_form")[0]);
data.append('_token', $('input[name="token"]').val());
$.ajax({
url:'/project/uploadImage',
data:{
data: data,
},
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});

Related

CSRF token mismatch when setting processData: false, contentType: false,

Hey guys I'm trying to send files to Laravel server using ajax for that i need to create form data and send it with the ajax request and in order to prevent illegal invocation i need to set these
processData: false,
contentType: false,
heres my code->
$("#saveChanges").click(function () {
let formData = new FormData();
formData.append("banner", $("input[name='banner']"));
$.ajax({
url: "/save/website/data",
type: "POST",
data: {
pickUpBtnColor: $("input[name='pickUpBtnColor']").val(),
banner: $("input[name='banner']").val(),
logo: $("input[name='logo']").val(),
_token: $('meta[name="csrf"]').attr("content"),
formData: formData,
},
processData: false,
contentType: false,
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
},
});
});
But when i set these my csrf is also ignored and the server responds with "CSRF token mismatch."
Any one has a solution?
The issue is because you need to place all the form field values within a single FormData object and send that in the request.
$("#saveChanges").click(function() {
let formData = new FormData();
formData.append("banner", $("input[name='banner']"));
formData.append('pickUpBtnColor', $("input[name='pickUpBtnColor']").val());
formData.append('banner', $("input[name='banner']").val());
formData.append('logo', $("input[name='logo']").val());
formData.append('_token', $('meta[name="csrf"]').attr("content");
$.ajax({
url: "/save/website/data",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
},
});
});
Note that you could potentially simplify this if your input elements are contained within a form; hook to the submit event of the form element instead of the click of the button, and then call let formData = new FormData(referenceToYourFormHere);. There is no need for the append() calls when using the constructor in this manner.

405 error in laravel 5.6

im sending a form data via ajax to the server using laravel 5.6
when sending the data to the server, i have specified the method of ajax to POST and the routing method in web.php to post too, the problem is, ajax sendS the form data with GET method not POST. what should i change???
ajax code
var form = $('#personPersonalInfoForm')[0];
var formData = new FormData(form);
$.ajax({
url:"/addNewPerson",
Type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data)
{
alert(data);
}
});
web.php code
Route::post('/addNewPerson', 'adminController#addNewPerson');
Here is an example of working code using the FormData.
Using the "method" configuration instead of "type".
var form = document.getElementById("ajaxForm");
var formData = new FormData(form);
var url = form.action;
$.ajax({
method : 'POST',
url : url,
data : formData,
contentType: false,
processData: false
}).done(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
Dont forget to add the CSRF token in the form.
<form method="POST" action="/addNewPerson" id="ajaxForm">
#csrf
...
</form>
Or configure the ajax method from the start with it.
in the < head> add
<meta name="csrf-token" content="{{ csrf_token() }}">
and in the JavaScript add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
web.php
Route::post('/addNewPerson', 'adminController#addNewPerson')->name(admin.add_new_person);
in your adminController :
public function addNewPerson(Request $request){
// you can check request parameters
//return response()->json($request->all());
// add new person code here ...
return response()->json(array('status'=>'success','message'=>'person added'));
}
your ajax code should be :
$.ajax({
url:"/addNewPerson",
type: "POST",
data:$('#personPersonalInfoForm').serialize(),
dataType:'json',
contentType: 'application/json',
success: function(data)
{
alert(data);
},
error:function(){
alert('ERROR');
}
});

CodeIgniter Upload File Ajax not working

No matter what I do I can't seem to get a file to upload via AJAX to CodeIgniter method. It always throws and never sees an uploaded file.
HTML
<div>
<h1>Upload Your Translation</h1>
</div>
<form method="POST" class="myForm" enctype="multipart/form-data">
<!-- add your span and pther stuff here-->
<input type="file" id="foto1" name="userfile" />
<input type="button" value="submit" onclick="submitFile();" />
</form>
<script>
function submitFile(){
var formUrl = "/system_administration/AJAX_upload_translation";
var formData = new FormData($('.myForm')[0]);
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data, textSatus, jqXHR){
//now get here response returned by PHP in JSON fomat you can parse it using JSON.parse(data)
},
error: function(jqXHR, textStatus, errorThrown){
//handle here error returned
}
});
}
</script>
PAYLOAD
Request Method:POST
Status Code:200 OK
------WebKitFormBoundaryvkN2BT8ZDxXmKj7Y
Content-Disposition: form-data; name="userfile"; filename="clippy-windows-8-10.jpg"
Content-Type: image/jpeg
function AJAX_upload_translation()
{
if (!isset($_FILES['userfile']['error']) || is_array($_FILES['userfile']['error']))
{
throw new RuntimeException('Invalid parameters.');
}
}
Try this code..
$('#upload').on('click', function() {
var file_data = $('#foto1').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'your_upload_php_file', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
Set form action path and use this for ajax(better not to use onclick function)
$(document).on("submit", ".myForm", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set form action url at your form
type: $(this).attr("method"),//set form method at your form
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});

Upload file using jquery ajax, and get result in $_FILES

How to upload file using, I tried this but it's not working and also not giving me the result in $_POST on result page.
$.ajax({
type:'post',
url:'../investor/archive2.php',
enctype: 'multipart/form-data',
tmp_dir:'tmp',
//dataType: 'json',
processData: false, // Don't process the files
//contentType: false,
cache: false,
data:'action='+action+'&title='+title+'&datetime='+datetime+'&name='+docfile,
success:function(result){
alert(result);
}
});
You must use Form data if you are using AJAX.
var data = new FormData()
data.append( 'photo', $('#photo')[0].files[0] ); //photo is the name and id of the <input type="file">
data.append( 'action', action);
data.append( 'title', title);
.
.
$.ajax({
type: "POST",
url: "../investor/archive2.php",
processData: false,
contentType: false,
cache:false,
data: data,
success: function(data){
alert(data);
}
});
You can use jQuery form plugin to handle file uploads through Ajax, files data will be available at the action under $_FILES if you submit a form using that plugin through Ajax.
Plugin Link: http://malsup.com/jquery/form/
Sample Code:
$('#form_id').ajaxForm(function(data, status, jqXHR) {
console.log(data);
});

AJAX post not working

I'm using jQuery and Codeigniter to update the database via AJAX. The following code does not seem to do anything or send anything to my controller when the button is clicked...
jQuery:
$("#button_submit1").click(function(e) {
$.ajax({
type: "POST",
url: window.location.href,
dataType: "json",
data: $('#writereview_form').serialize() + '&ajax=true',
cache: false,
success: function(data) {
alert("yay");
//$("#writereview_box").fadeOut(1000);
}
});
return false;
});
HTML:
<form action="http://mysite.com/places/writereview/2107" id="writereview_form" method="post" accept-charset="utf-8">
...
...
<input type="submit" name="submit" value="Submit Review" class="button_submit" id="button_submit1">
Any ideas why the ajax data is not being sent?
In this case its better to bind to the 'submit' event on the form and then use preventDefault() to stop the HTML submission and use Ajax instead.
You should also use the form's action instead of window.location
$("#writereview_form").submit(function(e) {
var $this = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: $this.attr('action'),
dataType: "json",
data: $this.serialize() + '&ajax=true',
cache: false,
success: function(data) {
alert("yay");
//$("#writereview_box").fadeOut(1000);
}
});
});
Try withiut using window.location.href and giving url as url: "page.php",

Categories