Request object is empty in a lumen api - php

Uploading the image file in lumen API using ajax call, it not getting the image in the lumen for processing, the Request object is empty.
Ajax call
var file = $('#img')[0].files[0];
var form_data = new FormData(document.getElementById("myform"));
form_data.append("img", file);
$.ajax({
url: "http://localhost:8000/api/image",
type: "POST",
data: form_data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
})
.done(function (data) {
console.log(data);
});
Route
$api->post('/image', 'ImagesController#addImage');
Controller
public function addImage(Request $request) {
return $request; // returns empty object
}
Request payload
Response

In your controller add this line
use Illuminate\Http\Request;
Do not use the Request facade as Lumen works differently from Laravel.

You can build a JavaScript object this way, this will ensure passing the body to the request.
let form_data = {
'name': $('#name').value(),
'file': $('#img')[0].files[0]
};
$.ajax({
url: "http://localhost:8000/api/image",
type: "POST",
data: form_data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
})
.done(function (data) {
console.log(data);
});

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');
}
});

PHP Ajax Post File and Text Same Time

I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});

Ajax not work in android device browser

I am using ajax function for checking username and password but some android device does not support it. so what i have to do? This is my ajax function
$(function()
{
$("#loginform").submit(function()
{
document.getElementById('loading').style.display = "block";
var formData = new FormData($("#loginform")[0]);
$.ajax({
url: 'login_check.php',
type:'POST',
data: formData,
processData: false,
contentType: false,
cache: false,
mimeType: 'multipart/form-data',
success: function(html)
{
}
});
return false
});
});
Probably your issue relates not to ajax not being available, but to a bad browser response. See this.

Knockout and AJAX post request PHP

I am attempting to get our knockout form to submit to a php script and am getting undefinedIndex errors. I am pretty sure it is the way we are sending the data over in our ajax function.
Here is the ajax:
$.ajax({
url: '/orders/add',
type: 'post',
data: {payload:ko.toJSON(allModel)},
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Here is the PHP (we use laravel)
return json_decode($_POST["payload"]);
Pete is correct. You need to use just one data field. If you want a variable, define it before the $.ajax post
var dataPayload = ko.toJSON(allModel);
$.ajax({
url: '/orders/add',
type: 'post',
data: {payload: dataPayload},
contentType: 'application/json',
success: function (result) {
alert(result);
}
});

Categories