How to pass Array in symfony route? - php

I have a function in my controller that takes an array as input. The value is passed from ajax. At the moment it is not being decoded correctly.
/**
* #Route("/userLogin/{params}", name="userLogin", methods={"POST"})
* #param UserdbRepository $repository
* #param $params
* #return \Symfony\Component\HttpFoundation\Response
*/
public function userLogin(UserdbRepository $repository, $params) {
$email = $params[0];
$pass = $params[1];
print_r($params); // output correct value test#test.com
echo $params[0]; // output t
echo $email; // output t
.... rest of code
}
js:
const array = [ 'email', 'pass' ]
$.ajax({
url: `/userLogin/${array}`,
type: "post",
dataType: 'json'
})

Use Request component Symfony\Component\HttpFoundation\Request you can autowire it: public function userLogin(UserdbRepository $repository, Request $request)
Example 1: fetch params from requestBody:
$email = $request->request->get('email', null);
$email will be null if 'email' parameter not provided in request
don't forget to pass data property in your ajax request
const requestBody = {
'email': 'asd#example.com',
'pass': '123',
};
$.ajax({
url: `/userLogin/`,
type: "post",
data: requestBody,
});
Note: don't send data in json format. Also you can remove {params} from your #Route pattern and $params argument.
Example 2: fetch 'email' param from queryString:
$email = $request->query->get('email', null);
https://symfony.com/doc/current/components/http_foundation.html

Related

php/symfony: retrieving an attribute in the url for POST/PUT api

