calling an Action using javascript - javascript

Fairly new to the PLAY Framework and because of restriction at my work we are using the 1.2.5 version, and while up til now was able to do all my process using the regular process from HTML to Controller via form submit. I would like to call an Application.Action from a JavaScript function.
While I have a form where information is inputted, another non-submit button could be clicked to go on a separate page for extra information. I want to call a JavaScript function via the "onClick" and inside the JavaScript function call the "#Application.Action(some param...)".
I need to get what is in a particular input field before calling the action.
I tried to do that with a PLAY "popup" but that does not seems to work as I can't pass the parameters along.
so here is the snippet I have:
in HTML file (extends the main.html who has all the javascript file "include")
<form>....
some input fields here
submit button here
</form>
<button onclick="myFunction()" data-role="button" style="width: 5em">Click here</button>
in the JavaScript file that is included in main.html I have something like this
function myFunction() {
var inputField1 = document.getElementById('inputField1').value;
var inputField2 = document.getElementById('inputField2').value;
var inputField3 = document.getElementById('inputField3').value;
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
}
Of course that does not work
Is there a way to do it like that?
Do I have to create a route for that?
I was able to reach a separate page by replacing
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
with
window.location.href='/goThere';
as long as I have a route
/goThere Application.goThere
but I could not figure out a way to pass parameters, I tried to set the route like
/goThere/{inputField1}{inputField2}{inputField3} Application.goThere(inputField1...)
but I guess I do not have the right syntax either.
Is there a way to call an Application.Action and pass it parameters/fields from a JavaScript function.
Any help is appreciated

The built-in #{jsAction /} template tag does exactly what you want.
Example:
Assume you have a route
GET /moreinfo/{foo}/{bar} Application.moreInfo
You can use the result of jsAction to get the correct URL with the parameters you want:
var fieldOne = "I'm a Javascript variable";
var fieldTwo = "Really? Me too";
var moreInfoAction = #{jsAction #Application.moreInfo(":foo", ":bar") /};
// and since it looks like you want to set the current location
// to your freshly obtained URL:
window.location.href = moreInfoAction({"foo": fieldOne, "bar": fieldTwo});

Related

AngularJS send window.location to a function or a directive

I'm trying to create a "Back" button as a function or directive. Upon clicking it, it would call a function that has several things to do before redirecting the user to a url.
Normally, in pure JS, I would have a simple div with an onclick function to which I would pass the URL to go to then the function would do its thing then make a window.location.href = url and it would be ok.
Here in angular, the URL i'm trying to send is part hardcoded, part coming from a ng-model: url="#/clients/editer/{{client._id}}"
When trying to use a simple function to which I would pass this as a string, my function doesent get the client.id as a string though the HTML inspector of firefox says it does. But if I console.log the URL the function gets, it says
"#/clients/editer/{{client._id}}" instead of "#/clients/editer/56684b4fe7b59ff020b85590"
When trying to use a directive instead of a function, as being new to all this, I dont understant how I'm supposed to pass thir URL to the directive. Since the URL could change radically from a module to another (from "#/clients/editer/{{client._id}}" to "#/materiel/editer/{{materiel._id}}", I need to pass the decoded URL directly to the directive which would then execute the onclick function.
Hope someone can help me !
I made simple test code
js
scope.client._id = 9;
scope.somefunction = function (url){
console.log(url)
}
Html
<div ng-click="somefunction('#/clients/editer/{{client._id}}')">link</div>
Result: #/clients/editer/{{client._id}}
<div ng-click="somefunction('#/clients/editer/'+ client._id)">link</div>
Result: #/clients/editer/9
Is this the result you wanted to achieve?

How to override variable parameter loaded from another script

