Prestashop 1.7.6.2 ajax call backoffice module - ajax

I have problem with ajax from select2 in prestashop 1.7. When I try writte something the calling is 200 but I got error "The Controller Psb2BAjaxModuleAdmin is missing or invalid."
I create Controller for test in my module
modules/psb2b/src/Controller/Psb2BAjaxModuleAdminController.php
<?php
namespace Scenario\PSB2B\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
class Psb2BAjaxModuleAdminController extends FrameworkBundleAdminController
{
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
return $this->ajaxDie(json_encode("test"));
}
public function postProcess()
{
PrestaShopLogger::addLog("MODULE CONTROLLER OK ", 1);
}
public function displayAjax()
{
$usb_search_token = $this->generateUrl("psb2bAjaxAdmin");
return $this->ajaxDie(json_encode("test"));
}
}
and in admin directory admin*********/themes/default/js
$(document).ready(function(){
$('#category_features').select2({
width: 'resolve',
ajax: {
type: 'POST',
url: usb_search_token,
dataType:'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
success: function (result) {
console.log(result);
}
} });
});
In my module i used hook
public function hookActionAdminControllerSetMedia()
{
MediaCore::addJsDefL('usb_search_token', $this->context->link->getAdminLink('Psb2BAjaxModuleAdmin'));
$this->context->controller->addCSS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/select2-full/dist/css/select2.min.css','all');
$this->context->controller->addJS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/select2-full/dist/js/select2.min.js');
$this->context->controller->addJS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/tree.js');
}

It seems your controller looks more like a 1.6+ one rather than a 1.7 with Symfony one.
I usually have an indexAction method in the controllers/Admin/my_controller.php.
In this method I use a
Media::addJsDef(array(
'usb_search_token' => admin_link));
));
Then as this method returns a
return $this->render('#Modules/rmvcolorgrid/views/admin/my_file.html.twig', [])
the URL is available for the js file in views/js/back.js.
You should have a look at PS docs for the recommended way to build this.

Related

How to return errors in Laravel Custom Request to Ajax

