Passing javascript variable to partial via render_javascript - 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.

Related

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.

Symfony2/Javascript delete alert

the main part of this question relates to how I can define a route in a javascript file. At the same time, I just want to make sure what I am doing is ok. Essentially, on my view page, I can see my records. When I output the records, each row I give
<input type="button" value="Delete" onclick="delete_alert( {{ alert[0].id }} )"/>
This gives the user the option to delete an alert. Before going straight into things, I like to first send it to javascript.
function delete_alert(id){
var answer = confirm("Confirm delete");
if (answer){
$.get("NickAlertBundle_delete", { row: id });
}
}
So if the delete is confirmed, it calls this route
NickAlertBundle_delete:
pattern: /view-alerts
defaults: { _controller: NickAlertBundle:Alert:delete }
requirements:
_method: GET
My first question here is they are deleting the alert from the view-alerts page. Once they confirm deletion, I dont want them to go anywhere, just have the view-alerts page refresh (as this will remove the deleted alert). But is giving the delete route a pattern of view-alerts confusing or wrong to do? Its what I want to do as I want them to stay on this page, just doesnt feel right.
Anyway, my real problem is the error
No route found for GET /NickAlertBundle_delete (from
http://localhost:8000/view-alerts;) (404 Not Found)
So I dont think the way I have define the route in my javascript file is correct. So how can I fix this route?
Thanks
I think you should use an URL as a first parameter to jQuery get. You are currently using the Symfony2 route name, not the URL.
Change it to /alert-views.
OR:
You can add a data attribute to your HTML button that would contain your path, If you are using Twig as templating engine, you can write something like:
data-url={{path('NickAlertBundle_delete')}}
Then using the attr() jQuery function onclick on your button:
var url = $(this).attr('data-url');
Finally, the jQuery get function can be sent to url.
I hope it helps.

Call a PHP Link with Onclick

This isn't a duplicate question by any means and I have tried a lot finding solutions.So, please read it before down voting.
Background:
This application is like a note-taking web app where you can post/delete your notes.
Each item in the list has an id which is needed when making a delete call.
In my application, I have to delete individual items from a list which is generated by looping over a JSON response (by a REST API) using PHP.The JSON response can be obtained after successful login.
Question:
To implement delete functionality I have to send id of each of the items as a parameter to the rest api delete call.
So, for this I have to generate dynamic links of the form :
http://localhost/myfolder/api/notes/:id
which should be passed to the delete.php function (Which I have implemented in CURL).
I searched for possible ways :
Using a PHP function: It seems to be complex, however if there is some way to invoke a PHP function (the delete code using CURL) on click of a link (Which I found not possible as per some answers ?) this could be a great solution.
Using Javascript: I have to call a function upon click of link that sets a variable $_SESSION["id"] to the current item["id"] and then goes to delete.php where I use the $_SESSION variable to first set up the link and then use the CURL code.
I tried basic implementation using the second approach but I have hit a roadblock in this issue. It would be great if you could tell with a bit of code which approach should be followed or any other way to do this ?
This functionality is present in twitter/facebook and almost every such service, how do they implement this, the basic approach should be the same, right: Generate dynamic links and pass them to a php script on click ?
Basic Javasript approach :
<script>
<script>
var el = document.getElementById('del1');
el.onclick = del1;
function del() {
// I have to set $_SESSION here
return false;
}
</script>
echo "<a href=\"delete.php\" title=\"Delete\" id=\"del1\">";
//Here, I have to pass the item["id"] to the javascript function.
I had tried some other ways but I have modified the code a lot so, I can't post them. Thanks for your help.
Regarding #2, you can't access the user's session from Javascript, so that will not work.
My preferred way (if using jquery) is to put the id in a data attribute of the delete button (or the block as a whole). Then in the delete onclick function do something like
<div class="block" data-itemid="<?=$item['id']?>">
...
<div class="delete_button">Delete</div>
</div>
...
$('.delete_button').on('click',function(event) {
block = $(event).target.parent('.block');
itemid = block.data('itemid');
$.post('delete.php',[itemid: itemid]...);
});

How do I change pages and call a certain Javascript function with Flask?

I am not sure if I worded my question correctly. I'm not actually sure how to go about this at all.
I have a site load.html. Here I can use a textbox to enter an ID, for example 123, and the page will display some information (retrieved via a Javascript function that calls AJAX from the Flask server).
I also have a site, account.html. Here it displays all the IDs associated with an account.
I want to make it so if you click the ID in account.html, it will go to load.html and show the information required.
Basically, after I press the link, I need to change the URL to load.html, then call the Javascript function to display the information associated with the ID.
My original thoughts were to use variable routes in Flask, like #app.route('/load/<int:id>') instead of simply #app.route('/load')
But all /load does is show load.html, not actually load the information. That is done in the Javascript function I talked about earlier.
I'm not sure how to go about doing this. Any ideas?
If I need to explain more, please let me know. Thanks!
To make this more clear, I can go to load.html and call the Javascript function from the web console and it works fine. I'm just not sure how to do this with variable routes in Flask (is that the right way?) since showing the information depends on some Javascript to parse the data returned by Flask.
Flask code loading load.html
#app.route('/load')
def load():
return render_template('load.html')
Flask code returning information
#app.route('/retrieve')
def retrieve():
return jsonify({
'in':in(),
'sb':sb(),
'td':td()
})
/retrieve just returns a data structure from the database that is then parsed by the Javascript and output into the HTML. Now that I think about it, I suppose the variable route has to be in retrieve? Right now I'm using AJAX to send an ID over, should I change that to /retrieve/<int:id>? But how exactly would I retrieve the information, from, example, /retrieve/5? In AJAX I can just have data under the success method, but not for a simple web address.
Suppose if you are passing the data into retrieve from the browser url as
www.example.com/retrieve?Data=5
you can get the data value like
dataValue = request.args.get('Data')
You can specify param in url like /retrieve/<page>
It can use several ways in flask.
One way is
#app.route('/retrieve/', defaults={'page': 0})
#app.route('/retrieve/<page>')
def retrieve():
if page:
#Do page stuff here
return jsonify({
'in':in(),
'sb':sb(),
'td':td()})
Another way is
#app.route('/retrieve/<page>')
def retrieve(page=0):
if page:
#Do your page stuff hear
return jsonify({
'in':in(),
'sb':sb(),
'td':td()
})
Note: You can specify converter also like <int:page>

Rails/JS - get variable without page refresh

In my app I have a variable which is an integer. The variable is constantly changing and I want it to always show the current integer when a user is on the site without them having to keep refreshing the page.
I know there are a few ways to do this, but what would be the easiest and most unobtrusive way to accomplish this?
For easy sake lets make this the integer
#foo = Post.all
I would supply some code but after research elsewhere I still haven't been able to try and solve this.
Thanks.
As far as I know, server can't send information to client without request from client. So, you can set up regular AJAX requestes for that.
Firstly, you should make separate action in controller, that return your integer in json
def foo_update
#foo = some_new_value
render json: #foo
end
In you .js files set Interval and AJAX request
var ajax_foo_update = function(){
$.get("/controller_name/foo_update",function(data){
$("#elem_to_place_foo").html(data.integer);
});
}
$(function(){
setInterval(ajax_foo_update, 10000);
});
This function will be updating foo every 10 seconds. Also, you #foo should look somehow like {integer: 5}
Don't forget to write right routes.

Categories

Resources