FOSJSRoutingBundle - Routing.generate doesn't do anything - javascript

I'm facing a bit of a trouble with the FOSJsRoutingBundle in Symfony4 when trying to load a new template from my Javascript file.
I followed the instructions over here.
The route I want to call is as follow :
/**
* #Route("/", name="homepage", options={"expose" = true})
*/
public function homepage()
{
return $this->render('home.html.twig');
}
When
Routing.generate('homepage');
alert("Finished!");
in my Javascript file gets called, the alert gets displayed and nothing else happens. I should probably add that I'm obviously not on the homepage when this gets called.
However, if I purposefully misspell the name of the Route or if I call a route that has not been exposed via
options={"expose" = true}
I do get an error :
Error: The route "misspelled_route" does not exist. 2 router.js:220:27
and no alert gets displayed, which leads me to believe that I followed the instructions on the Symfony website correctly (?).
Am I missing something obvious or poorly using the bundle ?
Thank you very much !

I'm not entirely sure if I'm supposed to answer my own question like this, but if anybody has the same problem when following the Symfony website's instruction on FOSJsRoutingBundle :
Routing.generate returns a String. If you're like me and want the page to redirect, you can use
window.location.href = Routing.generate('your_route_name');
Thanks to pbenard for this !

Related

Download JSON in React

