I’m using the following code to post an array of objects to an api Controller.
$.ajax({
url: "/api/links",
method:"post" ,
data: JSON.stringify( this.results ) ,
contentType: 'application/x-www-form-urlencoded',
context:this ,
success:
function(res){
$("#res").html(res);
}
});
The problem is $_POST array is empty while I could get the raw posted data using $raw = file_get_contents(“php://input”).
Somebody offered to use this:
$_POST = json_decode($rawdata, true);
It may fill the $_POST and solve the problem but I’m using Laravel so I’m supposed to use the $request (of type Request) parameter of Controller method not pure PHP.
So I think there is a right and Laravel way for handling this.
By the way $rawdata is precisely what I’ve posted to the controller which is something like this:
[{“id”:484,”LinkTitle”:”contactus”,”URL”:”https://url1…”},{“id”:485,”LinkTitle”:”faq”,”URL”:”/faq”}]
I also tried wrapping it with {} before serializing in order to make it an object:
JSON.stringify( {"myData":this.results} )
This way $_POST array was filled but not in a normal way.
All I want is to access LinkTitle via $_POST which means I would be able to use $request argument passed to controller’s method so i can do other things like validation etc…
EDIT : Like @AmeyaJoshi said it’s array of objects and not just object/array. So I can’t get it via $_POST[“LinkTitle”] . All I said here is because I imagine if $_POST is populated correctly then I can use $request to validate and save my records at once via eloquent.Thank you
EDIT2: I tried removing stringify like
katsarov said and result of print_r($_POST,true) is
Array
(
[undefined] =>;
)
and result of dd($request->all()) is
array:1 [▼
"undefined" => null
]
2
Answers
It is simple 🙂
if you have it in the method)
Considering your data structure ,
$_POST["LinkTitle"]
is not possible..LinkTitle
is key in object and you are sending array of objects. So to accessLinktTitle
key you will have to run loop on this array first.