in Rails, How to make a query in javascript? - javascript

Given the id of an element I need to make a query in javascript, for example:
javascript:
var post_value = $(".post").val() # return a post ID;
var post = #{Post.find_by(id: post_value).to_json.html_safe};
But the post_value variable don't recognize it
If I manually pass a value to it, it recognizes it and asks me the query of the post, for example:
var post = #{Post.find_by(id: 181).to_json.html_safe}; # If work because I pass 181 as an ID value
I would be very grateful if you could help me

This line gets rendered in server side. It will not have any access to the browser's runtime context. As this gets executed before reaching the user.
var post = #{Post.find_by(id: post_value).to_json.html_safe};
Either use XHR (have another endpoint API purely for data objects like json) or query your Post object/s in controller, pass the object to the view and render the Post object inside the view. It is also a bad practice to have DB queries inside the view template files.
It's also weird to use javascript to render elements in the backend context. You generally use javascript with the context or assumption that it is to be executed in the user's side, separated with the backend context.

Related

Connection between Java and Javascript through ZK framework

I have been facing an issue with the communication between java and javascript through zk framework in a iframe.
In simple words, I want to save a string in the current session and access it (or even overwrite it) in javascript.
my java lines:
HttpSession session = (HttpSession)(Executions.getCurrent()).getDesktop().getSession().getNativeSession();
session.setAttribute("key","testing");
my zul lines:
<iframe id = "change_option" src="select_one_option.html" scrolling="no" width="700px" height="400px" > </iframe>
my javascript lines in the html file:
var session= /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false; //finds the correct session id + desktop name?
session = session.substring(0, session.indexOf('.')); //removes desktop name and keeps just the session id in a string
//another try
console.log("Saved: " + sessionStorage.getItem("key")); //returns "Saved: null"
//another try
var username = '<%= Session["key"] =%>'
console.log ( " Variable is : " + username) //returns "<%= Session["key"] %"
Since the html file is big I thought it would be better to do it through iframe and not try to rewrite inside the zul file. Any suggestion is highly appreciated.
There are a few approaches you can consider depending on your full requirement.
#1 The page located inside of the iframe and the outer page may communicate directly, using the window postMessage API:
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
This require a bit of setting up, but allows the page located in the iframe to post an event to the parent page. The event has a data field, which you can use to transfer data.
The parent page can subscribe to such event, and read the event data.
With this method, you don't actually need to write stuff to the session at server-side, since this communication happen fully at client-side.
This is good if the server doesn't care about knowing the value.
#2 saving the object in session from the inner page, using it from the outer page
You are already setting the session attribute in the native session:
HttpSession session = (HttpSession)(Executions.getCurrent()).getDesktop().getSession().getNativeSession();
session.setAttribute("key","testing");
Note that session attributes are Java-side only. They are not automatically returned to the client as cookies.
You can add a cookie with the same value to your response, if you want to handle this by cookies:
https://www.zkoss.org/wiki/ZK_Developer%27s_Reference/UI_Patterns/Communication/Inter-Application_Communication#Use_Cookie
However, this is a bit overkill because ZK is a communication framework and you can already pass the value to the outer zul page in a number of ways.
First, you can just execute arbitrary JS on the page using the Clients#evalJavascript method.
https://www.zkoss.org/wiki/ZK_Developer's_Reference/UI_Patterns/Useful_Java_Utilities#evalJavaScript
With that, you can just build a JS call containing your value retrieved at server side, and execute it in client. Should look like this:
String myValue = ... //retrieve your server-side value;
Clients.evalJavascript("myClientSideFunction('"+myValue+"')"); //executed in an execution of the zul page.
But you can also use that value as a client-attribute, pass it as a component value, etc.
There are a lot of arbitrary things you can do to pass that value back to the client, all with pros and cons.
For example, if you want to put that value back into a textbox, you can simply use the textbox#setValue method. It really depends on what you are looking to achieve.

Django custom template tags in javascript

