How to use AJAX action in my controller method? - magento2

I'm integrating the payment module, I want to call ajax to the controller for third party API.
Does anyone know how to do it? Thanks in advance.
I've got a getAjax.php controller at
vendorName\moduleName\Controller\Index
I want to use getPrice() method with ajax.
Here is GetAjax.php
<?php
namespace vendorName\moduleName\Controller\Index;
use Magento\Framework\App\Action\Context;
class GetAjax extends \Magento\Framework\App\Action\Action {
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
) {
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
public function getPrice(){
print "heuss" ;
}
public function execute() {
/** #var \Magento\Framework\Controller\Result\Json $result */
$result = $this->resultJsonFactory->create();
return $result->setData(['success' => true]);
}
}
And this is the AJAX.js file
define(['jquery'],
function ($) {
$(document).ready(function() {
$.ajax({
url : 'Iostpaymagento/index/getAjax',
type : 'GET',
data: {
format: 'JSON.stringify'
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Error");
}
});
});
});
I am getting error like
require.js:166 Uncaught Error: Mismatched anonymous define() module: function ($) {

Magento 2 does not allow you to do that.
If you want to use that getPrice method I recommend you to create an API for that

Related

Laravel Backpack Admin CRUD Views returning 404

I had this working on a local dev environment, but now that I'm pushing it live I'm running into an error:
When I try to access my CRUD pages (/admin/images or similar), I get taken to my websites 404 page.
I uploaded the /routes/admin.php file, all my resource files, controllers, models, vendor files, public/vendor files, and probably some others I'm forgetting to mention.
Not sure if theres something in the config files for backpack I need to edit or what. Looking for some direction.
Note: I am able to access the default routes from Backpack (dashboard, login, logout)
RouteServiceProvider.php
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
protected function mapAdminRoutes()
{
Route::middleware(['web', 'admin'])
->prefix('admin') // or use the prefix from CRUD config
->namespace($this->namespace.'\Admin')
->group(base_path('routes/admin.php'));
}
Found this error in the error logs:
exception 'Illuminate\Database\Eloquent\RelationNotFoundException'
with message 'Call to undefined relationship [wheels] on model
[App\Models\WheelFinishes].' in
laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:20
But I have the relationship defined in my WheelFinishes model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
class WheelFinishes extends Model
{
use CrudTrait;
public function wheels()
{
return $this->belongsTo('App\Models\Wheels', 'wheel_id');
}
...
}
Wheels Model
namespace App\Models;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
use App\User;
class Wheels extends Model
{
use CrudTrait;
protected $table = "wheels";
protected $primaryKey = 'id';
...
public function tips()
{
return $this->hasMany('App\Models\WheelTips', 'wheel_id');
}
public function finishes()
{
return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}
public function factoryFinishes()
{
return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->where('factory_finish', '=', '1')->orderBy('order');
}
public function wheelImages()
{
return $this->hasMany('App\Models\WheelImages', 'wheel_id');
}
public function wheelImage()
{
return $this->hasOne('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}
public function profile()
{
return $this->BelongsTo('App\Models\Profile');
}
public function series()
{
return $this->BelongsTo('App\Models\Series');
}
public function vehicles()
{
return $this->hasMany('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order')->take(3);
}
public function vehicle()
{
return $this->hasOne('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}
}
routes.php
<?php
// Backpack\CRUD: Define the resources for the entities you want to CRUD.
CRUD::resource('video', 'VideoCrudController');
CRUD::resource('wheels', 'WheelCrudController');
Route::get('finishes/ajax-finishes-options', 'FinishCrudController#wheelsOptions');
CRUD::resource('finishes', 'FinishCrudController');
Route::get('albums/ajax-albums-options', 'AlbumCrudController#albumsOptions');
CRUD::resource('albums', 'AlbumCrudController');
CRUD::resource('heros', 'HeroCrudController');
If you have a separate route file you probably need to register it in RouteServiceProvider:
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
require base_path('routes/admin.php');
});

Laravel redirect to post method

To stay basic I would like to create a bookmark app
I have a simple bookmarklet
javascript:location.href='http://zas.dev/add?url='+encodeURIComponent(location.href)
I created a rest controller
<?php
use zas\Repositories\DbLinkRepository;
class LinksController extends BaseController {
protected $link;
function __construct(DbLinkRepository $link) {
$this->link=$link;
// ...
//$this->beforeFilter('auth.basic', array('except' => array('index', 'show', 'store')));
// ...
}
public function index()
{
//return Redirect::to('home');
}
public function create()
{
}
public function store()
{
return 'hello';
//$this->link->addLink(Input::get('url'));
//return Redirect::to(Input::get('url'));
}
public function show($id)
{
//$url = $this->link->getUrl($id);
//return Redirect::to($url);
}
public function edit($id)
{
}
public function update($id){
}
public function destroy($id){
}
}
in the routes.php, I created a ressource
Route::resource('links','LinksController');
and as I want to redirect /add to the store method I added
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
but it never display the hello message, in place it redirects me to
http://zas.dev/links
I also tried with
return Redirect::route('links.store');
without much success
thanks for your help
Ok I now get what you are trying to do. This will work:
Route::get('add', 'LinksController#store');
Remove:
Route::resource('links','LinksController');
and remove:
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
Sorry it took so long!
The problem is that once you Redirect::, you loose all the Input values, so you should manually give them to your controller when you do the redirect, like so :
Redirect::route('links.store', ["url" => Input::get("url")]);
Finally add an $url parameter to your store method to receive the value we give it in the previous method, like this :
public function store($url) {
$this->link->addLink($url);
return Redirect::to($url);
}

Passing the Ajax request data parameter through Zend Framework Controller to model class

I am Using the Zend Framework.
As a design pattern i am using the state design pattern.
Now as you may know, Zend Framework let's you create custom controllers, which can be used to respond to Ajax requests.
In my example i have the following ajax request
function getResponse(name){
$.ajax({
dataType: 'json',
data: {button: name},
url: 'motor/ajaxtest',
type: 'post',
success: function(response)
{
}
});
}
The function getResponse is called every time a specific button is pressed.
public function ajaxtestAction()
{
$input_in = $this->getRequest()->getParam('button');
$Lok = new Lok();
$this->_helper->viewRenderer->setNoRender();
$text = array($Lok->getMotorState());
$phpNative = Zend_Json::encode($text);
echo $phpNative;
}
The Code above is my custom response to the ajax request. I want to pass on the name of the pressed button to $Lok = new Lok(); so i can use it in the "Lok" model Class without creating a new instance of The controller in the "Lok" class
Is there anyone who might be able to help me ?
EDIT-----------------------------------
Here's my Controller :
class MotorController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
{
}
public function ajaxtestAction()
{
$input_in = array($this->getRequest()->getParam('button'));
$phpNativ1 = Zend_Json::encode($input_in);
echo $phpNativ1;
$Lok = new Lok();
echo $input_in;
$this->_helper->viewRenderer->setNoRender();
$text = array($Lok->getMotorState());
$phpNative = Zend_Json::encode($text);
echo $phpNative;
}
}
Here are my Jquery functions :
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
$("input[name=State]").val('Forwards');
});
function getResponse(name){
$.ajax({
dataType: 'json',
data: {button: name},
url: 'motor/ajaxtest',
type: 'post',
success: function(response)
{
}
});
}
$("button[name=on]").click(function() {
var d_response = getResponse('on');
});
});
And this is my Lok.php file :
class Lok
{
private $newMotor;
private $newTimer;
private $newSpeaker;
private $mySession;
private $motorState;
private $input;
public function __construct()
{
//Method instances
$newMotor = new Motor();
$newTimer = new Timer();
$newSpeaker = new Speaker();
$this->motorState = $newMotor->getMotorState();
// Declaring the Session
$mySession = new Zend_Session_Namespace();
$mySession->s_motorState = $this->motorState;
}
public function __get($mySession)
{
return $this->mySession;
}
public function __set($motorState, $mySession)
{
$this->$mySession->s_motorState = $motorState;
}
public function getMotorState()
{
return $this->motorState;
}
public function playSound($soundNumber)
{
echo "Playing sound";
}
public function resetTimer()
{
echo "Resetting timer";
}
public function setInput($input_in)
{
$this->input=$input_in;
}
}
As i've stated previously you should get the button name by calling the requests post data, this is done by $postData = $this->getRequest()->getPost()
Then, to get the output into your Model, inside your model class you would create a property as well as setter and getter method for it.
class Lok {
protected $button;
public function setButton($btn){}
public function getButton(){}
}
And then it becomes as easy as doing something like
$lokModel->setButton($postData['button'])
First of all, thanks for posting your solution.
I tried to implement your solution but unfortunaly it didnt work.
So after a good night sleep, i looked at the problem again. I think the problem is, that
$postData = $this->getRequest()->getPost() or $postData = $this->getRequest()->getParam('button')
is executed in the response itelfe.
<pre>string(2) "sr"
</pre>["Not Moving"]
This is what the JSON response looks like in The Google Chrom debugger. If you'r familliar with this Google Chrome debugger you know what i mean.
Now the button name that i want is in between the &quot tags the only problem is, getting it out of there. and being able to use it before the response is triggerd. I also tried getPost() and getParam('button') in the init() and indexAktion() Methods in the Controller but it still didn't work
public function init()
{
postData = $this->getRequest()->getPost()
$lokModel->setButton($postData['button'])
}
public function indexAction()
{
postData = $this->getRequest()->getPost()
$lokModel->setButton($postData['button'])
}
Any other ideas ?

