How to use a JavaScript variable in erb code in Rails? - javascript

I have a JavaScript variable:
var selectValUser = $('.select_user :selected').val();
I need to use this variable in erb code on the same page, i.e
<%= get_free_hours_for_user(selectValUser) %>
How can I do it?

You cannot do it because javascript run on client side while the code in ERB file runs at server side, you can send the value using ajax request,
Plus here is an awsome rails cast
Here is an example to send message from javascript to controller; When user click on apply we have an action 'set_id' in controller, it get the power, do the validations etc, the show the message in 'id_message' div in views.
$('#apply').live('click', function(event, data, status, xhr) {
event.preventDefault();
return $.ajax({
url: '/users/registrations/set_id',
type: 'GET',
data: {
code: $('#user_id').val()
},
success: function(data, event, status, xhr) {
$('#id_message').html(response);
return $("#id_message").show();
},
error: function(event, data, status, xhr) {
$('#id_message').html(response);
return $("#id_message").show();
}
});
});
Hope it would answer your question

There is no way to do it directly. Reason is, html runs in your server side whereas javascript runs in your local browser.
Additional discussion can be found here.
How to pass a javascript variable into a erb code in a js view?
And regarding different way to try it out, you can start with this.
http://jing.io/t/pass-javascript-variables-to-rails-controller.html
and
http://www.ruby-forum.com/topic/3818171

Related

Jquery AJAX button call in Umbraco BackOffice

Hi I just created a simple new option for umbraco backoffice, it is a simple html page which displays a button to click.
Simple form
This button should send an ajax call to an UmbracoApi, but the request never reaches the webapi. Below the Api Code:
API Code
The Ajax call is a simple Jquery Ajax call in the event click of the html button.
I'll appreciate any help you can provide me, in order to complete this ajax call.
I think yor problem is the way you are calling it:
not sure if url casing not same as Controller and action will cause routing failure or not, but might as well make then the same
you action is binding a primitive type, from my understanding of webapi - primitive type will check at querystring otherwise specifically tell it to look at body
more info about this, checkout https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
so base on above two statement, try change your call to:
$("#btnGetData").click(function() {
$.ajax("http://localhost:44302/Umbraco/Api/StripeBackOfficApi/GenerateLockBoxile?date=" + $('#txtDate').val(), {
type: "GET"
}, cache: false, success: function(data, status, headers, config) {
if (data) {
alert("Done!");
}
}, error: function(jqXHR, timeout, message) {
console.log("Error: " + message);
}
});
});

How to display data from mysql with id sent with javascript ( Adobe Phonegap )

I make a menu link with javascript. By using the parsing in php I display a menu with the help of javascript. The problem is how do I display data in accordance with the "id" which has been on the destination page.
Here's the code in index.html
function loadkategori(idnya){
$('#contentID').load('kategori.php?id='+idnya, function(){
$('#myListview').listview().listview('refresh');
});
}
$(document).ready(function(){
$.ajax({
url: 'http://localhost/fiqi/fiqi2/kuliner/www/parsing2.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
// $("#listview").append("<li><h2>"+item.namatempatnya+"<p>Kalimat</p></h2></li>");
// seharusnya menggunakan class, tidak inline function
$('#listview').append('<li data-filtertext="form checkboxradio widget checkbox input checkboxes controlgroups" onclick="loadkategori('+item.idkat+')">'+item.namakategori+'</li>');
});
// $("#listview");
// $('ul').listview('refresh');
$('#listview').listview().listview('refresh');
// $('#element').collapsibleset('refresh');
},
error: function(){
alert('Error terjadi');
}
});
});
here's the code in kategori.php
The code in kategori.php doesn't work on adobe phonegap.
I couldn't implement you code but as far as i understand, You need to use some http request function to get data from serverside php rather than using load(), go for using $.get(). That might work out as a solution to your problem.
function loadkategori(idnya){
var data = $.get('kategori.php?id='+idnya, function(data,status){
//PROCESS YOUR DATA OR CALL YOUR FUNCTION TO POPULATE YOUR LISTVIEW
});
}
Secondly you should use either xml or json data for client server communication. That would make your program simple and more efficient. You might paste your php code instead of putting screenshot so that some editing or testing can be done.

Correct jQuery syntax for doing a $.post with a header (ASP.NET MVC)

