read JSON data sent using post in jquery with laravel framework - php

I have this codes,
var obj = '{"items":[{"Code":"c101","Description":"Car"}]}';
$.post('get-items',obj,function(){
});
I used this code,
file_get_contents('php://input')
Because I cant get the POST Data that is sent.
Using the above code, I get the raw POST Data.
How can I read data sent without using file_get_contents('php://input')?
Because I can't use file_get_contents('php://input').
Here is my Laravel controller function,
public function getItems()
{
$data = file_get_contents('php://input');
if(isset($data))
{
...
}
}

Laravel 5.3 expects input to be sent in array format https://laravel.com/docs/5.3/requests#retrieving-input
Request sent through jQuery
$.ajax({
url: 'http://weburl.com/api/user/create',
dataType: 'json',
type: 'POST',
data: {'user': user},
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(null, status, err.toString());
}.bind(this)
});
Laravel UserController::create
public function create(Request $request)
{
$user = new User();
$user->name = $request->input('user.name');
$user->email = $request->input('user.email');
$user->password = $request->input('user.password');
$user->save();
return response($user, 201);
}

In a Laravel 5.2 controller's method you could do this:
public function store(Request $request)
{
$items = $request->input('items');
return [
'error' => false,
'items' => $items
];
}

Related

Laravel 6 - Ajax - retreiving file - Internal error 500

I'm trying to fetch file via ajax from the laravel storage (I don't want to use the public folder as the docs should be only available for the admins). So the Ajax function calls a Route (post) , which calls the controller function to respond, but getting 500 internal server error in the console all the time.
If I dd() the request, or some string right in the begining of the controller function I get that back as output. so the request actually happens with the proper data. CSRF tokens are included.
The route:
Route::post('/tes/admin/filter/docview/', 'AdminTravelExpenseController#showdoc')-
>name('admin.tes.displayDoc');
The controller:
public function __construct()
{
$this->middleware('auth');
//adminvalidator here
}
public function showdoc(Request $request){
$item = \App\TravelExpense::find($request['id']);
if($request['src'] == 1){
$url = $item->doc_url1 ;
}
else{
$url = $item->doc_url2 ;
}
if (!Storage::disk('local')->exists($filePath)){
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return \Response::json($response);
}
And the ajax:
$('.docview').on('click',function(){
var id = $(this).data('id');
var src = $(this).data('src');
var form_data = new FormData();
form_data.append('id', id);
form_data.append('src', src);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/tes/admin/filter/docview/',
type: "POST",
processData: false,
contentType: false,
data: form_data,
success: function(data){
console.log(data);
$('.docDisplay').html(data);
}
});
});
Not sure what I'm missing here.
Thanks for the help in advance!

Rendering view after changing Locale by Ajax in Symfony 4

