Laravel is sending GET instead of POST request - php

I have a problem with Laravel and POST request. My route is defined as POST and method used in AJAX is POST but it keeps sending GET requests. If I change route to undefined route then it sends POST, but if I aim to this route defined as POST it sends GET request.
AJAX:
$.ajax({
method: "POST",
url: "{{ url('admin/rentacar/save_availability_for_d') }}",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: $(form).serialize(),
dataType: "json",
success(result){
//
}
});
Route is defined as:
Route::post('save_availability_for_d', [
'as' => 'save_availability_for_d',
'uses' => 'RentacarController#saveCarAdjustment'
]);
CSRF token is included in meta tags:
<meta name="csrf-token" content="{{ csrf_token() }}">
This is what happens in console when I try to send AJAX request:
XHR finished loading: GET "http://www.carsrental.me/public/me/admin/rentacar/save_availability_for_d".
and this is what happens if I append just one random character at the end to aim for route that doesn't exists
XHR failed loading: POST "http://www.carsrental.me/public/admin/rentacar/save_availability_for_dd".

This might not be a Laravel thing. I've seen this happen if the server-configuration is a little off. What was happening was the site was set to be https, and the Apache config was set to redirect http, port 80, requests over to port 443. But in the process, it was losing track of the request-method (and the GET arguments).
Not certain this is your exact problem, that's kind of an all-or-nothing thing. But it might be worth a look.

As #Claymore has pointed out in the answer above, it's almost always how your server is configured and how you call the API/route. If server is configured to only allow https(port 443) requests, any http(port 80) POST request will be redirected to https by the server and received as a get request.
This was my main problem because we had recently installed ssl certificates and didn't change the API call protocol from our mobile app, which resulted in failed/undesired requests.

Try this and also don't forget to clear the cache
$.ajax({
url: '{{route('save_availability_for_d')}}',
dataType: 'json',
type: 'POST',
data: $(form).serialize(),
success: function (result) {
}
});

Very interesting effect that hasn't been described here, yet:
In my case, my URL contained a slash "/" at the end.
Like this:
$.ajax( '/my-function/', {
type: 'POST',
data: {
'xxx': '{{ $yyy }}',
'_token': '{{ csrf_token() }}'
}
}).done(function(data){
console.log('DONE data: %o', data);
if(data) {
...
}
}).fail(function(data){
...;
}).always(function(data){
...;
});
The redirect from a POST to a GET was done (by jquery, btw), and I was puzzled.
Removing the slash at the end of the URL fixed it.
I.e. like this:
$.ajax( '/my-function', {
type: 'POST',
data: {
'xxx': '{{ $yyy }}',
'_token': '{{ csrf_token() }}'
}
}).done(function(data){
console.log('DONE data: %o', data);
if(data) {
...
}
}).fail(function(data){
...;
}).always(function(data){
...;
});

Related

Send image with formData to Laravel using AJAX (405 Error)

I would like to send an image with jquery ajax method to my server where laravel is installed but get a 405 Method not allowed error.
I also tried to create an "any" root, but still won't work.
Also with all other posts on this topic I couldn't solve my problem.
So here is my javascript code.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = new FormData();
data.append('file', resp);
$.ajax({
url: '/images/store',
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data, textStatus, jqXHR) {}
});
on the Server side i use the Resource controller of laravel so this is the snippet from my routing file.
Route::resource('images', 'ImageController');
I think the store method of laravel is a post route, but as mentioned above also with an any route I get the 405 error.
In fact, according to the laravel 5 doc : https://laravel.com/docs/5.4/controllers
If you want to use the store() method in your controller, you will just need to sent the request to "/images" (but not "/images/store") with the POST method

Angular http get params aren't getting through

