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.
Related
I have a few ajax calls in my app they all go to the same file server side. i want to know if I can use a variable... I want to have a way to distinguish the call from other calls and of course, use the variable to select which script in the file to send back to the client. I do not need to use the variable after the script has run in any way. Or am i going about this the wrong way?
for example this is one of my ajax calls
var variable1 = 'currentuser1var';
return $.ajax({
type: 'GET',
url: '/users/index',
data: {currentuser1var: variable1},
dataType: 'script',
});
then the script in my server side file would be
if (currentuser1var) { script here }
else if (currentuser2var) { script here }
...
I am not sure how to access the string, inside the object call. Do i need to access the object first then the string? Or just reference the variable some how.
EDIT Tried
if(typeof(currentuser1var) != "undefined") { script here }
to no avail.
If you were using PHP, your server side script would be:
if(isset($_GET['currentuser1var'])) {
... script to process the currentuser1var variable ...
} else if (isset($_GET['currentuser2var'])) {
... script to process the currentuser2var variable ...
}
Aj was right here I guess for php as I did not list what server side code I was using, but simply put, I changed my ajax call to
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentuser1var: 'variable1'},
});
where the key is currentuser1var and the value variable1 is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentuser1var=variable1. And in my destination file add my ruby code there to use the variables.
I make an ajax call to a server and the server returns javascript and jquery code such as
$('someclass').html('<form id='billform'>......</>');
$('#billform').submit();
How do I execute this on the client side?
You could put that code inside a script tag and append it to the body
This procedure is described best here: https://stackoverflow.com/a/611016/4202031
However, it is not recommendet to simply execute some javascript which is loaded via ajax. I would recommend to work with events that would trigger this code which is on your page already.
$.get('/sumUrl', function(data) {
switch(data.action) {
case 'event1':
//do sth.
break
case 'event2':
// do sth. else
break
}
})
You can include the code as a function in your static page, then call the function from the returned ajax call. A small example:
on your static page:
function submitmyform(formcontents)
{
$("someclass").html(formcontents);
$("#billform").submit();
}
on your ajax success method:
$.ajax({
url: "/getform",
method: "POST",
data: $(".myform").serialize(),
success: function(data){
submitmyform(data);
}
});
You have to put your id in quotation marks, and as id instead $ use #
$('someclass').html('<form id="billform"></>');
$('#billform').submit();
You can use eval function from javascript to execute the scritp which are string
e.g.
eval('alert("Hello!")');
I your case
eval('$(".someclass").html("<form id="billform">......</>")');
eval('$("#billform").submit()');
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
So, i'm making a subscribe form.
Jquery
$("<div id='dialog' title='Subscribe!'> <form id='subscribe_form' method='POST' action='/user/subscribe'>" +
"<input type='text' name='subscribe_email' id='email' placeholder='Email Address'> <br/>" +
"<button id='submit_subscribe_form'>Submit</button></p><p id='ruby_bool'></p></form>" +
"</div>").appendTo($("#subscribe"));
When this form is submitted, it sends an ajax call to a Ruby Sinatra listener (sorry if I'm not using the right terminology, haven't really been taught Sinatra, just shown how to use it)
$('form').submit(function(){
$.ajax({
type: "POST",
url: "/user/subscribe",
data: $('form').serialize(),
success: function()
{
Ruby Code
post "/user/subscribe" do
user_Information = EmailList.new
if params[:subscribe_email] =~ /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
user_Information.email = params[:subscribe_email]
puts user_Information.save
#email_validation_result = "True"
else
#email_validation_result = "False"
end
puts #email_validation_result
(Yes i know i shouldn't use regex, but the engines i could find were for PHP)
I want to use the #email validation result so i can know what to put in my success: call in my ajax. Problem is, JavaScript doesn't allow Ruby Injection (according to my god knows how many hours of research) and i cant update a div on the web page that contains that variable async. I want to do this all async, so there is no refreshing of the entire page whatsoever. (If it's not possible otherwise i will concede, but i highly doubt that). I tried to put the div on another page and use the JQuery .load() function, but .erb files aren't recognizable.
Out of ideas and nearly out of sanity.
Thanks!
JavaScript:
$.post( '/user/subscribe', $('form').serialize(), function(data){
// Do whatever you want with the response from the server here
// data is a JavaScript object.
}, 'json');
Ruby/Sinatra:
require 'json' # just for a convenient way to serialize
post '/user/subscribe' do
# process the params however you want
content_type 'application/json'
{ :ok => #is_ok }.to_json
end
Without the JSON library you could end your method with just some valid JSON markup, like:
%Q[ { "ok":#{#is_ok} } ]
JavaScript/AJAX will post to the server, the matching Sinatra route will process the request, and the string result of that method (not done via puts) will be sent as the response to the method. The jQuery AJAX handler will receive it, parse it as JSON and invoke your callback function, passing the JavaScript object it created as the parameter. And then you can modify your HTML DOM as desired, client side.
I hope this is not too much of a newbe question but I've been pulling my hair out for a while now so thought I'd give in and ask for my first piece of advice on here.
I'm trying to read an external xml file using javascript / jQuery / ajax and place the retrieved data into an array so that I can then reference it later.
So far I seem to be doing everything right upto the point I put the data into the array but then I'm struggling to to read the data anywhere other than inside the function where I create it. Why am I not able to access the Array from anywhere other than in that function?
Here is my code...
Please help!!
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser
});
function do_xmlParser(xml)
{
var myArray = new Array();
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
console.log("inside "+myArray); // This outputs the array I am expecting
return myArray; // is this right???
}
console.log("outside: "+myArray); // This does NOT output the array but instead I get "myArray is not defined"
You're defining do_xmlParser as a callback to an asynchronous function (success of the jquery ajax call). Anything you want to happen after the ajax call succeeds has to occur within that callback function, or you have to chain functions from the success callback.
The way you have it now, the actual execution of code will go:
ajax -> file being requested -> console.log ->
file transfer done -> success handler
If you're doing some critical stuff and you want the call be to synchronous, you can supply the
async : false
setting to the ajax call. Then, you should be able to do something like this:
var myArray = [],
do_xmlParser = function (xml)
{
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
};
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser,
async: false
});
console.log("outside: " + myArray);
The async option doesn't work for cross-domain requests, though.
NOTE
I don't recommend doing this. AJAX calls are supposed to be asynchronous, and I always use the success callback to perform all of the processing on the returned data.
Edit:
Also, if you're into reading... I'd recommend jQuery Pocket Reference and JavaScript: The Definitive Guide (both by David Flanagan).
look close and you will see. You are actually firing up an array that dosen't exist. You have declared myArray inside function. Try do something like this.
console.lod("outside :"+do_xmlParser(xml)); // I think that when you merge a string and an array it will output only string, but I can be wrong.