I have a custom template tag that returns suppose name of a student and roll number if passed as an argument id of the student.
#register.inclusion_tag('snippet/student_name.html')
def st_name_tag(profile, disp_roll=True, disp_name=True):
#some calculations
return {'full_name':student.name,
'roll':student.roll_number,
}
The template(included) consists of some Html file which is written in a single line(to avoid unterminated string literal error from js).
I simply want to call the st_name_tag from inside the JS function.
My JS looks like:
{% load profile_tag %}
<script type = "text/javascript">
eventclick : function(st){
var div = ('<div></div>');
var st_id = st.id;
if (st.status == 'pass'){
div.append('<p>Student Name:{% st_name_tag '+st_id+' %}</p>');
}
}
So far I tried the above method along with removing the + and '' signs from st_id varaible. That hasnt helped me at all. Help Please!
You are trying to render a template based on the interaction by user. The first happens on the server (server-side as it is often referred to), and the latter happens on the user's browser.
The order that these happen is first to render the template on server, send and present in browser, then user interacts with js. Because of this fact, as I mentioned in the comment, it is not possible to affect the template rendered within javascript.
I would recommend you to use ajax in order to accomplish this. Whenever an iteraction occurs, you asynchronously make a request to the server to present you with new data.

Retrive post data back using javascript/jquery

I want to pass the object to the new page by using only client side script(javascript),
and I want to read the data back when the new page is loads, but I could not find any tutorial or method to get it.
function postToURL(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
The POST message sent to the server to retrieve the current page is not exposed, by the browser, to JavaScript in that page, so you cannot.
Pass the data via some other technique (such as through the URL, or localstorage).
Yeah, POST data is only handled and seen by the server side (ex. PHP). Javascript is on the client side so it will never be able to see that data unless the POST data first gets passed to server side and that server side in turn hands it off to the client side (ex. Javascript).
Consider using GET as your method in your code above so that you can pass the parameters inside the actual URL to make it accessible to the browser / client / Javascript.
parameters can be parsed from a JSON-encoded string. If you build your parameters programmically (in the previous step) like:
parameters = {};
parameters['USA'] = 'Washington DC';
parameters['UK'] = 'London';
You can create a flat JSON String representing your structured data by:
parametersString = JSON.stringify(parameters);
and end up with something like this:
"{'USA': 'Washington DC', 'UK': 'London'}"
You can store this string in a cookie, or in a query string or fragment part of the URL.
Your next page can read back this value on the following page, and re-create the structured parameters by decoding the JSON string like:
parameters = JSON.parse(parametersString);
and you're getting the original data back, on which you can run JQuery's each.

How to pass value to another static page via javascript?

I am trying to pass value to another page and read the value in the another page. I use only JavaScript and jQuery. Not use others language as PHP. I don't want to be as like (http://www.example.com/?value=test). I am trying to use POST or GET method.
On first page:
$.post("second_page.html",{q:"test"});
window.location.replace("second_page.html");
On second page:
var location_query = window.location.search.substring(1);
var vars = location_query.split("&");
for (var i in vars) {
var param = vars[i].split("=");
params[param[0].toString()] = param[1];
}
If I pass value as like http://www.example.com/?q=test , the second page script is read the value, but I use this line: $.post("second.html",{q:"test"}); not read.
How to pass value from first page to another static page via JavaScript or jQuery or ajax?
See this post says:
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
but you can use cookies to read and store values:
<script src="/path/to/jquery.cookie.js"></script>
you can get it from here
Try with reading the documentation and see if this works for you.
Without using GET or POST you can transfer the content using HTML5 Local Storage or
Web SQL
$.post and $.get send AJAX request and waiting response on current page, you cant send params for next window.location.replace by this.
Use url get-params window.location.replace("404.html?q=404"); and look this for get params on second page.

How to get the action name (or view name) in Grails from Javascript or JQuery

I read here, that in the GSP we could write:
${params.action}
From the GSP, we could call a Javascript function with ${params.action} as parameter (see here).
Is there any other way to get the action name without passing parameters from the GSP view?
I understand the desire to reduce application code happening in the views, but to allow the proper components to handle what they handle (separation of concerns), it is the best way to have the controller pass the action name to the view via a model.
The client-side script otherwise has only the url and a loose sense of the route table compared to the server-side which must know exactly the route table.
If you still feel it best to use client-side script, window.location provides the url. To parse the url, javascript's string.split using '/' as the delimiter should suffice, the following snippet should help:
var url = window.location;
var urlParts = url.split('/');
var controller = urlParts[3];
var action = urlParts[4];

Categories

Resources