How to have an action respond to javascript in PHP? - javascript

I'm currently working with a Kohana project and am trying to implement endless scrolling. I'm trying to use the method Ryan Bates shows in the following Ruby on Rails video:
https://youtu.be/PQX2fgB6y10?t=2m29s
At 3:21 he says the action won't respond to javascript and proceeds to create a js.erb file. What is the PHP equivalent to this step going forward? Where would I place the php file equivalent to his index.js.erb?

To copy what he did, just create a PHP file that generates Javascript with the content you want to append like he did with render(). You can call this file whatever you want, but following his convention, it would be index.js.php.
So for example:
$('#products').append('<?php render_elements(); ?>');
$('#pagination').replaceWith('<?php render_pagination(); ?>');
Since you're already this far in his tutorial, I assume that you have the code to render the elements you want to display already.
It may be easier however to use other AJAX methods to achieve the same thing though.

Related

Making processing.js sketch get value from external JS variable

I have a game written in Javascript with the Processing.js library. I want to make highscores for that game, and for that I want the user to be able to type a name in an input tag in the page HTML.
How can I make my Processing.js sketch "see" the variable containing the value of the input field?
You should check out the Processing.js documentation, specifically the JavaScript Quick Start, specifically the Writing Documents that Combine Processing and JavaScript Code section.
There are three main ways to approach this: you can write Processing code that accesses an external JavaScript variable, or you could write JavaScript code that does something like call a setter function in your Processing code, or you could write JavaScript code directly in your Processing code.
Any of those approaches would work fine for what you're trying to do. If you still can't get it working, please post a MCVE of what you tried in a new question, and we'll go from there. Good luck.

Best way to use C#-Ressources (ResX Files) in Typescript?

our current project is in ASP.Net MVC with Razor.
We use ResX Files for a few thousend translations.
In C# and Asp.net Razor this is pretty easy with HTML:
<div>#Ressources.Local.Test</div>
Now when I wrote JavaScript I normaly did this within the cshtml files with razor like this:
<script>alert('#Ressources.Local.Test');</script>
Which works but seems a bit ugly...
A few weeks ago we starded with Typescript, and, of course excluding (nearly) all javascript code to ts-files.
The only solution we found here, to get the ressources from C# to Typescript is through a "hack":
We made a ressources.cshtml file in which we just include javascript variables:
var ressourceTest = "#Ressource.Local.Test";
We load this ressource.cshtml at first in our _layout.cshtml.
Additional, we have a self need a selfmade declarion for this variable to jump from javascript to typescript in our projectDeclarions.d.ts:
var ressourceTest:string;
And now we can use the ressource in our typescript file test.ts:
alert(ressourceTest);
As you can see it is a working "hack" or "workaround" but it seems to likly kill us for a few thousend ressources... It's handmade, the maintain duration and work is high...
Any better ideas?
I have seen a few good ideas around this.
You could supply an JSON endpoint in your MVC application to give you chunks of translations. You would decide how granular you want to make it, but you would essentially JSON serialize a translation, or set of translations and send it back. This would avoid stuffing a big view with hundreds of the things.
Another alternative is to place translations in the view to make them available, but contextually. So if you had a button that you are using to trigger some AJAX call to the server and you need to say "Update Worked" or "Update Failed" you could put the attributes inline...
<button ... data-msg-success="Saved OK" data-msg-failed="A problem occurred" />
And you could populate these attributes with your resources.

Call JavaScript function from Ruby on Rails model

I have built a Rails app that has an API that returns a JSON object. I want to allow users to write their own scripts and store them. These scripts will then be executed when the user makes an API call to the app and injected as part of the response.
An example would be when a user calls my API, their javascript would be called and whatever is returned from their script would be saved as a string and used by one of my models and used as part of the JSON object - not the full response.
I want to know how to call a javascript function from a rails model, save the output of the javascript as a string in Ruby, and then be able to process whatever is returned before making the API response.
The current answers seem to only be related to the controllers and rendering as JS, but I would like to execute the script from the model.
It should be something like:
string = execute_javascript("return 'hello world';")
This is more related to pure Ruby than Rails as I am just wanting to call it from a standard Ruby class and save the output as a string. I also need to consider the security implications of doing this, but first would like to know how to do it
The simplest solution to execute most common Javascript code is using ExecJS gem. If you are using the Rails standard gem bundle then ExecJS is already included with Rails Coffeescript. A short example:
require "execjs"
ExecJS.eval "'red yellow blue'.split(' ')"
# => ["red", "yellow", "blue"]
The above solution is only good if you are running a prototype. In production, you would want to somehow run the user code in sandbox and preferably on the whole different server. You would also need to ensure the code won't take 100% resource of your server while executing and screen the code to ensure it won't do anything malicious.
You can call javascript function in Helper class and then include that helper inside your model where you need it.

Is it possible to use $_SESSION with a Javascript file?

I have a Javascript file main.js and I need to use echo $_SESSION["username"] within it, but it doesn't work obviously. Is there any way I can do this / some kind of workaround?
You cannot execute PHP code in a .js file but there are ways to work around it. You could use an ajax call to get that variable (check out this link for ajax tips).
Depending on the information you wish to store, you could also get PHP to echo it into a specific element in your html page and then use JS to look up that element like this:
echo "<span id='usernameForJS' style='display: none;'>".$_SESSION['USERNAME']."</span>";
And then go and grab that elements inner html with JS like this:
var username = document.getElementById('usernameForJS').innerHTML;
I would advise AJAX just because then there is no need for almost redundant elements in your page. And obviously don't use the second method for anything sensitive.
There is a option I saw on css-tricks.com
https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/
I have never tried on my own but commentators said it works.
There is also a explanation of how you could do this in the comments:
https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/#comment-85757
But don't forget taht this is a rather "hacky" way to do it, you should consider to open that javascript file and instantiate your class/function(or whatever is in this file) from the .php-page.

cakePHP : requestAction and JS Helper

I use requestAction with parameter return $this->requestAction (....,array('return');
request action in plugin . plugin render view has $js->submit('Save',array('updade'=>'#fsjkfsj');
but it dont show any javascript when i view source code. I tested with code $js->alert('ksldjflkjs'); but it dont , too
how make requestAction width JS Helper or it is impossible ?
are you on cake 1.3 using the new $js engine helper? if so, i remember reading about bueffering and needing to explicitly write the buffer to the view. This is what the manual says:
It is recommended that you place $js->writeBuffer() at the bottom of your layout file above the tag. This will allow all scripts generated in layout elements to be output in one place. It should be noted that buffered scripts are handled separately from included script files.
the request action method might be buffering your scripts for the same reason. try this out and let the community know if it is the case seeing how the manual does not mention it.
Good luck!
btw, here is the link where i found the reference http://book.cakephp.org/view/1596/Javascript-engine-usage
in this case, I use $this->Js->writeBuffer() in file view.ctp of plugin . It'll output javascript buffered, but dont in one place , it in bottom file view.cpt of requestAction.

Categories

Resources