I'm working on a ASP.NET MVC project that uses some jQuery on the client side. I have a jQuery call like this, which works correctly:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
I want to do the exact same call, except I also want to send in a custom header. I am able to successfully create and send a custom header like this:
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
url: "/report_observation/" + submitType,
cache: false,
type: "POST",
data: {
'viewModel': $('form').serialize(),
},
headers: headers,
success: function (data) {
// Deal with the data that came back from the ASP.NET MVC controller
},
error: function (response) {
alert("Error: " + response);
}
});
There are two problems with this second bit of code. One is that I have to make a custom url to go to the correct controller, and I don't know of a way to simply use $('form').attr("action") to automatically go to the correct place.
The second -- and bigger -- problem is that I'm not able to pass over the form data with $('form').serialize() as I could in the one liner $.post example. Doing a #Html.Raw(Json.Encode(Model)) in my Razor cshtml file doesn't send over the model for the whole form, presumably because this code is within a partial view that doesn't know the state of the models in the other partial views that make up this form.
Anyway, I'm thinking there must be an easy way to take this code...
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
...and incorporate the headers property into this bit of code:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
However, I can't figure out the correct syntax. Any ideas?
OK, I figured it out. The second example can indeed work if the data field looks like this:
data: $("form").serialize(),
In other words, I had to NOT assign it to the viewModel parameter.
yes, for the second problem use that dev5000 says, and, for the URL, simply get the value for the attribute action fo the form and use it:
var url = $("from").attr("action");
$.ajax({
url: url,
...
})

Call a ruby method with different parameters embedded in javascript

I have this ruby method:
def something(sometext, jsvariable, rubyobject)
return HTMLOBJECT
end
And I would like to call this method like this in a javascript function:
$("#someid").append('<% something("sometext", '/jsvar/', rubyobject) %>');
Its not working.I don't know how to call this method from a javascript function with proper
formatting of the variables. I don't really know the exact syntax for it.
Any help is much appreciated.
UPDATE: This is what I'm trying to do
function somejsfunc(){
$.ajax({
url: "/app/SomeController/someMethod",
data: {'something': something }
success: function(data){
var $response1 = $(data);
jsvar = $response1.find('#anotherselector').text();
$("#someid").append('<% something("sometext", '/jsvar/', #rubyobject) %>');
}
});
}
Please Note
def something
is a generic method which returns a HTML DOM element based on these parameters,along with
other data passed into it.Thanks.
You can not do this, because erb templates compiles before application startup. Use remote requests to take info from server if you want send some js parameters.
UPD: Something like this
$.ajax({
url: '/some_url',
data: { jsvar: jsvar },
success: function(data) {
$("#someid").append(data.sometext);
}
});
Normally our ruby runs on the server and your JavaScript runs in the browser, so calling one from the other is pretty much impossible. You may of course resort to Ajax as #uselesssmile suggester, but that involves a whole lot more than a simple method call. On the other hand you can compile your ruby to JavaScript using opalrb, then you can package it into your JavaScript on the client and call it directly.

Getting rss feed with jquery and ajax

I found this site that allows to convert RSS feeds into json.
It also provides a way to specify a callback, so i think users are able to make jsonp calls to this web service.
However, i tried different ways to do that but none worked.
Here is my code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://www.blastcasta.com/feed-to-json.aspx',
dataType: "jsonp",
jsonpCallback: "loadRSS",
data: {
feedUrl: 'http://xml.corriereobjects.it/rss/homepage.xml',
param: "callback"
},
success: function (data) {
var list = "";
for (var propertyName in data) {
list+=data[propertyName];
}
console.log(list);
},
error: function(xhr, ajaxOptions, thrownError){
alert(ajaxOptions)
}
});
});
Whatever i try, the success handler doesn't get executed. I get error handler instead.
I tried with jsonpCallbak: "callback", jsonpCallback: "?", param: "callback" and other values too but without success.
I have to use ONLY javascript without the support any server side scripting language (no aps, no php, etc.)
Did someone get this service working in his site?
Any suggestion would be really appreciated!
I find jQuery JSON API not suitable for this kind of JSON response that provides BlastCasta service. It assigns JSON to a custom variable, specified in URL, and doesn't uses callback functionality JSONP operates with. For example this URL:
http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml&param=rssFeed will return following response:
rssFeed = { "rss": { "channel": /*...*/}}
So, script injection technic may be used:
/* URL of the BlastCasta service and his parameters:
feedUrl :== escaped URL of interest (RSS Feed service)
param :== javascript variable name which will receive parsed JSON object */
var url = "http://www.blastcasta.com/feed-to-json.aspx"
+"?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml"
+"&param=rssFeed";
/* since the service declares variable without var keyword,
hence in global scope, lets make variable usage via window object;
although you can write param=var%20rssFeed" in the URL :) */
window.rssFeed = null;
$.getScript(url, function() {
/* script is loaded, evaluated and variable is ready to use */
console.dir(window.rssFeed);
/* some feeds are huge, so free the memory */
window.rssFeed = null;
});
Update:
here's an example that works for your code:
$.getJSON("http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http://xml.corriereobjects.it/rss/homepage.xml&param=?", function(data) {
console.dir(data);
});
problem is, that I get some javascript errors with returning json:
see this jsfiddle

Categories

Resources