Extract parameter from route url - javascript

I want to give a parameter to an url in Ember.js and extract this parameter in the route index.js.
http://localhost:4200/7698
And then in index.js I do this:
model( params ) {
console.log( params.edition_id );
return "something";
}
Router.js file:
Router.map( function( ) {
this.route( '/index' );
this.route( '/', {
path: '/:edition_id'
} );
} );
This gives me the following error:
Error while processing route: / Ember Data Request GET undefined
returned a 404 Payload (text/html; charset=utf-8) Cannot GET /7698
Error: Ember Data Request GET undefined returned a 404 Payload
(text/html; charset=utf-8) Cannot GET /7698
However I don't want ember-data interfering with this, I simply need the parameter in my app logic, without any models or such.

you should just use
Router.map( function( ) {
this.route('index', { path: '/:edition_id' });
} );
by the way be aware if you remove # from first of url, you would get 404 error on reload your page

Related

Moralis Web3API react hook returning 400

For some reason, my getNFTsForContract web3API call keeps returning 400s, but I can't tell why. Here is what I'm using to make the call:
const { fetch, data, error, isLoading } = useMoralisWeb3ApiCall(
Web3Api.account.getNFTsForContract,
{
chain: networkId,
address: user,
token_address: retroCatsAddress,
}
)
And it looks like in my browser inspect tools that the request body of the API call is ok. I also have setup the MoralisProvider like so:
ReactDOM.render(
<MoralisProvider
appId={process.env.REACT_APP_MORALIS_APP_ID}
serverUrl={process.env.REACT_APP_MORALIS_SERVER_URL}
>
<App />
</MoralisProvider>,
document.getElementById('root')
)
But am wondering if I'm missing something. The parameters i'm passing are:
address: 0x643315C9Be056cDEA171F4e7b2222a4ddaB9F88D
chain: 4
token_address: 0xc8d8B5a3ED2aA35Df8F1781F2B06A14Fb0411bc8
And I've verified that the address in question has NFTs on the token_address.
So what am I missing?
You need to provide the chain as a string and in hex form:
const { fetch, data, error, isLoading } = useMoralisWeb3ApiCall(
Web3Api.account.getNFTsForContract,
{
chain: "0x4",
address: user,
token_address: retroCatsAddress,
}
)

Symfony: Send variable throught GET to handler from Ajax