I am trying to change page language by a dropdown. Dropdown is generated by this code {{ form_widget(registrationForm.locale, { 'attr': {'onChange': 'languageChange()'} }) }} in the twig.
Ajax function
function languageChange() {
let selectedLanguage = $('#email_form_locale').val();
$.ajax({
url: '{{ path('change_locale') }}',
type: 'POST',
dataType: 'json',
data: {'selectedLanguage': selectedLanguage},
async: true,
success: function(data, status) {
console.info(data);
location.reload();
},
error : function(xhr, textStatus, errorThrown) {
alert('Ajax request failed.');
}
});
}
Controller function
/**
* #Route("/registration/changeLocale", name="change_locale")
* Method({"GET","POST"})
*/
public function changeLocale (Request $request)
{
$user = new User();
$form = $this->createForm(EmailFormType::class, $user);
if ($request->isXmlHttpRequest()) {
$jsonData = array();
$temp = $request->request->all();
$jsonData[0] = $temp;
$request->getSession()->set('_locale', $temp['selectedLanguage']);
$request->setLocale($temp['selectedLanguage']);
$jsonData[1] = $request->getLocale();
$user->setLocale($temp['selectedLanguage']);
return new JsonResponse(array(
'jsonData' => $jsonData,
'html' => $this->renderView('main/registration.html.twig', array('registrationForm' => $form->createView()))
)
);
} else {
return $this->render('main/registration.html.twig');
}
I am trying to render the view after Jason response. Then the page must be selected languge( I have added the translation module and words for certain languages in translation folder and If I change the locale in services.yaml languages are changing)
Please help me to do this.
I guess that's what you look for ?
https://symfony.com/doc/current/translation/locale.html
If you follow what's explained here, it should set the Locale for the whole Translation component during that request. So all your translated labels will change.

Laravel x AngularJS $http.post authentication issue

I've successfully sent some information through AngularJS to my backend in Laravel, however, I'm facing some issues while trying to get some authenticated user data.
Basically, it just don't retrieve any authenticated user data from my backend.
AngularJS
$scope.generatePrescription = function () {
//check for token in meta tag
var csrf_token = $('meta[name=csrf-token]').attr('content');
console.log('CSRF_TOKEN =>'+csrf_token);
info = {
_token: csrf_token,
receita: $scope.receita,
receita_info: $scope.receita_info
};
$http({
method: 'POST',
url: apiURL + '/prescription/create',
data: info,
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(
function(response){
console.log(response.data)
},
function(error){
console.log(error.data)
}
);
}
Api.php (Laravel)
Route::middleware('api')->post('/prescription/create','Dashboard\PrescriptionController#store');
PrescriptionController.php
public function store(Request $request, Prescription $prescription)
{
//receive prescription object
$data = $request->json()->all();
if(auth()->check()){
return 'authenticated!!!';
} else {
return 'user is not authenticated..';
}
}
How should I proceed to get my authenticated user variables?
Thank you in advance.

laravel ajax request params yields null

I am new to laravel framework and started following the laravel tasks tutorial.
I am trying to pass via ajax request the name of the task in order to save it in the database.
front end:
var taskdata= {
"name": $("#new_task").val()
};
//console.log(JSON.stringify(taskdata));
$.ajax({
url: '/task',
type: 'POST',
data: taskdata,
contentType: 'json',
processData: false,
success: function(result) {
alert("success");
}
});
server side:
Route::post('/task', function (Request $request) {
//die(var_dump($request->json("name")));
$validator = Validator::make(json_decode($request->getContent(), true), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
return redirect('/')
->withInput()
->withErrors($validator);
}
$task = new \App\Task;
$task->name = $request->name;
$task->save();
return redirect('/');
});
When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
Hence you could change your controller method to
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
return $validator->errors()->all();
}
$task = new \App\Task;
$task->name = $request->name;
$task->save();
return url("/");
});
and your ajax method as
var taskdata= {
"name": $("#new_task").val(),
"_token" : "{{ csrf_token() }}"
};
$.ajax({
url: '/task',
type: 'POST',
data: taskdata,
contentType: 'json',
success: function(result) {
console.log(result); // The url
},
error: function (data) {
console.log(data.responseJSON); // Here you could see the error
}
});
Here's a better way to solve that:
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
throw new ValidationException($validator); //Your error handler should send JSON or redirect as appropriate.
}
$task = new \App\Task;
$task->name = $request->name;
$task->save();
if ($request->expectsJson()) {
return response()->json(true); //Success
} else {
return redirect()->to("/");
}
});
Update:
You also need to let jQuery process the data so it constructs a proper query:
var taskdata= {"name": $("#new_task").val()};
//console.log(JSON.stringify(taskdata));
$.ajax({
url: '/task',
type: 'POST',
data: taskdata,
contentType: 'json',
processData: true, //Or remove it completely since the default is true
success: function(result) {
alert("success");
}
});

cant't query json data in laravel 5.2

I'm making a adressbook app via laravel 5.2 and vuejs, my app needs CRUD functionality, i stuck at Update part, i send the data via ajax to laravel
and i get the data in laravel but i cant update rows.
this is my method in vuejs that handle updating:
updatecontact:function(){
var contactid = this.editingcontact.id;
var contact update = JSON.stringify(this.editingcontact);
this.$http({url: '/adressbook/'+contactid, data: {contactupdate} , method: 'PATCH'})
.then(function (response) {
console.log(response);
}, function (response) {
// error callback
});
and this the method that handles ajax request in laravel(it's a PUT)
public function update(Request $request, $id)
{
$adressbook = Adressbook::findorFail($id);
$adressbook->save($request->all());
}
at last this is how the data looks like:
contactupdate: "{"id":5,"companyName":"poolad","zamineKar":"test","tel":"44044440","fax":"44044422","email"}"
A better way to do it would just be to send this.editingcontact as the data:
updatecontact:function(){
var contactid = this.editingcontact.id;
this.$http({url: '/adressbook/'+contactid, data: this.editingcontact , method: 'PATCH'})
.then(function (response) {
console.log(response);
}, function (response) {
// error callback
});
Then this update code should work:
public function update(Request $request, $id)
{
$adressbook = Adressbook::findOrFail($id);
$adressbook->update($request->all());
}

Categories