Laravel cannot access FormData from an HTTP POST request? - laravel

I'm having trouble getting values from my request when I set the content-type as multipart/form-data, but when I set the content-type as application/x-www-form-urlencoded everything works as expected. The values seem empty.
The request I sent via Postman:
Laravel API snippet:
use Illuminate\Http\Request;
...
public function foo(Request $req){
echo $req->get('some_key');
}
I've tried extracting the values via $req->get('key_name'), $req->key_name but to no avail. Calling the $req->all() method gives me the array with correct content but I have trouble extracting the values from it as well, is there a simpler way to achieve this? Thanks in advance.

When using multipart/form-data, set the action to PUT or PATCH and be sure to use the FormData object client side:
let Data = new FormData();
// using vuejs as an example of appending files.
Data.append( 'your_file', this.$refs.input.files[0], this.$refs.input.files[0].name );
Data.append('_method', 'PATCH');
axios.post('/api/foo', Data ).then( Response => {
// handle success
});

Related

How can I get the signature image from this signature pad with Vuejs + Laravel

Hi I have this signtaure pad with Vuejs:
Signature pad code
I am trying to send this data into a controller to store it, but when I do this:
const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
console.log(isEmpty);
console.log(data);
let formData = new FormData();
formData.append('signtaure', this.$refs.signaturePad.saveSignature());
axios.post('/api/employee/update/27141399-8?api_token='+App.apiToken, formData, config)
.then(function (response) {
currentObj.success = response.data.success;
})
If I check the console.log() it displays this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABioAAAJxCAYAAADcoOoFAAAAAXNSR0IArs4c6QAAIABJREFUeF7s3c+LrUmaF/AYN25GqkXGndbIbEQYSxQUV+WAi9lIzT8g1S5ddbkQXAhVsxSErlq7qGpcupgqcCHCYNfGhQhjLcQfMM604CC6GAsFR8Fp+eL7jNGnT96b92bmiXif83khOXnvPXki4vNEZla93xMRPzNcBAgQIECAAAECBAgQIECAAAECBAgQIECAAIFFAj+zqF3NEiBAgAABAgQIECBAgAABAgQIECBAgAABAgSGoMIkIECAAAECBAgQIECAAAECBAgQIECAAAECBJYJCCqW0WuYAAECBAgQIECAAAECBAgQIECAAAECBAgQEFSYAwQIECBAgAABAgQIECBAgAABAgQIECBAgMAyAUHFMnoNEyBAgAABAgQIECBAgAABAgQIECBAgAABAoIKc4AAAQIECBAgQIA
I check the laravel controller to get the file like this:
$request->signature;
And it is empty.. a blank value so I wonder how can I send the base_64 image with vuejs to the controller because how I am doing it does not work
You append the signature to the formdata object like this:
formData.append('signtaure', this.$refs.signaturePad.saveSignature());
In the laravel controller you're checking for the signature property on the request object.
Notice the typo you've made within the append function? signtaure != signature.
#julianstark999 also made a comment about this, but I think you misinterpreted his comment, so I'm explaining it again :)

Http PUT volley. Parameter in the middle of the url

I am using Volley for my HTTP requests and I have an HTTP put URL which looks like below.
http://mycompany.com/favorite/{roomNumber}/count. I am using a JSON object request. How do I make the API work with the extra "/count" in the API? I am passing the parameter room number in the JSON object.
JSON Object request works fine with this type of URL "http://mycompany.com/favorite/{roomNumber}"
JSON Object request
JsonObjectRequest request = new JsonObjectRequest(METHOD_TYPE_PUT, url, jsonObjectParams, responseListener, errorListener)
Can somebody help me with passing the JSON object parameter in the middle of the URL
Thanks.
You can call the API dynamically like this,
private void getTheApiData(int roomNumber){
JsonObjectRequest request = new JsonObjectRequest(METHOD_TYPE_PUT,
"mycompany.com/favorite" + roomNumber + "/count",
jsonObjectParams, responseListener, errorListener)
}
and call the above API dynamically by the method when you get the new data every time like this.
getTheAPiData(20) //if room number is 20
let me know if you have any issue #Shravani

Laravel HTTP Client does not work with empty body but Postman works

