Running a ruby function based on data in a textbox - javascript

So in my ruby on rails application, I have a textbox that, when someone pastes data, it gathers a bunch of data (e.g. does some web requests, etc.). I've gotten everything from the ruby function working properly just using some sample data.
What I'm trying to figure out now is how can I pass the value of a textbox into a ruby function? Is that possible? For example, here's my code:
<script>
function doSomething() {
var searchData = $('#myTextBox').val();
<% helperFunction(<<How can i pass searchData here?>) %>
};
</script>
I'm guessing if this doesn't work, I could always create a small form that posts the textbox input to a controller, and go from there.

Related

Need to convert Web Form JavaScript to a js file

Basically I have three functions embedded into my form. I want to move this into a js file that I have already. I did this previously and my pop ups are working but now I want to move one function which executes the onclick event for a download button and the other two functions belonging to my autocomplete extender so I can display the results how I want them.
I have been messing around but I cannot seem to get this working.
This is my JavaScript function in Web Forms
function Download() {
__doPostBack("<%= btnDownload.UniqueID %>", "OnClick");
}
This is what I have tried in a js file
function Download(button) {
__doPostBack(button, 'OnClick');
}
and this is how I am calling it
ClientScript.RegisterStartupScript(Me.GetType(), "download", "Download(" & btnDownload.ClientID & ");", True)
please can somebody give me a clue to what I am missing and before I forget yes, the file is in my headers
<script type="text/javascript" src="js/importBuyer.js"></script>
The javascript function __doPostBack("<%= btnDownload.UniqueID %>", "OnClick"); expect a string as the client ID of the button. So you need to construct the calling script with ID parameter as string as follows:
ClientScript.RegisterStartupScript(Me.GetType(), "download", "Download(""" & btnDownload.ClientID & """);", True)
Note the double double-quotes ("") above so that the rendered javascript will be like :
Download("btnDownloadID");
From the example you've posted it seems that the webform way was sending the UniqueID and you are sending the ClientID
So you probably only need to send the UniqueID property instead.
I am wondering why should you do that. I would expect you to move from webforms to an API base backend but I can't understand why you want to separate the js integration part while keeping the webforms backend - I would understand if you'd separated the js logic part... not the part that communicates with the webforms
Hoped that helped
Here is a link describing the difference

How to Put Data coming through Request or session into JavaScript Code in a JSP Page

I am making a Project where the need is to query no of already booked seats from database and show those seats as already booked in the layout made on a JSP page using JavaScript.
I have made a query in database & I have the data. All the data is joined by "," using Join() function.
Example:- 3,6,8,10
Now how to put that data dynamically into Javscript code existing on a JSP Page? The Javascript Code where I want to put the dynamic data (Not Posting Full Java Script Code, Posting Only The Exact Part)
<script>
var bookedSeat = [5,10,25]; // << Put Dynamic Data Here
seats(bookedSeat);
</script>
I have tried using <% --- %> but it didn't work. Can someone please help me? I am very new to JavaScript.
You can easily use those Request or Session data in JavaScript using EL. You can try like below code:
<script>
var bookedSeat = ${variableName}; //Put variable name which you are setting in request or session
seats(bookedSeat);
</script>

Passing javascript variable to partial via render_javascript

I receive a google ID from an Ajax call and then want to use that ID to update a button on my view.
Here is the code in new.js.erb, which is linked to a new.html.erb.
Problem is, I don't know how to pass the variable's content. Restaurant is a json. The alert returns the correct ID and when I search my db on the terminal with the returned google id I find the restaurant.
Here is the code:
alert(restaurant["google_id"]);
var google_id = restaurant["google_id"];
$("#rating_bar").html("<%= escape_javascript(render 'reviews/buttons/full_profile_rate_restaurant', :google_id => "+google_id+".html_safe) %>");
What happens is that the variable being passed is the string "google_id" instead of the combination of letters and numbers that is the google ID. I've tried multiple approaches, this is just one of many wrong one - I think this question is pretty easy for anyone who knows their JS really well.
It is not possible to pass a JS variable to the ruby partial.
As Ryan Bigg explained for the same type of problem here, its not possible to send the variable while rendering that partial. We need to work out some thing else. Even i also had the same issue once.
Alternatively,
if that is google_id is only a variable to display in the partial, then update those divs manually after rendering that partial.
like
$("#rating_bar").html("<%= escape_javascript(render 'reviews/buttons/full_profile_rate_restaurant', :google_id => "sample_id") %>");
// Now update the required elements
$("#what-ever-ids").text(google_id);
or just create some other action in that controller, and call send an ajax request to that action, and there you will have this js variable, and in that js.erb file render the same partial which you actually want to update with the google_id variable.

Grails - rendering div with a javascript call within a remoteSubmit

I have a situation where I want to hit a button in the GSP (actionSubmit) and update a div when I finish the call (which includes a call to a javascript function). I want to ultimate end up in the controller rendering the searchResults parameter and the div with the results (which is currently working).
Problem is, I need to (presumably) wrap my actionSubmit in a remoteForm. But how do I:
1) Run the javascript method already existent in the onClick
2) Render the page in the controller.
If I try both wrapped in a controller, I finish the remoteForm action and the javascript action "hangs" and never finishes.
Any ideas?
List.gsp
<g:actionSubmit type="button" value="Ping All" onclick="getIds('contactList');"/>
function getIds(checkList)
{
var idList = new Array();
jQuery("input[name=" + checkList + "]:checked").each
(
function() {
idList.push(jQuery(this).val());
}
);
$.ajax({
url: "pingAll",
type:"GET",
data:{ids:JSON.stringify(idList)}
});
}
controller:
def pingAll() {
String ids = params.ids
if(ids == "[]") {
render(template:'searchResults', model:[searchResults:""])
return
}
def idArray = contactService.formatIDString(ids)
idArray.each {
def contactInstance = Contact.get(Integer.parseInt(it))
emailPingService.ping(contactInstance)
}
/**
* Added this on 3/13. Commented out line was initial code.
*/
def searchResults = contactSearchService.refactorSearchResults(contactSearchService.searchResults)
render(template:'searchResults', model:[searchResults:searchResults, total:searchResults.size()])
}
You have a couple options:
1) You can avoid using the Grails remote tags (formRemote, remoteField, etc.), and I really encourage you to explore and understand how they work. The Grails remote tags are generally not very flexible. The best way to learn how they work is to just write some sample tags using the examples from the Grails online docs and then look at the rendered page in a web browser. All the tags do generally speaking are output basic html with the attributes you define in your Grails tags. Open up your favorite HTML source view (i.e. Firebug) and see what Grails outputs for the rendered HTML.
The reason I say this is because, the code you've written so far somewhat accomplishes what I've stated above, without using any GSP tags.
g:actionSubmit submits the form you are working in using the controller action you define (which you haven't here, so it runs the action named in your value attribute). However, you also have an onClick on your actionSubmit that is running an AJAX call that also submits data to your pingAll action. Without seeing the rest of your code and what else is involved in your form, you are submitting your form twice!
You can simply just not write actionSubmit, and simply do an input of type button (not submit) with an onClick. Then in your javascript function that runs, define a jQuery success option for your AJAX call
$.ajax({
url: "pingAll",
type:"GET",
data:{ids:JSON.stringify(idList)},
success:function(data) {
$('#your-updatedDiv-id-here').html(data);
}
});
2) If you want to use the GSP tags, I think you are using the wrong one. Without knowing the full extent of your usage and form data involved, it looks like g:formRemote, g:submitToRemote, and g:remoteFunction could serve your purposes. All have attributes you can define to call javascript before the remote call, as well as defining a div to update and various event handlers.

Cascading Dropdown List

I am working on a web app and trying to code a form with two dropdown lists. The list in the second dropdown will be dependent on the selection from the first one. The task itself isn’t too complicated except that once the first selection is made, I need to make a database call to pull the data for the second dropdown. This is where I am having difficulty. Both lists are in fact populated from a database.
I am working on this in a python script and have been trying to do this w/ an onChange javascript function. The web app is built in Zope and page templates may be an option along w/ the python scripts.
you will have to use a combination of Ajax and javascript here. Onchange event of your select drop down call a javascript function. This javascript function will make a ajax request to a python script that will actually make a database hit and return you a response in a javascript variable. With this javascript variable you can edit you DOM and set the html of second select box.
see if u can get some hint from this:
http://www.satya-weblog.com/2007/04/dynamically-populate-select-list-by.html
That's exactly what I did. Below is the javascript function I came up with. OnChange, I call getOptions and the pythonScript creates the second dropdown list. I am able to pass in a parameter to get the data I need for this dropdown. Thanks!
function getOptions() {
var code = 'code=' + $("dropdown1").getValue();
var myAjax = new Ajax.Updater('dropdown2', './pythonScript', { method: 'get', parameters: code });
}

Categories

Resources