I am now facing an issue related to getScript in rails. Actually I am able to pass a variable data to a particular action of my rails controller using the following line in my view.
getScript('/user/out_action.js?pt=' + resulted_time); // resulted_time is the variable name I want to send.
Where 'user' is the controller name and out_action is an action in the controller.
It is completely fine.
Now my problem is that I am unable to send multiple different variable data to the controller action from my view. I am using ruby on rails. I want to pass this data using one single call.
For example I want to pass to another variable like resulted_time using the same call.
Please tell me how to do it.
Very simple you need to enhance your query string like below example. If you are using coffee script below
$.getScript('/user/out_action.js?pt=#{resulted_time}&ps=#{resulted_time}');
That will insert multiple parameters. For plain javascript, you can use below code.
$.getScript('/user/out_action.js?pt='+resulted_time+'&ps='+resulted_time);
Let me know if you need more elaboration.
Related
For a f:link show action in my fluid list template i want to pass a javascript variable to the arguments, basically the uid (to pass that specific object to the showAction), but it doesn't work the way i intend to do it. Is there a workaround for this particular problem?
The naked template looks like this:
<f:for each="{termins}" as="termin">
<tr>
<td><f:link.action action="show" arguments="{termin : termin}"> {termin.mitarbeiter}</f:link.action></td>
<td><f:link.action action="show" arguments="{termin : termin}"> {termin.kunde}</f:link.action></td>
</tr>
</f:for>
</table>
You can't - and you also can't (read: never should) generate links to controller actions from JS since it needs to generate a security checksum. Modifying the URL you create will generate a security error. The checksum exists to prevent DDOS so it has good reason.
There are two options:
You can generate all links in advance
You can make a link-generating service that you call with XHR to generate the necessary links from JS.
Only the first one is appropriate to your use case. Especially so since you want to pass UID values which always refer to an object in the database - which means you can easily generate a list of links to all possible detail views, then read/pass that list of links from your JS to select the right one.
The JS is something working after the fluid template. The right order is, your fluid template is parsed into the HTML, and then the browser render the HTML/JS/CSS to you. So, you can not expect to use JS value in your fluid template.
There are 2 possibilities:
1) Instead of a link use a form and transmit it via POST. Set a form field dynamically with JavaScript. That way your variable isn't included in the (cHash-) checksum.
2) Create an AJAX action that accepts your variable as argument. Let it generate a valid link. Use POST to call it with your variable data. Show the link on your page with JavaScript.
I'm using AngularJS (mainly the client side) and web2py (mainly the server side)together in an app.
I have an issue now.
At a point of the program, I use AngularJS to get some data from the client and these data are store in an AngularJS variable. I planed to use $http.post to submit these data to database directly, but it didn't work due to cross-orign problem.
Right now I'm trying to pass these data(they are in JSON format) back to web2py and let web2py insert these data to database.(similar to submitting a SQLFORM).
Is there anyway I could pass these data as an argument to an web2py function and invoke that function within javascript code?
Possible approach in my mind:
1) Since I could write python in html using {{}}, and I could write html in javascript, could I write python code within javascript using something like: document.write({{python code}}) ?
I tried this but whatever html I write it goes to a brand new html page. I also tried document.getElementById('testDiv').write("<p></p>"); But it doesn't work.
2)use ajax, I'm not familiar with ajax, any example will be really appreciated!
Any thoughts?
Thank you all!
ok so you got me lost for a second there, lets see if i got it right
1- angular as your frontend
2- python as your backend
3- you are rendering an html document in python and delivering it to the browser
4- since python template language uses {{}} as delimiter am assuming you changed the angulars delimiters too
either using ajax or reload you'll need to provide a python post handler script. that takes your data and makes the DB update. if this is going to be a pattern and you are going to be making AJAX CRUD operations, you should use angular resources ngResource if not a simple
$http.post(url,data).success(function(response){})
https://docs.angularjs.org/api/ng/service/$http#post
where url would be your form submission handler url.
if you where to use a form you'll need to set the target to an iframe hidden in your page and the response should a script tag that gets the scope pertinent to your controller and let him know the result of the operation. this is an old approach, but handy when it comes to send information to sites that don't allow CORS which by the way might be the solution to your problem, when storing data directly to your db, you might just need to enable CORS headers in your storage engine API and that should allow you to submit information even when coming from a different domain
After hours of struggles and countless google, here's my workaround solution:
Main problem: the data are stored in AngularJS but AngulatJS could not submit data to database through API due to cross-orign issue. But Web2py could submit data to database using sqlform.
My approach:
1.)When the user click the submit button, invoke 'ng-click="submitBtn()"'.
submitBtn() is a function of the ng-controller, which has access to the data.
2.)In submitBtn(), the function first write data into web2py's sqlform through
document.getElementById('inputId').value=$scope.data;
then the function click the sqlform submit button through
document.getElementById('submitBtn').click();
It took me a lot time to figure out those element ids of fields in web2py's auto-generated sqlform. The way to find them is using developers' inspect element tool in a browser and see the source code directly.
Hope this will help someone will face the same issue!
I followed Hartl's Rails tutorial where he does Ajax using RJS and sending javascript in the response to be executed on the client side to edit the DOM.
But what do you do if you want just JSON sent in the response and not send javascript. This also means the javascript to manipulate the DOM should already be in the html file on the client. Is there a tutorial as good as Hartl's book on how to do this in Rails. Presumably it would use Jquery and some other stuff maybe that I've not heard of to make the code not be a million lines?
My best attempt at an answer is that it really depends on the scope and complexity of what you're trying to achieve. Generally, JSON shows up in views. If your application does not require you to dynamically retrieve JSON, that is, you can load it all when the view is initially rendered, then you can set an instance variable in your view's controller like so
#my_json = some_object.to_json()
Then, your instance variable is available in your view
<script type = 'text/javascript'>
var theJSON = <%= #my_json %>
</script>
Now, your data is available in the DOM, parsed nicely into JSON.
If your application requires you to dynamically retrieve JSON after the controller/view are loaded, then you should probably look into using AJAX to hit a particular controller's method that returns the JSON that you desire.
Here's a good RailsCast that can hopefully help you along your way Passing Data to Javascript
You should take a look at Ajax in Rails 3.1 - A Roadmap.
I recently started working on a project which involves ruby on rails/javascript/jquery. I am very new to all this. The part I am involved is like this. User clicks on a button. A dialog will open, where user will enter a term to search. With that term, I am will be constructing an URI by looking at an xml. Then I will do a REST call. The response will be a XML file. I will be parsing it and displaying data in the same dialog where user entered term to search.
I am using JQuery to create a dialog. And I am doing parsing and REST call part in ruby code (Helper class). I am not using models and controller for my part. Now I need to send data from helper method to erb file where I will be displaying data as a table. Output will be like this
string11 string12 string13
string21 string22 string23
string31 string32 string33
. . .
. . .
For now, in ruby code I have create 3 arrays for every column. I am not sure on how to send data from ruby to html/javascript. If there is better way to do this then let me know. For ex: instead of sending as 3 separate array, is it better to send as xml/json? Or any other suggestions will be really helpful. Mainly I am not understanding on how to send this data to the erb file. Thank you in advance.
Edit: Adding a sample code
Javascript/Jquery -
On button click, I want to call a ruby method in erb file
Ex: <%= getUserList%>
erb file is also having other javascript/html code to display other stuffs.
And in helper method I have getUserList method
def getUserList(search)
uri = create_url(search)
#doc = Nokogiri::HTML(open(uri))
//Doing parsing and other stuffs here
//creating 3 array as mentioned above which needs to be displayed
end
I want above arrays to be displayed. I am not sure on how to send these arrays to the erb file which invoked this method
In your controller:
def users
respond_to do |format|
format.js do
render(:js => "callback(#{#users.to_json});")
end
end
end
Use something like this in your HTML to call that:
<%= link_to_remote "get users", :url => { :action => "users" } %>
More information on rendering vanilla JavaScript from a Rails action: http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-vanilla-javascript
This example constructs JavaScript that calls a "callback()" function in your JavaScript code, with JSON data. Your callback function will receive a JSON string that will be easy to parse. You could also use to_xml to send XML if you really want, but parsing JSON is much simpler and faster.
You don't need a helper in this example because the JavaScript call that includes the data will come directly from your controller. There is no view template, so you don't need a helper. The best place for the code that gets the #users would be in a User model class. Not an Active Record model, just a plain model. The code that fetches the users from the remote REST API could possibly be a class method. (If you're feeling lazy then you could set #users with the REST API response right there in the "users" controller action. But that's not ideal use of Rails because the whole point of Rails is MVC.)
If you're using jQuery, then you could also use jQuery's getJSON() function so that your controller would send only the JSON data without using the callback: http://api.jquery.com/jQuery.getJSON/
Note that this is the simple kind of answer that you seem to be looking for, but this isn't really the best way to do this kind of thing for more complex applications. The best way to do this kind of thing at the moment is with something like Backbone.js. http://documentcloud.github.com/backbone/ With Backbone.js, you can define a "users" collection in JavaScript, set the REST URL of that collection (it can be a URL in your Rails app, which relays data from some other API) and then you simply call users.fetch() in your JavaScript to load the data. It's very similar to Active Record, but for the client site. It's better because it abstracts the process and allows you to update and delete records as well as simply listing them.
I have the need to pass the current model of the view, from the view into a controller, upon a button click.
This is to export the current data to Excel.
What is the best way to do this? I keep trying to pass the Model from the view into a JS function as such:
onclick = "ExportToExcel(this.Model);"
But, the data is being passed into the JS as undefined. What am I doing wrong?
Thanks.
The Model, after reaching the View from Controller (initially at the page load) is no longer accessible, I mean it sort of does not exist any more as an Object you can say. So, you cannot directly pass the model back to JS/Controller. If you want to pass any particular data from Model to JS, you can do so by actually "writing" the data in a hidden input and access this from Java Script using the input id by jQuery.
PS: I know this is pretty old question but I just wanted to know if I'm correct about this. :)
You can use jQuery to post your model object using and as #Raynos said, get download link.
To do that, you'll to convert your model (cs/vb) to javascript.
the onclick code will get run in global scope so this === window.
I'd assume window.Model is undefined
Try
element.onclick = function() {
ExportToExcel(this.Model);
};
For the record, exporting data to excel should be done on the server and should return a link to an excel file that get's temporary created on the server that users can download