So I'm having an interesting issue with Laravel HTTP Client while trying to hit an API endpoint for PayPal.
I can get Laravel HTTP Client working on all my endpoints that POST with data, but this one endpoint that only requires headers (no data is passed in the body) fails with an error.
{
"name":"INVALID_REQUEST",
"message":"Request is not well-formed, syntactically incorrect, or violates schema.",
"debug_id":"609388c4ddfe4",
"details":[
{
"field":"\/",
"location":"body",
"issue":"INVALID_SYNTAX",
"description":"MALFORMED_REQUEST_JSON"
}
],
"links":[
{
"href":"https:\/\/developer.paypal.com\/docs\/api\/orders\/v2\/#error-INVALID_SYNTAX",
"rel":"information_link",
"encType":"application\/json"
}
]
}
When I hit the same endpoint in Postman everything works fine
My method for hitting the endpoint looks like this
public static function capture($order)
{
$token = Paypal::fetchToken();
$api_url = config('services.paypal.api_url') . '/v2/checkout/orders/' . $order['id'] . '/capture';
$headers = [
'Content/Type' => 'application/json',
];
$response = Http::withToken($token)
->withHeaders($headers)
->post($api_url)
->json();
return $response;
}
I have tried passing an empty array in the post request like this ->post($api_url, []) but that did not work either.
I have hardcoded the $api_url just in case I made a mistake with my formatting with variables. Resulted in the same issue.
I have tried changing the 'Content/Type' in the header to 'none'. This did not work either and also doesn't make sense because I have this same header set in postman and it works fine (PayPal docs also says to pass this content/type)
Based on the error I am receiving I can only assume the request is hitting the endpoint correctly, but either the HTTP wrapper or guzzle itself is adding something to the body when I leave it blank and it is causing PayPal to throw the error. Don't really know what else I can try though.
Is there a parameter I am overlooking for specifying an empty body on a post request?
Any help is appreciated.
Looking at the source I found the following solution
$response = Http::withToken($token)
->withHeaders($headers)
->send("POST", $api_url)
->json();
I had the same issue, but I fixed it with a simple trick.
I found the solution on https://docs.guzzlephp.org/en/stable/request-options.html#json.
This code should work.
$response = Http::withToken($token)
->withHeaders($headers)
->post($api_url,['json' => []])
->json();
The empty array is now seen as an empty array/body in JSON.

How to map URL in iron-ajax call to server with that of routes in server-side index.js?

<iron-ajax id="ajax_call_send_student_feedback" url="/student/feedback" handle-as="json" content-type='application/json' method="POST" body="{{student_feedback_body}}" on-response="ajax_response_student_feedback" on-error="ajax_error_student-feedback"></iron-ajax>
The above is my ajax-call to post body to server.As am running locally my url when this call is made is localhost:3000/student/feedback.
On the server-side , I have this following route to take care of the above ajax-call
app.post('/student/feedback',function(req, res) {
var body = _.pick(req.body, 'student_loginID', 'student_feedback_subject', 'student_feedback_message');
res.json(body);
});
But as soon as I make the ajax call , following error is shown on client-side.
POST http://localhost:3000/student/feedback 400 (Bad Request)
I have already checked the API end-point via Postman. So , there is some problem in the URL which I am not getting.
Ask for any other information , if I haven't provided.
this is probably a problem with your server route. inspect what's being sent to the server and how you're modifying that data.
log the value of body before your response returns json
send back a piece of hard-coded json
app.post('/student/feedback',function(req, res) {
var body = _.pick(req.body, 'student_loginID', 'student_feedback_subject', 'student_feedback_message');
console.log(body)
res.json({"foo": "bar"});
});

Using the return json code

I'me trying to use ajax with php, I have the follogin script in php :
<?php
// this file get the POST infor sent by a AJAX request and will return the value is succesful.
$price['name'] = "Called";
$price['Wheel'] = 75.25;
$price['Tire'] = 50.00;
echo json_encode($price);
?>
and I'm calling this code from my main page in the following way :
$.post("ajax/profileMod.php", {
'lname':lname,
'fname':fname,
'mname':mname,
'language':language,
'title':title,
'ptype':ptype,
'vip':vip,
'vreason':vreason
})
// Retreive the data from the php script
.done(function(data) {
// php code : echo json_encode(array("name"=>"Called!"));
alert(data);
}, "json");
// Stop original behavior
return false;
});
The returniong result from the alert is the following test :
{"name":"Called",Wheel":75.25,"Tire":50}
How can I change this result so I may use it in the following way in javascript EX:
alert(myresult['Name']) ; Would give me "Called".
So I basicly would like a associative array in javascript, but I read somewhere on this forum that you can't have associative array in Javascript, only object...
Please help!
Pass "json" as the last parameter to .post() to tell jQuery to parse the response as JSON.
(or, fix your server to return the correct Content-Type of application/json, and jQuery should do that automatically)
You will then get a Javascript object, allowing you to write
alert(result.name);

Resources