ZF using placeholders inside plugins

I'm trying to implement a plugin that handles responses to the user on success or failure in a persistance transaction. When the response is false I use a _forward to the action that performed the form's submit and get my placeholder message shown but when the response is true I use a _redirect to the browse with the new record shown.
My problem is that when I use _redirect the browser doesn't show the placeholder message. I'll show the code here:
/**
* Plugin
*/
class Application_Plugin_PostMessage extends Zend_Controller_Plugin_Abstract
{
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$message = $request->getParam('message');
$error = $request->getParam('error');
if (null !== $message || null !== $error) {
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$placeHolder = $view->placeholder('message');
$placeHolder->setPostfix('</div>');
if (null !== $error) {
$placeHolder->setPrefix('<div class="errorMessage">')
->append($error);
}
elseif (null !== $message) {
$placeHolder->setPrefix('<div class="infoMessage">')
->append($message);
}
}
}
}
/**
* Controller
*/
class My_FooController extends Zend_Controller_Action
{
public function init()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_PostMessage());
}
...
public function browseAction()
{
...
// No message is shown here on redirect
...
}
public function newAction()
{
...
// This code shows the placeholder on _forward call
...
}
public function insertAction()
{
if(true) {
return $this->_redirect('/my/foo/browse?message='
. urlencode("success message"));
}
else {
return $this->_forward('new', null, null, array(
'error' => 'error messsage'
));
}
}
}
I can't use _forward on success because I don't want the use of [F5] key repeats the insert action
Thanks in advance
This is what Flash Messenger is for:
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelper.flashmessenger.basicusage
It stores messages in your session removing the need for passing messages as you are.

How can I use Zend_Auth with Zend_Json_Server?

Zend's JSON-RPC server doesn't seem to like sessions, and I can't seem to attach a session even by passing Zend_Session::getId() in to my RPC method and revive it with Zend_Session::setId($session_id) as I might expect.
To illustrate what does NOT work:
<?php
$server = new Zend_Json_Server();
$server->setClass('MyRPC');
?>
<script>
$(document).ready(function() {
myrpc = jQuery.Zend.jsonrpc({
url : <?=json_encode($this->baseUrl('/ajax'))?>
, smd : <?=$server->getServiceMap()?>
, async : true
});
myrpc.getIdentity(<?=json_encode(Zend_Session::getId())?>, {
success : function(data) {
alert(data.user_id);
}
});
});
// see: http://www.tanabi.com/projects/jsonrpc
</script>
and in my RPC class:
<?php
class MyRPC {
/**
* #param string
* #return array
*/
public function getIdentity($session_id) {
\Zend_Session::setId($session_id);
\Zend_Session::start();
// returns NULL
return \Zend_Auth::getInstance()->getIdentity();
}
}
It looks like this is unimplemented.