I made custom request as following.
class CustomRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rule['name']='required';
$rule['email'] = 'required|email';
return $rule;
}
}
How can I return validation errors in ajax?
When I didn't use custom request, I returned errors like this.
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
'name'=>'required',
'email'=>'required|email'
]
if($validation->fails())
{
return response()->json([$errors=>$validation->errors()]);
}
return response()->json(['status'=>'success']);
}
So here instead of Request, if I use CustomRequest then how can we catch errors?
Another thing.
In custom request rule, how can we get request input values?
public function rules()
{
$rule['name']='required';
if($this->input('phone')) {
$rule['phone'] = 'integer';
}
$rule['email'] = 'required|email';
return $rule;
}
$this->input('phone') Is this right?
Hope to give me answer to my 2 questions.
the error will be either in your error call back function or catch callback depends on how you make ajax call.
eg.
$.ajax({
url: "/test",
type: "post",
data: {foo:'test'} ,
success: function (response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
var data = jqXHR.responseJSON;
console.log(data.errors);// this will be the error bag.
}
for FormRequest I think your code is not correct
public function rules()
{
return [
'title' => 'required',
'body' => 'required',
];
}
This will do the validation. You do not really need to access the input value as Laravel does it for you. But for some reason, if you really want it you can always use the global helper function request()->input('title');

Is it possible to post from custom js to .module/custom.php/controller file and get response in custom js while developing custom module in drupal8?

i have this in custom.js file in drupal modules/mymodule/js/ folder
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: 'modules/mymodule/custom.php',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);
and i have to post to modules/mymodule/custom.php
<?php
echo "test";
?>
and return data from custom.php
You can do that by creating a controller for listening that ajax call
my_module.routing.yml
my_module.call_back:
path: '/my_module/call_back'
defaults:
_controller: '\Drupal\my_module\Controller\DefaultController::callBack'
_title: 'Call Back'
Controller
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Class DefaultController.
*/
class DefaultController extends ControllerBase {
/**
* Your Callback
*
*/
public function callBack() {
return ["This is a test" ];
}
custom.js
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: '/my_module/call_back',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);

Put method yields HTTP 405 (method not allowed) but works in Postman (HTTP 500)

I have created an addition to the profile settings page in Spark. The vue code:
Vue.component('update-mail-settings', {
props: ['user'],
data() {
return {
form: new SparkForm({
type: ''
})
};
},
mounted() {
this.form.mailsettings = this.user.mailsettings;
},
methods: {
update() {
Spark.put('update-mail-settings', this.form)
.then(response => {
Bus.$emit('updateUser');
});
}
}
});
I've created a route:
Route::put('/update-mail-settings', 'SettingsController#updateMailSettings');
and the Controller to handle the request. I disabled CSRF checking and as can be seen in the code beneath, also the auth middleware:
class SettingsController extends Controller{
public function __construct(){
//$this->middleware('auth');
}
public function updateMailSettings(Request $request)
{
$request->user()->forceFill([
'mailsettings' => $request->mailsettings
])->save();
return Redirect::back()->with('success', 'Successfully updated mailsettings');
}
}
I didn't show the blade with radio buttons but that doesn't seem like the source of the error.
Interestingly, when I monitor the requests in my Nginx log files I see a 405 error if I click on the update button on the website but if I use Postman, it yields a 500 code (after which it fails since it cannot assign the mailsettings variable --> "Call to a member function forceFill() on null")
Anyone have any idea?

Invalid JSON response on Laravel 5.2 and yajra/laravel-datatables-oracle

My question is very similar with Yajra Datatables Package for Laravel deosnt work properly with laravel 5.2
I get Invalid JSON response on Chrome but I couldn't view the HTTP call response.
Here is my controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Office;
use Datatables;
class OfficeController extends Controller
{
public function index()
{
return view('offices.index', ['page_title' => 'Jabatan']);
}
public function data()
{
$offices = Office::select(['id', 'title']);
return Datatables::of($offices)->make(true);
}
...
My script
$(function() {
$('#offices-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('offices.data') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'title', name: 'title' }
]
});
});
First of all you have to check what your function exactly returns. So I would suggest you to modify it like that first
public function data()
{
$offices = Office::select(['id', 'title']);
dd(Datatables::of($offices)->make(true));
}
And then go to the URL aimed to this function in your browser or use inspector to see what you get there. I think it will help you figure out whats wrong.
If it will show expected result try to modify your function like this:
public function data()
{
$offices = Office::select(['id', 'title']);
return new JsonResponse(Datatables::of($offices)->make(true));
}
And don't forget to add
use Illuminate\Http\JsonResponse;
statement before your controller class definition.

ajax post works when function is in the route, but return error 500 when route to function in controller

I'm trying to post ajax in laravel 5, but when i have the function in the controller it works fine but when i try to link to controller, it return error 500 (Internal Server Error)
my JS
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
$.ajax({
url: 'myLink',
type: "post",
data: {
'start': start.format('YYYY-MM-DD'),
'end': end.format('YYYY-MM-DD')
},
success: function(data){
alert(data);
},
error: function(){
alert("error!!!!");
}
});
My route (non working)
Route::post('/admin/getStoreIncome', 'Admin#method');
My route (working)
Route::post('/admin/getStoreIncome', function()
{
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
});
My Controller
public function method() {
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
Namespace i use for my controller
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
Am i doing something wrong here? Do i need a session namespace for the csrf? If someone have experience with this please help.
I'm not sure my answer will help you, But Through Jquery I have Done
I have a DropDown OnChange I am sending selected Value in My Controller and Then I am getting the response on my view Page
(function($) {
$('#bath').on('change', function() {
var optionSelected = $(this).find("option:selected");
var prop_type = optionSelected.val();
$.ajax({
type: "GET",
url: "baths", //my Controller Function
dataType: "json",
data: {baths: prop_type},
success:function(row)
{
$('#getRequestdata').empty('clear').html(row.html);
}
});
});
})(jQuery);
I hope it will help you!!!

Resources