I notice my get-data isn't passed through in my GET request. I've stripped it down to:
$http({
url: "http://www.myurl.com/somefolder/demo.php",
method: "GET",
data: { info: "lala"},
timeout: 5000
})
.then(function (res) {
var data = res.data;
console.log((data));
},function (error) {
alert("Something went wrong");
})
demo.php only contains:
<?php var_dump($_GET) ?>
It does work when I visit the URL with my browser, but via the http-get, everything seems fine but the data is never past.
console.log(data) always returns array(0) {} as if I didn't send any data.
Don't know if this is relevant, but I'm using this in an Angular based Ionic-app, and I'm testing it in my browser.
It's puzzling me for hours now...
In the configuration object, data represents the body of the request (Used by a POST request for example). It seems that you want to add parameters to the URL. You should use params key instead.
$http({
url: "http://www.myurl.com/somefolder/demo.php",
method: "GET",
params: { info: "lala"},
timeout: 5000
})
More details here: https://docs.angularjs.org/api/ng/service/$http#usage

Angular $http post not posting variable correctly for PHP

I have a PHP service at api/add in my application, and you can pass it rq and name via POST. rq tells the service what function to perform, so in my example addCity is defined, and it inserts a city into the database, and name is the name of the city.
So, with that being said, here is my angular code. I'm defining an angular module above with ngRoute.
whereApp.controller('AddCityCtrl', function($scope, $http) {
$scope.addCity = function() {
$http({
method: "POST",
url: '/api/add/',
data: { rq:'addCity', name: $scope.name },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
});
/*
$.ajax({
url: "/api/add/",
type: "POST",
data: { rq: 'addCity', name: $scope.name },
dataType: "json"
})
.success(function(data) {
console.log(data);
});
*/
}
});
Here's the problem. The ajax request (jQuery style that is commented out) works. I'm wanting to use the angular style since, well, it's what I'm using and what I'm trying to learn a little bit more about. The jQuery ajax call gives me back the success message that I have from server-side, and the $http method says that the rq variable is not defined, which I'm accessing via $_POST['rq'].
I've done some research already on Google, but so far have only come up with adding headers: {'Content-Type': 'application/x-www-form-urlencoded'} like this post says.
Can anyone tell me what the difference is between these two ajax calls (or if there is something else I haven't considered)?
Since it is json data that is being sent in php you cant get it by simple $_POST you need to do this kind of stuff to get this posted data
$data=file_get_contents('php://input');
$dataobj= json_decode($data);
Here you get data first then decode it from json to normal object

404 not found when posting to localhost

When a user enters some details I am trying to add them to the database via a POST to a file called registerNewUser.php However the POST never succeeds. I'm simply given a 404. Here is the post code:
$http({
method: 'POST',
url: '../../php/login/registerNewUser.php',
data: newUser,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status) {
console.log("success");
}).error(function(status) {
console.log("ERROR");
});
I have tried moving setting the url to /registerNewUser.php and moving registerNewUser.php to the base directory but still no luck. Any help would be greatly appreciated.

AJAX headers ending up in HTTP_ACCESS_CONTROL_REQUEST_HEADERS on PHP side

I'm trying to get the SalesForce Rest API to work and I've debugged my problem down to this point:
When I make an AJAX call from my web app to my back-end (which is on a different domain than the backend), all of the AJAX headers end up crammed into $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] and there is no way for me to get access to their values.
return $j.ajax({
type: 'POST',
url: my_endpoint_url,
cache: false,
processData: false,
data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken,
success: callback ,
error: error ,
dataType: "json",
beforeSend: function(xhr) {
if (that.proxyUrl !== null) {
xhr.setRequestHeader('SalesforceProxy-Endpoint', url);
}
}
});
On the server side, I only receive:
[HTTP_ACCESS_CONTROL_REQUEST_HEADERS] => accept, salesforceproxy-endpoint, doiwork, origin, content-type
How can I access the value of "salesforceproxy-endpoint" over on the server side? Likewise, I can't seem to find the "data" of the ajax call anywhere..
UPDATE: Just for giggles I moved my end-point to the same domain. Now it is working as expected.
[HTTP_SALESFORCEPROXY_ENDPOINT] => https://login.salesforce.com//services/oauth2/token
Is there any way to get this working cross domain?
You just got aware what the Same origin policy is ;)

Categories