Attempted to follow this nice example in React https://jsfiddle.net/cowboy/hHZa9/ by creating a state variable that gets updated with an async call. When the link is rendered and I click on the link - it says network error.
// constructor
this.state = {
linkReady: false,
data: {}
};
// ***
show() {
return (
<a href={`data: ${this.state.data} `} download={"data.json"}>Download JSON</a>
);
}
download() {
this.props.downloadRequest({action: "download"}).then(
(obj) => {
this.setState({
linkReady: true,
data: "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj))
});
}
);
}
What am I doing wrong?
Edit
After some investigating I found that the problem is the object returned from the server is too large. I made the object smaller and it works.
Since I don't expect special characters in my object - I removed encodeURIComponent and I am able to download the large file.
If there are better solutions I would like to know.
First of all you should check if your server has secure connection, when you are making request (I assume, you making an async request upon downloadRequest).
Also, you should remove plus sign (+) in your href attribute. You are using string interpolation so you don't need it.
href={`data: ${this.state.data}`}
Another thing (I don't know how it implemented currently due to not seeing full code, but) it to be sure that link is ready - so I advice you to create some conditions before rendering link.
The last one - I've created working sandbox for you - it might help you. Click here.
Hope it helps!

Following a redirect for images in HTML

Apologies if the question isn't correctly worded, but here it goes: I currently have a website which needs to display a certain image, however, the link provided to me is a link that redirects to the image.
So think www.linktoimage.com/foo, which redirects me to my actual image's url, so for example, https://i.imgur.com/76lLZAn.png.
Unfortunately this is a requirement to the project I am working on for several reasons and I can't really think of a way to get around this.
For the record, I am using meteor with the blaze template engine, in case that helps. A way I thought of getting this done may be through using a helper, which will follow the redirect for me, and somehow grab the ultimate url. So something like this:
Template.myTemplate.helpers({
getMyImage: function (proxyUrl) {
var actualAddress
// somehow get the images actual address...
return actualAddress
}
})
Then in my html file:
<template name="myTemplate">
<div>
<img src="{{getMyImage 'proxyUrl'}}"
<div>
</template>
Of course if there is a better way to do this just through the HTML that would be fantastic too. Unfortunately right now, I am clueless on how I would get the actual URL.
Thanks!
Edit: essentially I want to do this, but using JavaScript instead of PHP.
Edit2: possibly found a way to get around this, though it is not quite working and has some problems due to it being async. Basically it would be using meteor's HTTP library:
Template.myTemplate.helpers({
getMyImage: function () {
var proxyUrl = 'http://www.tablotv.com/client-paywall-snapshots/web'
return HTTP.call('GET', proxyUrl, function (err, result){
console.warn('hereeee', result, err)
})
}
})
However I am getting the following error:
network at XMLHttpRequest.xhr.onreadystatechange
I can imagine this has something to do with it being async, perhaps? Anyway, am I on the right path now? How could I get this working?

PhoneGap Cloud Build: Correct facebookConnectPlugin installation

I'm sure this is going to be so trivial, but have had a number of tries and being the last thing I need to configure before I can deploy the private test is driving me mad.
This question extends off this question, my config.xml is established in the same way, this part is a no brainer. I have also got in my <head>:
<script type='text/javascript' src="./js/facebookConnectPlugin.js"></script>
I have tried both ./facebookConnectPlugin.js as well as ./js/facebookConnectPlugin.js, so part (a) of my question is, how can I determine what is the correct relative path without seeing the directory? I can't find its install location to verify.
Next part of the question follows the advice I received from somewhere, that instead of using the usual device ready event, to use the window.onload:
window.onload = onDeviceReady;
...
function onDeviceReady() {
onDeviceReadyFacebook();
...
}
...
function onDeviceReadyFacebook() {
// ?
}
window.fbAsyncInit = function () {
if (!window.cordova) {
// Initialize - only executed when testing in the browser.
facebookConnectPlugin.browserInit(<APP_ID>);
}
}
I have tried the window.fbAsyncInit both inside and out of the call I make for onDeviceReadyFacebook, trying to follow the advice from different forums...
So finally the error occurs within the call I have made to login:
function fb_login(){
var login_data = {};
client.cmd = "login";
login_data.userid = user_id;
login_data.cmd = "login";
facebookConnectPlugin.login([
'user_about_me',
'email',
'user_status',
'user_posts',
'user_photos',
'user_videos',
'user_friends'
],function(response) {
// success
...
Saying that the facebookConnectPlugin is undefined. After sligthly modifying different areas and everything else about the app is working, I would generally say that I'm not specifying the right source url for the primary JS file...
One last question on this topic: if I have correctly put in my Content Security Policy, is there any reason I need to use a plugin when I can just use the Facebook all.js they provide as is used in the browser version? I have got my key hash and other properties defined to add the android platform, I would have thought I can specify those attributes to match the platform...
EDIT: The plugin branch in question is located here.
UPDATE 2:
#JesseMonroy650:
Yes; a few things are definitely becoming clearer, but I did switch to cordova-plugin-facebookconnect-orlando, but adding that made the build crash, the log file result saying the message "...-FacebookLib/ant-build does not exist". I found the exact problem happening here, so I've now tried the same npm plugin and preference settings that was used there. It now builds, but I have the same problem (facebookConnectPlugin is undefined).
However, I checked the repo again this morning, specifically the path:
/platforms/android/assets/www/index.html
To see what I am crucially missing :
<div id="fb-root"></div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/facebookConnectPlugin.js">/script>
So hopefully if I copy off this example, I should be alright now. Will be trying again tonight.
Any help is always very appreciated!
The code added to index.html has finally resolved the issue. I tidied up the actual call to the login as demonstrated, but ultimately the variable wasn't found because I hadn't done the script include. Confusion over the scripts to include and what path they would be.
BIG relief!!! Props to you #JesseMonroy650 for steering me in the right direction of a deprecated plugin.

NodeJS, SocketIO and Express logic context build

I read a lot about Express / SocketIO and that's crazy how rarely you get some other example than a "Hello" transmitted directly from the app.js. The problem is it doesn't work like that in the real world ... I'm actually desperate on a logic problem which seems far away from what the web give me, that's why I wanted to point this out, I'm sure asking will be the solution ! :)
I'm refactoring my app (because there were many mistakes like using the global scope to put libs, etc.) ; Let's say I've got a huge system based on SocketIO and NodeJS. There's a loader in the app.js which starts the socket system.
When someone join the app it require() another module : it initializes many socket.on() which are loaded dynamically and go to some /*_socket.js files in a folder. Each function in those modules represent a socket listener, then it's way easier to call it from the front-end, might look like this :
// Will call `user_socket.js` and method `try_to_signin(some params)`
Queries.emit_socket('user.try_to_signin', {some params});
The system itself works really well. But there's a catch : the module that will load all those files which understand what the front-end has sent also transmit libraries linked with req/res (sessions, cookies, others...) and must do it, because the called methods are the core of the app and very often need those libraries.
In the previous example we obviously need to check if the user isn't already logged-in.
// The *_socket.js file looks like this :
var $h = require(__ROOT__ + '/api/helpers');
module.exports = function($s, $w) {
var user_process = require(__ROOT__ + '/api/processes/user_process')($s, $w);
return {
my_method_called: function(reference, params, callback) {
// Stuff using $s, $w, etc.
}
}
// And it's called this way :
// $s = services (a big object)
// $w = workers (a big object depending on $s)
// They are linked with the req/res from the page when they are instantiated
controller_instance = require('../sockets/'+ controller_name +'_socket')($s, $w);
// After some processes ...
socket_io.on(socket_listener, function (datas, callback) {
// Will call the correct function, etc.
$w.queries.handle_socket($w, controller_name, method_name, datas);
});
The good news : basically, it works.
The bad news : every time I refresh the page, the listeners double themselves because they are in a loop called on page load.
Below, this should have been one line :
So I should put all the socket.on('connection'...) stuff outside the page loading, which means when the server starts ... Yes, but I also need the req/res datas to be able to load the libraries, which I get only when the page is loaded !
It's a programing logic problem, I know I did something wrong but I don't know where to go now, I got this big system which "basically" works but there's like a paradox on the way I did it and I can't figure out how to resolve this ... It's been a couple of hours I'm stuck.
How can I refacto to let the possibility to get the current libraries depending on req/res within a socket.on() call ? Is there a trick ? Should I think about changing completely the way I did it ?
Also, is there another way to do what I want to do ?
Thank you everyone !
NOTE : If I didn't explain well or if you want more code, just tell me :)
EDIT - SOLUTION : As seen above we can use sockets.once(); instead of sockets.on(), or there's also the sockets.removeAllListeners() solution which is less clean.
Try As Below.
io.sockets.once('connection', function(socket) {
io.sockets.emit('new-data', {
channel: 'stdout',
value: data
});
});
Use once instead of on.
This problem is similar as given in the following link.
https://stackoverflow.com/questions/25601064/multiple-socket-io-connections-on-page-refresh/25601075#25601075

CPRangeException thrown when objects added to an CPArray

In my cappuccino app, I am reading from an RoR backend via JSON and putting the results onto a list. When the app first loads everything is fine, but when I edit an item (and write the edit to the database) there is an error generated when the items list is refreshed.
The error is CPRangeException: -[_CPJavaScriptArray objectAtIndex:]: index (-1) beyond bounds (3).
I get this error even if I edit an item without making any actual changes. The JSON string received by the app remains exactly the same in this case, there are no items added or removed and therefore the array should not be written to out of bounds.
Here is my code:
- (void)connection:(CPRURLConnection)connection didReceiveData:(CPString)data
{
if(connection === listConnection)
{
var results = JSON.parse(data) ;
var posts = [Post initFromJSONObjects:results];
[postListView setContent:posts] ;
// My error occurs at the above line
[postListView setSelectionIndexes:[[CPIndexSet alloc] initWithIndex:0]] ;
}
}
I am not sure if it's an error with my code or if it's some kind of inconsistency with the cappuccino framework. Does anybody know what I can do to fix this?
The rest of the code can be found here
You should probably simply log what's in posts before setting it. CPLog.info('posts: ' + posts); should work, or console.log(posts). Next you can set a 'break on uncaught exception' debug point in Chrome or Safari to stop at the actual error you are seeing. Make sure you run your app using index-debug.html so that you get full method names. Then it should be an easy matter to look at the calling stack to see where things are going wrong. There's a lot of information on debugging a Cappuccino app here.

Categories