Rendering view after changing Locale by Ajax in Symfony 4 - php

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.

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!

Pass a View Data From Controller to Ajax View File - Laravel 5

From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data.
I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong
CallingAjaxFromViewFile
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
alert(data);
data = JSON.parse(data);
console.log(data.html);
$('#gymimages').html(data.html);
}
});
}
}
myControllerFile
public function AjaxCurrentPastFutureData($data, $status){
$title = "HDTuto.com";
$html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
NowmyViewFile From Where I append HTML Data
<h1><i>{{ $title }} </i></h1>
Can anyone tell me where I am going wrong?
** Use this**
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
$('#gymimages').html(data.html);
}
});
Also update your Controller function
public function AjaxCurrentPastFutureData(Request $request){
$title = "HDTuto.com";
$html = view('my')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}

read JSON data sent using post in jquery with laravel framework

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
];
}

Display results in twig json

I have in my controller a function to make a search filter.
The search parameter is obtained from a select field of my twig template.
The selected option is passed to the controller to see where results are with that value.
The query result is returned in JSON format.
Controller:
public function categoryAction(Request $request)
{
$category = $request->request->get('category');
$contentCategory = $em->getRepository('MyAppBundle:Content')->findByCategory($category);
$filterContent = new JsonResponse();
$filterContent->setData([
'categoryResult' => $contentCategory
]);
return $filterContent;
}
Twig template:
$('#selectCategory').change(function() {
var optionSelect = $(this).val();
$.ajax({
url: '{{path('playlist_category') }}',
data: '&category='+optionSelect,
type: 'POST',
success: function(filterContent) {
},
error: function(e){
console.log(e.responseText);
}
});
});
How I can display the result returned in JSON in my function 'success'?
You should change your JS code to the following. I would rather user $.post than $.ajax. And don't forget to pass json as fourth arg.
$('#selectCategory').on('change', function () {
var optionSelect = $(this).val();
$.post("{{path('playlist_category') }}", {category: optionSelect}, function (res) {
console.log(res);
}, 'json');
});

Laravel AJAX Image Upload error: Image source not readable

Trying to upload an image via AJAX but having issues...
The form:
{{ Form::open(array('class' => 'update-insertimage-form', "files" => true,)) }}
{{ Form::file('image', array('class' => 'update-insertimage-btn', 'name' => 'update-insertimage-btn')) }}
{{ Form::close() }}
And the PHP:
$createImage = Image::make(Input::file('update-insertimage-btn'))->orientate();
$createImage->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$createImage->save("user_uploads/cover_images/TEST.jpeg");
jQuery:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: $('.update-insertimage-form').serialize(),
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
I use this same exact code else where which works fine but not with AJAX (not sure if that has anything to do with it)
The error is this:
{"error":{"type":"Intervention\\Image\\Exception\\NotReadableException","message":"Image source not readable","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":257}}
Any help?
You can't serialize the image and pass it over, you need to construct a FormData object and use it to send over the image.
var formData = new FormData();
formData.append('update-insertimage-btn[]', $('.update-insertimage-btn')[0].files[0], $('.update-insertimage-btn')[0].files[0].name);
Then you just need to pass it over to the server as the data along with some other options:
data: formData,
processData: false,
contentType: false
Now you can do:
Image::make(Input::file('update-insertimage-btn'))->orientate()
From the page here https://github.com/Intervention/image/blob/master/src/Intervention/Image/AbstractDecoder.php it is passing this following check:
case $this->isDataUrl():
return $this->initFromBinary($this->decodeDataUrl($this->data));
Which is returning true from that function:
public function isDataUrl()
{
$data = $this->decodeDataUrl($this->data);
return is_null($data) ? false : true;
}
which is firing the abstract function initFromBinary that is passing decodeDataUrl's result as an argument, and the decodeDataUrl looks like:
private function decodeDataUrl($data_url)
{
$pattern = "/^data:(?:image\/[a-zA-Z\-\.]+)(?:charset=\".+\")?;base64,(?P<data>.+)$/";
preg_match($pattern, $data_url, $matches);
if (is_array($matches) && array_key_exists('data', $matches)) {
return base64_decode($matches['data']);
}
return null;
}
So it seems it expects that element to be a base64 encoded image as opposed to a raw binary image; therefore, base64encode the image when you pass it along instead of passing along .files[0]

Categories