I have a script that loads the code dynamically. It is kind of a search engine. When I press a search button, the action gets triggered and a new page opens with many parameters.
I want to override one of the parameters generated with the script in the new URL. JS code is quite big and hard to read, but I have found the important part in the Firebug DOM editor.
This is the pattern of the URL generated when you perform the search:
http://www.example.com/...?ParameterOne=123&ParameterTwo=Two&ThisParameter=Sth&ParameterFour=Four...
What I want to edit is "ThisParameter" and change its value. This is the part edited in the DOM that does what I want:
Foobar = {
_options: [],
...
var options = {"ParameterOne":123,"ParameterTwo":"Two","ThisParameter":"ABC","ParameterFour":Four,...}
...
And this is the output of "ThisParameter" when you choose "Copy path" in Firebug's DOM tab:
_options[0].ThisParameter
I am wondering it this is possible at all. What makes me think that it is, is the fact that I can change this parameter in Firebug and it works perfectly. So, if Firebug can edit it, there should be a way to influence it with another script.
Looking forward to any suggestions, thank you in advance!
Since you cannot edit the dynamic script you have the following options:
You have to try to give the script the correct input and hope it uses your value.
Add a script to the results page which will read the url and arguments, change it and redirect, as we discussed here. (If you put everything in functions it should not conflict with the dynamic script if the functions are uniquely named.)
You could try adding something like this jQuery code to the page with the search button:
$('input[name=search_button_name]').click(function(e) {
e.preventDefault();
var form_search = $('#search_form_id');
$('<input>').attr({
type: 'hidden',
name: 'ThisParameter',
value: 'SomethingElse'
}).appendTo(form_search);
f.submit();
});
You can override any js function and method, or wrap you code around it. The easiest thing would be to look at the code you get and once it gets loaded, you re-declare a method with your own functionality.
I you are trying to replace a parameter in a specific jquery request, you can even wrap around the jquerys ajax method:
var jquery_ajax = $.ajax
$.ajax = function(options){
// parse only a specific occurence
if(options.url.indexOf("example.com") > -1) {
// change the url/params object - depending on where the parameter is
options.params.ThisParameter = "My Custom value"
}
// call the original jquery ajax function
jquery_ajax(options);
}
But it would be a lot cleaner to override the method that builds the ajax request rather than the ajax request itself.
I would investigate further on the scope of the variable options (var options), is it global? i.e. if you type 'options' in the Firebug console, does it display its properties?
If so, you could then access it via your own script and change is value, e.g.
options.ThisParameter = 'my-own-value';
You might hook your script to the click event of the search button.
I hope this helps, it could be more specific maybe if you have some sample code somewhere.

Javascript variable to html page 'script tag'

Is it possible, if one has a javascript variable like this:
var myVariable = "alert('BAM! It works!');"
to send it to an html page that has a script tag in, in other words, looks like this:
<script id="theScriptTag"></script>
and by 'sending' I mean going like this in the Javascript file:
getElementById("theScriptTag").innerHTML = myVariable;
Now maybe people normally don't do this. If there's another way to get a Javascript variable to an HTML page please don't hessitate to tell. It's difficult for me to explain why I would like to do it like this, only that I need to do it like this.
Thanks in advance!
EDIT...
From all the comments I can see this is some serious bad practice. Let me give you the over view and 'bigger picture' here... On the very same HTML page there is a form, and a div. Now right after a user fills out the form and submits it, it goes to the server and 'custom javascript' is generated depending on the variable the user selected. This custom javascript is then intended to go back to the client and execute. When it executes is creates/fills up a div element that then contains a google charts table (thus needed to get generated server side). The JS that needs to be executed looks like this:
var sendAttemptsChartTableData, sendAttemptsChartTable;
google.load('visualization', '1', {packages:['table']})
google.setOnLoadCallback(drawTable);
function drawTable() {
sendAttemptsChartTableData = new google.visualization.DataTable();
sendAttemptsChartTableData.addColumn('string','smsGuid')
sendAttemptsChartTableData.addColumn('string','attemptNo')
sendAttemptsChartTableData.addColumn('string','response')
sendAttemptsChartTableData.addColumn('string','error')
sendAttemptsChartTableData.addRows(1)
sendAttemptsChartTableData.setCell(0,0,'092A49AA-E2EF-46D3-A83E-0932B17B649A')
sendAttemptsChartTableData.setCell(0,1,'1')
sendAttemptsChartTableData.setCell(0,2,'<aatsms><submitresult action="enqueued" key="2066317199" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317200" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317201" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317202" result="1" number="0833756610"/></aatsms>')
sendAttemptsChartTableData.setCell(0,3,'')
sendAttemptsChartTable = new google.visualization.Table(document.getElementById('sendAttemptsTable'));
var view = new google.visualization.DataView(sendAttemptsChartTableData);
sendAttemptsChartTable.draw(view, {showRowNumber: true, allowHtml:false});
google.visualization.events.addListener(sendAttemptsChartTable, 'select', smsSearchHandler);
}
Based on your edit I understand your form sumbission results in a custom script. Would a JSONP-like solution work? Basically you can create a script tag in your current document, pointing its source to a server side script that processes the form and returns the code.
A basic example:
function getScript(){
/**process form, generate params**/
var nwScript = document.createElement('script');
nwScript.src = '/myscriptsrc/somescript.php?'+[generated parameters];
document.body.appendChild(nwScript);
}
If your goal is to execute the javascript code contained in the string, you can use the following :
var myVariable = "alert('BAM! It works!');";
eval(myVariable);
What you are trying to do is essentially this:
var myVariable = "alert('BAM! It works!');";
eval(myVariable);
eval takes the string you provide and "evaluates" the content - it executes the javascript stuff you provide in the string. Normally you want to do this with input from the user.
But this is considered bad habit, because:
it is slow
it is unsecure
Usually you can go another way, so you don't need to use eval. In most cases this is cleaner, faster and more secure.
Perhaps you could tell, WHAT you are trying to achieve, and then we can find a better solution.

submitting form through javascript and passing a variable with it

I want to submit a form and add a javascript variable with it. I tried using AJAX but that didn't work properly because the form is cut in two parts on the same page. I'm now using a <button onclick='submit_form()'>send</button> which calls on the following function:
function submit_form()
{
document.getElementById("form2").submit();
}
however I need to pass on a javascript variable current_score I have it declared and it has a value I just don't know how to add this to my submit function I tried using a return within the function itself and writing a function for it but neither worked :) help and hints are greatly appreciated.
The idea is that people receive a score fill a form and send it to a database, The ajax script part was to try and pass the values on to the next page that will submit the data
Your question is not very clear. The simple way would be to append a get parameter to the URL you are requesting. The following example will append a hidden input element to your form:
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "theName";
hidden.value = current_score;
var f = document.getElementById("form2");
f.appendChild(hidden);
f.submit();
You could store the information in window.variable also

Managing Html text in popup

I'm using OpenLayer popup.
when initializing it, there a parameter required to contain the html displayed in the popup.
this parameter is javascript string.
I have a conflict, on the one hand the html text is long so I prefer to place it in html file and read the file to the variable.
On the other hand, the html depends on other local variables, so if I leave it on its place I can concatenate some strings and local variables to compose the final variable containing the html text. but it is very long and ugly code...
Maybe experienced javascript programmers can help me to find a design solution to this problem?
thanks
As you are using OpenLayers you can use the OpenLayers.loadURL function to retrieve HTML from your server.
http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Ajax-js.html
If you want to pass in local variables to server side HTML you can set up a simple handler that accepts variables, and integrates these into some static HTML (using string formatting or a template).
If you are using .NET then a .ashx file can do this. See http://dotnetperls.com/ashx for an example.
Another solution is to use an Ajax request to load your file, and then print the content inside the popup.
Using JQuery:
$.get('myfile.php',function(content){
var popup = new OpenLayers.Popup("popupid",
new OpenLayers.LonLat(mouseX,mouseY),
new OpenLayers.Size(360,200),
content,
true);
map.addPopup(popup);
});
When the Ajax request is completed, you can create the popup and fill it with the file content previously loaded.
I would recommend geographikas solution, and also try to use different js-classes to improve maintainability and readability. Don't do everything in the same object, make your own popup object that inherits from or uses OpenLayers.Popup.Anchored or something, and make the Ajax server call from there. This way you won't clutter your other code with this. Also makes it easy to reuse and substitute when needed.
I would go for something like this (untested!):
mynamespace.mypopup = function(o) {
var size = new OpenLayer.Size(100, 70);
var icon = new OpenLayers.Icon(); // Fill it
var popup = new OpenLayers.Popup.Anchored(o.id, o.lonlat, size, getContent(), icon, false, null);
var getContent = function() {
// ajax call
// return a string
}
return popup;
}
in a file called "mypopup.js"
and call it with:
var popup = new mynamespace.mypopup({id: 'whatever', lonlat: myLonLat});

Categories

Resources