For a datatable I use in a page (webix datatable), I have to use a REST API.
My url is for example: http://localhost:8000/trial/1
In this page to make the api call I use the following:
save: "rest->{{ path('api_i_post') }}",
url: "rest->{{ path('erp_interventionapi_get', { trialid: trial.id })
With the GET method, I retrieve for a trial (/trial/1), many interventions which are loaded from a database and filled in the datatable.
With this datatable, I'm able to "add a new row". It uses the POST method (save: "rest->{{ path('api_i_post') }}")
When I add a new row, I'd like to be able to get the field trial_id filled in automatically, depending from where I add a new row in the datatable (for /trial/1, trial_id = 1) but I don't know how to retrieve this attribute (or the trial object id), in a POST and a PUT.
My postAction:
/**
* #Rest\Post("/api_i/", name="api_i_post")
*/
public function postAction(Request $request)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$trial = $request->get('trialid');
$data->setAction($action);
$data->setDaadala($daadala);
$data->setDate($date);
$data->setWeek($week);
$data->setWho($infopm);
$data->setInfoPm($comment);
$data->setComment($location);
$data->setTrial($trial);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
$lastid = $data->getId();
$response=array("id" => $id, "status" => "success", "newid" => $lastid);
return new JsonResponse($response);
$view = View::create(array("newid" => $lastid, "id" => $id, "status" => "success"));
return $this->handleView($view);
}
And my putAction
/**
* #Rest\Put("/api_i/{id}")
*/
public function putAction(Request $request)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$sn = $this->getDoctrine()->getManager();
$intervention = $this->getDoctrine()->getRepository('ErpBundle:Sponsor')->find($id);
if (empty($intervention)) {
return new View("Sponsor not found", Response::HTTP_NOT_FOUND);
}
$intervention->setAction($action);
$intervention->setDaadala($daadala);
$intervention->setDate($date);
$intervention->setWeek($week);
$intervention->setWho($infopm);
$intervention->setInfoPm($comment);
$intervention->setComment($location);
$sn->flush();
$response=array("id" => $id, "status" => "success");
return new JsonResponse($response);
}
Can you help me with this issue?
Thank you very much
Update of my code after the replys:
I have update this in my twig template:
save: "rest->{{ path('api_i_post', { trialid: trial.id }) }}",
If I look in the profiler of the ajax request, I see it is here:
Key Value
trialid "1"
But I still don't figure how to get it in my post request (the trial_id is still null right now)
I've tried the following:
/**
* #Rest\Post("/api_i/", name="api_i_post")
* #Rest\RequestParam(name="trialid")
*
* #param ParamFetcher $paramFetcher
* #param Request $request
*/
public function postAction(Request $request, ParamFetcher $paramFetcher)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$trial = $paramFetcher->get('trialid');
$data->setAction($action);
$data->setDaadala($daadala);
$data->setDate($date);
$data->setWeek($week);
$data->setWho($infopm);
$data->setInfoPm($comment);
$data->setComment($location);
$data->setTrial($trial);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
$lastid = $data->getId();
$response=array("id" => $id, "status" => "success", "newid" => $lastid);
return new JsonResponse($response);
$view = View::create(array("newid" => $lastid, "id" => $id, "status" => "success"));
return $this->handleView($view);
}
I guess you are using the FosRestBundle, if so, you can use annotations to retrieve your url parameters :
/**
* #Rest\Put("/api_i/{id}", requirements={"id" = "\d+"})
*/
public function putAction($id)
{
// you now have access to $id
...
}
If you want to allow additionnal parameters for your route but not in the uri, you can use RequestParam with annotations :
/**
* #Rest\Put("/my-route/{id}", requirements={"id" = "\d+"})
*
* #Rest\RequestParam(name="param1")
* #Rest\RequestParam(name="param2")
*
* #param ParamFetcher $paramFetcher
* #param int $id
*/
public function putAction(ParamFetcher $paramFetcher, $id)
{
$param1 = $paramFetcher->get('param1');
....
}
Be sure to check the fosRestBundle documentation to see everything you can do (such as typing the params, making them mandatory or not, etc...)
To get post value you need to do this inside your post action:
public function postAction(Request $request)
{
$postData = $request->request->all();
Then you have an array of value like:
$id = $postData['id'];
For the PUT you need this:
public function putAction(int $id, Request $request)
{
$putData = json_decode($request->getContent(), true);
And then to treieve a value like this:
$id = $putData['id'];

Symfony 3 - How to insert data from Ajax Response to Database

I am just starting to use Symfony and I just ran in to this problem and even after houers of research online I can not figure it out.
I am trying to insert data from a ajax request into my database. The ajax request works so far an send the following string
{"description":"","location":"","subject":"asdfasdfdsf","allDay":false,"endTime":"2016-11-22T07:00:00.000Z","startTime":"2016-11-22T06:30:00.000Z","user":"6","calendar":"1","offer":"1","status":"open"}
Here is my ajax request
$.ajax({
type: 'POST',
url: '{{ path('calendar_new') }}',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newAppointment),
dataType: 'json',
success: function(response) {
console.log(response);
}
});
My controller looks like this
/**
* #Route("/calendar/new", name="calendar_new")
* #Method({"GET", "POST"})
*/
public function calenderNewAction(Request $request)
{
if ($request->isXMLHttpRequest()) {
$content = $request->getContent();
if (!empty($content)) {
$params = json_decode($content, true);
$new = new timeEntry;
$new->setDescription($params->get('description'));
$new->setLocation($params->get('location'));
$new->setSubject($params->get('subject'));
$new->setAllDay($params->get('allDay'));
$new->setEndTime($params->get('endTime'));
$new->setStartTime($params->get('startTime'));
$em = $this->getDoctrine()->getManager();
$calendar = $em->getRepository('AppBundle:calendar')
->findOneBy(['id' => 1]);
$offers = $em->getRepository('AppBundle:offer')
->findOneBy(['id' => 1]);
$new->setCalendar($calendar);
$new->setOffer($offers);
$new->setUser($this->getUser());
$em->persist($new);
$em->flush();
}
return new JsonResponse(array('data' => $params));
}
return new Response('Error!', 400);
}
After i try it i get the following error
Call to a member function get() on array
So the $params varible actually returns a object with all the data inside but I don't know how to set my Database variables with these values.
I figured it out.
As mentioned by Cerad I called a method on an array which was the mistake.
Here is my now working controller.
/**
* #Route("/calendar/new", name="calendar_new")
* #Method({"GET", "POST"})
*/
public function calenderNewAction(Request $request)
{
if ($request->isXMLHttpRequest()) {
$content = $request->getContent();
if (!empty($content)) {
$params = json_decode($content, true);
$new = new timeEntry;
$new->setDescription($params['description']);
$new->setLocation($params['location']);
$new->setSubject($params['subject']);
$new->setAllDay($params['allDay']);
$new->setEndTime(new \DateTime($params['endTime']));
$new->setStartTime(new \DateTime($params['startTime']));
$em = $this->getDoctrine()->getManager();
$calendar = $em->getRepository('AppBundle:calendar')
->findOneBy(['id' => 1]);
$offers = $em->getRepository('AppBundle:offer')
->findOneBy(['id' => 1]);
$new->setCalendar($calendar);
$new->setOffer($offers);
$new->setStatus('Open');
$new->setUser($this->getUser());
$em->persist($new);
$em->flush();
}
return new JsonResponse(array('data' => $params));
}
return new Response('Error!', 400);
}

Yii2 and OAuth2 Plugin Filsh/yii2-oauth2-server: Unauthorized when sending POST data

EDIT: SOLVED
Apparently this plugin, was having some problem missing the request headers. The solution was adding
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
To the .htaccess file to make Authorizaion variable available as this issue report says:
https://github.com/yiisoft/yii2/issues/6631
I'm currently working with Yii2 and using this OAuth2 plugin (Filsh/yii2-oauth2-server) for login and to work with tokens from a mobile HTML5 app.
I've configured everything, and it's retrieving the token, but when I try to send the token via POST it throws an error.
I start by calling send() to retrieve the token.
function send(){
var url = "http://www.server.org/app/api/oauth2/rest/token";
var data = {
'grant_type':'password',
'username':'user',
'password':'pass',
'client_id':'clientid',
'client_secret':'clientsecret',
};
$.ajax({
type: "POST",
url: url,
data: data,
success:function(data){
console.log(data);
token = data.access_token;
},
})
};
Then when I perform this a call to createuser().
function createuser(){
var url = "http://www.server.org/app/api/v1/users/create";
var data = {
'callback':'asdf',
'username': 'user',
'password':'pass',
'first_name':'name',
'last_name':'lastname'
};
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
},
success:function(r){
console.log(r);
},
});
}
It returns
Unauthorized: You are requesting with an invalid credential
When I change to GET instead, it works fine.
This is my controller, I'm already using:
['class' => HttpBearerAuth::className()],
['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
As authentication method.
<?php
namespace app\api\modules\v1\controllers;
use Yii;
use app\models\OauthUsers;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;
use filsh\yii2\oauth2server\filters\auth\CompositeAuth;
class UsersController extends \yii\web\Controller
{
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
['class' => HttpBearerAuth::className()],
['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
]
],
'exceptionFilter' => [
'class' => ErrorToExceptionFilter::className()
],
'class' => \yii\filters\ContentNegotiator::className(),
]);
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new OauthUsers;
try {
if ($model->load($_POST) && $model->save()) {
return $this->redirect(Url::previous());
} elseif (!\Yii::$app->request->isPost) {
$model->load($_GET);
}
} catch (\Exception $e) {
$msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage();
$model->addError('_exception', $msg);
}
return "true";
}
}
This is my configuration object
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'tokenParamName' => 'accessToken',
'tokenAccessLifetime' => 3600 * 24,
'storageMap' => [
'user_credentials' => 'app\models\OauthUsers',
],
'grantTypes' => [
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
]
]
This is class OauthUsers
<?php
namespace app\models;
use Yii;
use \app\models\base\OauthUsers as BaseOauthUsers;
/**
* This is the model class for table "oauth_users".
*/
class OauthUsers extends BaseOauthUsers
implements \yii\web\IdentityInterface,\OAuth2\Storage\UserCredentialsInterface
{
/**
* #inheritdoc
*/
public static function findIdentity($id) {
$dbUser = OauthUsers::find()
->where([
"id" => $id
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$at = OauthAccessTokens::find()
->where(["access_token" => $token])
->one();
$dbUser = OauthUsers::find()
->where(["id" => $at->user_id])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* Implemented for Oauth2 Interface
*/
public function checkUserCredentials($username, $password)
{
$user = static::findByUsername($username);
if (empty($user)) {
return false;
}
return $user->validatePassword($password);
}
/**
* Implemented for Oauth2 Interface
*/
public function getUserDetails($username)
{
$user = static::findByUsername($username);
return ['user_id' => $user->getId()];
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username) {
$dbUser = OauthUsers::find()
->where([
"username" => $username
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
I've changed createuser too, but still receiving a 401. I'm not sure it is passing through findIdentityByAccessToken (access_token is in a different table than oauth users, thats why I'm querying it first).
Any thoughts?
I don't know the plugin you are using but what I know is that you can use the Yii2 HttpBearerAuth filter when implementing OAuth 2.0 which means using the HTTP Bearer token. And that token is typically passed with the Authorization header of the HTTP request instead of the body request and it usually looks like :
Authorization: Bearer y-9hFW-NhrI1PK7VAXYdYukwWVrNTkQ1
The idea is about saving the token you received from the server somewhere (should be a safe place) and include it in the headers of the requests that requires server authorization (maybe better explained here, here or here) So the JS code you are using to send a POST request should look more like this :
function createuser(){
var url = "http://www.server.org/app/api/v1/users/create";
var data = {
'callback':'cb',
'username': 'user',
'password':'pass',
'first_name':'name',
'last_name':'lastname'
};
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
},
success:function(r){
console.log(r);
},
});
}
Also check in the User class (the one defined in your config files and responsible of authenticating a user) check the implementation of the findIdentityByAccessToken() method. it should usually look like this (see Yii docs for more details) :
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]);
}
This is the function that will receive the token and it should return null when authentication should fail (by default findOne() returns null when no record is found) or returns a User instance to register it and make it accessible within Yii::$app->user->identity or Yii::$app->user->id anywhere inside your app so you can implement whatever logic you need inside it like checking the validity of an access token or its existence in a different table.
Apparently this plugin (Filsh/yii2-oauth2-server), was having some problem missing the request headers. The solution was adding
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
To the .htaccess file to make Authorizaion variable available as this says:
https://github.com/yiisoft/yii2/issues/6631

Symfony2 - KnpPaginator - AJAX/Embedded Controller

I'm having an issue with Knp, an AJAX request, and a filter. I think I'm doing something very wrong here, but I am not sure how exactly KnpPaginator works internally, and I don't have the time to figure it out on this project.
Anyway, basically, my page has an embedded controller which renders a table on the page. When paginator is called from twig, it returns the route to the container page, which results in paginator failing to work with my GET requests to that uri.
I'm not sure if any of you have come across this - I'm happy to listen if there is a better solution to the problem (I'm quite sure there is). Here is my code:
CONTROLLER
/**
* Just a shell page
*
* #Route("/postmanagement/index")
* #Template()
*
* #return array
*/
public function indexAction()
{
$form = $this->createForm(new FilterPostsType(), null, array(
'action' => $this->generateUrl('myblog_admin_postmanagement_filterposts'),
'method' => 'POST'
)
);
return array(
'form' => $form->createView()
);
}
/**
* Returns active posts and comments
*
* #param Request $request
*
* #return array
*/
public function defaultAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository('ModelBundle:Post')->findBy(array(
'active' => true
)
);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($posts, $request->query->get('page', 1), 10);
return $this->render("AdminBundle:PostManagement:_ajax-panel.html.twig", array(
'isPost' => true,
'posts' => $posts,
'pagination' => $pagination
)
);
}
/**
* #param Request $request
*
* #Route("/postmanagement/filter")
*
* #return array
*/
public function filterPostsAction(Request $request)
{
$form = $this->createForm(new FilterPostType(), null, array(
'action' => $this->generateUrl('myblog_admin_postmanagement_filterposts'),
'method' => 'POST'
)
);
// if ($request->isMethod('POST')) {
$posts = null;
$form->handleRequest($request);
$data = $form->getData();
$posts = $this->get('myblog.admin_manager')->filterPosts($data);
switch ($data['type']) {
case 'post':
$isPost = true;
$isComment = false;
break;
case 'comment':
$isPost = false;
$isComment = true;
break;
}
// }
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($posts, $request->query->get('page', 1), $data['maxresults']);
if (is_null($posts)) {
return new NotFoundHttpException();
} else {
return $this->render('AdminBundle:PostManagement:_ajax-panel.html.twig', array(
'posts' => $posts,
'isPost' => $isPost,
'isComment' => $isComment,
'pagination' => $pagination
)
);
}
}
I'm not posting the view here, since it is a simple render(controller(MyBundle:Controller:myAction)). As you can see, there is a form I'm submitting on the page, to filter the posts. That also poses a problem, since it seems paginator doesn't keep the query after I've run it through the filter.
Thanks for any help! I would love if someone has done this before and has come up with a better solution than my rather convoluted one (which also involves too many queries for my liking).
I figured it out.
If anyone else would like to paginate with InfiScr trigger + KNPPaginatorBundle + filter (PHP), use this JS:
/**
* Load more pagination handler
*/
var AjaxPagination = function (options) {
AjaxProt.call(this, options);
this.filter = options.filter;
this.toJoinEl = options.toJoinEl;
this.containerEl = options.containerEl;
this.navContainer = options.navContainer;
this.nextSelector = options.nextSelector;
this.uri = options.uri;
};
AjaxPagination.prototype = Object.create(AjaxProt.prototype);
AjaxPagination.prototype.init = function () {
var thisObj = this,
uri = thisObj.uri;
$(thisObj.navContainer).hide();
$(document).on(thisObj.event, thisObj.targetEl, function (e) {
e.preventDefault();
thisObj.ajaxRequest(uri);
});
};
AjaxPagination.prototype.ajaxRequest = function (uri) {
var thisObj = this,
page = $(this.nextSelector).attr('href').match(/\d+$/);
$('#filter_bets_page').val(page);
var data = $(this.filter).serialize(),
method = this.method;
console.log(data);
$.ajax({
url: uri,
data: data,
type: method,
success: function (data) {
thisObj.infiScrCallback(data);
}
});
};
AjaxPagination.prototype.infiScrCallback = function(data) {
var thisObj = this;
$(thisObj.navContainer).remove();
if (thisObj.toJoinEl) {
var filteredContent = $("<div>").append( $.parseHTML( data ) ).find( '.findable');
var newPagination = $("<div>").append( $.parseHTML( data ) ).find( 'div.pagination-hidden' );
$(thisObj.toJoinEl).append(filteredContent);
$(thisObj.containerEl).append(newPagination);
} else {
$(thisObj.containerEl).append(data).fadeIn();
}
if (!$(thisObj.nextSelector).length) {
$(thisObj.targetEl).fadeOut();
}
};

Typo3 6.2 eid AjaxDispatcher ignores Controll and action

I’m trying to get my Ajax-Function to call a certain controller inside my Typo3 extension.
After several attempts, I decided to go with the same Ajax-Dispatcher that powermail uses. It does show an output, but it completely ignores the supposed controller and action.
There are two Controllers in my Extension and so far three actions:
Category=>list
Family=>list,compare
PHP:
<?php
namespace Vendor\Myextension\Utility;
use \TYPO3\CMS\Core\Utility\GeneralUtility;
class AjaxDispatcher {
/**
* configuration
*
* #var \array
*/
protected $configuration;
/**
* bootstrap
*
* #var \array
*/
protected $bootstrap;
/**
* Generates the output
*
* #return \string rendered action
*/
public function run() {
return $this->bootstrap->run('', $this->configuration);
}
/**
* Initialize Extbase
*
* #param \array $TYPO3_CONF_VARS The global array. Will be set internally
*/
public function __construct($TYPO3_CONF_VARS) {
$this->configuration = array(
'pluginName' => 'my_plugin',
'vendorName' => 'Vendor',
'extensionName' => 'myextension',
'controller' => 'Family',
'action' => 'compare',
'mvc' => array(
'requestHandlers' => array(
'TYPO3\CMS\Extbase\Mvc\Web\FrontendRequestHandler' => 'TYPO3\CMS\Extbase\Mvc\Web\FrontendRequestHandler'
)
),
'settings' => array()
);
$_POST['request']['action'] = 'compare';
$_POST['request']['controller'] = 'Family';
$this->bootstrap = new \TYPO3\CMS\Extbase\Core\Bootstrap();
$userObj = \TYPO3\CMS\Frontend\Utility\EidUtility::initFeUser();
$pid = (GeneralUtility::_GET('id') ? GeneralUtility::_GET('id') : 1);
$GLOBALS['TSFE'] = GeneralUtility::makeInstance(
'TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController',
$TYPO3_CONF_VARS,
$pid,
0,
TRUE
);
$GLOBALS['TSFE']->connectToDB();
$GLOBALS['TSFE']->fe_user = $userObj;
$GLOBALS['TSFE']->id = $pid;
$GLOBALS['TSFE']->determineId();
$GLOBALS['TSFE']->getCompressedTCarray();
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->getConfigArray();
$GLOBALS['TSFE']->includeTCA();
}
}
$eid = GeneralUtility::makeInstance('Vendor\Myextension\Utility\AjaxDispatcher', $GLOBALS['TYPO3_CONF_VARS']);
echo $eid->run();
Ajax:
var read = 'string';
var requestData = {'value': read};
var currentUrl = window.location;
$.ajax({
url: currentUrl,
type: 'POST',
data: {
eID: "ajaxDispatcherMyextension",
request: {
controller: 'Family',
action: 'compare',
arguments: {
'test': requestData
}
}
},
dataType: 'html',
success: function(success) {
console.log('success ' + success);
$('#test').html(success);
}
});
Instead of showing family->compare the Ajax puts out category->compare. I don’t understand why.
Can someone please help? I'm working on this problem for over 2 days now...
I don't know exactly what you mean. If you want to trigger an AJAX request while clicking on a link you can do the following in the belonging view of your action. In this example the script will output the AJAX response.
1) Create a ViewHelper containing something like that:
$uriBuilder = $this->controllerContext->getUriBuilder();
$uri = $uriBuilder->uriFor(
'title',
array("param1" => $value1, "param2" => $value2),
'<controllerName>',
'<extKey>',
'<pluginName>');
return '<a id="link" href="'.$uri.'">';
2) Call the ViewHelper in your view template and add a output container div with an id.
3) Implement the JavaScript for AJAX call
function loadurl(dest, obj) {
try {
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
console.log(e);
}
xmlhttp.onreadystatechange = function() {
triggered(obj);
};
xmlhttp.open("GET", dest);
xmlhttp.send(null);
}
function triggered(obj) {
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
document.getElementById(obj).innerHTML = xmlhttp.responseText;
}
}
window.addEventListener("load", function() {
var item = document.getElementsById('link');
item.addEventListener('click', function(event) {
event.preventDefault();
var href = this.childNodes[1].getAttribute("href");
loadurl(href, 'idOfOutputContainer');
}
}
It's not implemented in 6.2 as noted in my bug report: action and controller not used in RequestBuilder.php:loadDefaultValues

Categories