I would like to use AJAX in my Symfony3.0.3 project.
The communication works, but I can't get variable from JS to the handler. In the direction handler to JS, it works fine.
I'm trying to get the variable from the request with "$request->query->get('id'))" but I only get "null".
In an other way I'm trying to use the variable from the URL but I get this error:
"An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("id") to generate a URL for route "admin_ajax".") in CommonBundle:Default:index.html.twig at line 421."
I don't mind using a solution or an other (I'll use the best one depending of your advices), but I still would like the solution for both error.
JS
function selectClient(idClient)//idClient = 1
{
alert(idClient);
$.post('{{path('admin_ajax')}}',{idClient: id},
function(response)
{
if(response.code == 100 && response.success)
{
alert(response.id);//Show null if using $request->query->get('id')) in handler but should be 1
}}, "json");
}
routing:
admin_ajax:
defaults: { _controller: CommonBundle:Default:getClient }
path: /ajax/{id}
handler:
public function getClientAction($id)
{
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
if ($isAjax)
{
$response = array("code" => 100, "success" => true, "id" => $request->query->get('id'));
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}
EDIT:
Thank for Rim, and Rvanlaak answer, I used the FOSJsRoutingBundle.
JS
function selectClient(idClient)
{
$.get(Routing.generate('ajax_getclient', { id:idClient }),
function(response)
{
if(response.code == 100 && response.success)
{
alert(response.id);
}
else
}, "json");
}
routing:
ajax_getclient:
defaults: { _controller: CommonBundle:Default:getClient }
path: /ajax/{id}
options:
expose: true
Note that the option "expose: true" was necessary to works.
Thats because the twig is executing before javascript so he is not reconizing the client id param
i had the same problem and resolve it using FOSJSRoutingBundle see this post :
Ajax url parametetr using Twig path

FOSJsRoutingBundle does not see a route from FOSRESTBundle

I want to access an API route to a FOSRESTBundle Controller from my JS. I'm using the FOSJSRoutingBundle, but the route is not visible (I'm getting the 'the route xxx does not exist' error.
This is an action from my controller:
namespace ApiBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Get;
class AjaxController extends FOSRestController{
/**
* #Get("/someaction", name="someaction")
*/
public function someAction()
{
$response = 'some response';
$view = $this->view($response,200);
return $this->handleView($view);
}
}
This route is accessible via curl requests and by hardcoding it in the JS file, but I don't want to hardcode it. So i tried this in the JS file (after installing the JSRoutingBundle of course):
function prepareChart() {
$url = Routing.generate('someaction');
$.get( $url, function( data ) {
<do something>
}, "json" );
}
Here is the routing.yml entry:
ajax:
resource: "#ApiBundle/Controller/AjaxController.php"
prefix: /ajax/
type: rest
options:
expose: true
I've solved the problem - the FOSRestBundle does not support the 'name' attribute - the path to my controller was autogenerated and I had to retrieve its name from list of all routes by executing php app/console debug:router in the console.

Meteor and Iron-Router Subscription Exception from Deps recompute: Error: Member already exists

Important: I'm currently working with Meteor and Iron-Router both in the SHARK branch
To abstract the problem, lets say I have two routes:
// Home
this.route('home', {
path: '/',
layoutTemplate: 'layout',
action: function() {
// Performing some animation
}
});
// User profile
this.route('profile', {
path: '/profile/:id',
controller: UserShowRouter
});
The UserShowRouter looks something like this:
UserShowRouter = RouteController.extend({
before: function() {
this.subscribe('user', this.params.id).wait();
this.subscribe('userPlaylists', this.params.id).wait();
},
data: function() {
var user = Meteor.users.findOne({
'profile.username': this.params.id
}),
var playlistsMade = Playlists.find({
'user.id': user._id
});
return {
user: user,
playlistsMade: playlistsMade,
};
},
action: function() {
this.render('profile', {
to: 'rightbarYield'
});
}
});
A user has several playlists. On the user's profile page the user data and the playlists he owns should be shown.
In the before hook I subscribe to the user and to all playlists the user owns. Here are the according publish functions:
Meteor.publish('user', function(username) {
return Meteor.users.find({
'profile.username': username
});
});
Meteor.publish('userPlaylists', function(username) {
return Playlists.find({
'user.username': username
});
});
Following problem occurs: When I visit the /profile/user page for the first time everything works like a charm. When I change from the /profile/user page to the / (home) page and then back to the /profile/user following exception gets thrown:
Exception from Deps recompute: Error: Member already exists: jzJMYRTYjG9FDqHmT
at _extend.add (http://localhost:3000/packages/ui.js?b7accb7b6966f638ff085b5d7f310d129aad8c19:1757:17)
at Object.ObserveSequence.observe.addedAt (http://localhost:3000/packages/ui.js?b7accb7b6966f638ff085b5d7f310d129aad8c19:3572:15)
at Object.diffFn.addedBefore (http://localhost:3000/packages/observe-sequence.js?c4bfebff26188a6d7bd7b902bf9ad3e3c87a0f77:196:17)
at http://localhost:3000/packages/minimongo.js?56dbd9be5b85de2aee072a05810b82c155a20d99:2649:42
at Array.forEach (native)
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?13ab483e8a3c795d9991577e65e811cd0b827997:130:11)
at LocalCollection._diffQueryOrderedChanges (http://localhost:3000/packages/minimongo.js?56dbd9be5b85de2aee072a05810b82c155a20d99:2639:5)
at diffArray (http://localhost:3000/packages/observe-sequence.js?c4bfebff26188a6d7bd7b902bf9ad3e3c87a0f77:194:3)
at http://localhost:3000/packages/observe-sequence.js?c4bfebff26188a6d7bd7b902bf9ad3e3c87a0f77:125:11
at Object._.extend.nonreactive (http://localhost:3000/packages/deps.js?34f4906d0a01d1c2873bed712b3bd039da3c9bab:341:14)
This problem does not occur when I subscribe to all playlists at the beginning in my main.js (not in the routeController) Meteor.subscribe('playlists')
But this brings along following issue: When I'm not at the profile/user route anymore, but at at the home router / and the data of one of the existing playlists changes (e.g. the title is changed) and the dependency gets recomputed following exception is thrown:
Exception in queued task: TypeError: Cannot read property 'data' of null
at Object.ObserveSequence.observe.changed (http://localhost:3000/packages/ui.js?b7accb7b6966f638ff085b5d7f310d129aad8c19:3584:52)
at Object.cursor.observe.changed (http://localhost:3000/packages/observe-sequence.js?c4bfebff26188a6d7bd7b902bf9ad3e3c87a0f77:137:25)
at Object.cursor.observeChanges.changed (http://localhost:3000/packages/minimongo.js?56dbd9be5b85de2aee072a05810b82c155a20d99:1096:19)
at http://localhost:3000/packages/minimongo.js?56dbd9be5b85de2aee072a05810b82c155a20d99:349:15
at _.extend.runTask (http://localhost:3000/packages/meteor.js?e2f7aa115469a020bb2030038d4f74b320dc9533:558:11)
at _.extend.flush (http://localhost:3000/packages/meteor.js?e2f7aa115469a020bb2030038d4f74b320dc9533:586:10)
at _.extend.drain (http://localhost:3000/packages/meteor.js?e2f7aa115469a020bb2030038d4f74b320dc9533:594:12)
at LocalCollection.update (http://localhost:3000/packages/minimongo.js?56dbd9be5b85de2aee072a05810b82c155a20d99:638:22)
at Object.self._connection.registerStore.update (http://localhost:3000/packages/mongo-livedata.js?2f66d8591aa3225badaf5a98bfba28287bff3a3d:239:30)
at Object.store.(anonymous function) [as update] (http://localhost:3000/packages/livedata.js?dab0057c9e7c90bcd874be39d89b9cd54637979b:3583:48)
I don't know where the problem lies – with Meteor? with Iron-Router? with my subscriptions or routes? Any help is highly appreciated! Thanks

How to direct multiple routes to the same method in Backbone JS?

This is my routes object in a BackboneJS app:
routes: {
"" : "_navigate",
"home" : "_navigate",
"blog" : "_navigate",
"photos" : "_navigate",
"notes" : "_navigate",
"about" : "_navigate",
"singlepost_:id" : "_navigate"
},
it redirects routes to the _navigate method, which looks like this:
_navigate: function(postId) {
if (postId) {
// show single entry
return;
}
// show regular entry
},
It works perfectly fine. However, I find the repetitive routes object to be annoying.
My question is: Is there a better way to direct all these routes to the same method without repeating yourself so much?
Thanks!
http://backbonetutorials.com/what-is-a-router/ Check out the section on splats
Any "*splats" or ":params" in route definitions are passed as
arguments (in respective order) to the associated function. A route
defined as "/:route/:action" will pass 2 variables (“route” and
“action”) to the callback function. (If this is confusing please post
a comment and I will try articulate it better) Here are some examples
of using ":params" and "*splats"
routes: {
"/posts/:id": "getPost",
// Example
"/download/*path": "downloadFile",
// Download
"/:route/:action": "loadView",
// Load Route/Action View
},
getPost: function( id ){
alert(id); // 121
},
downloadFile: function( path ){
alert(path); // user/images/hey.gif
},
loadView: function( route, action ){
alert(route + "_" + action); // dashboard_graph
}
Quite simple, really.
routes: {
"*actions:_id": "_navigate"
}
Thanks to Jason Strimpel from the BackboneJS Google Group.

Categories