I'm using jQuery getScript in Rails to load an AJAX search on a dashboard page. I just noticed, though, that in addition to properly making the call it's ALSO reloading the entire page (in the background).
I have no idea why this happening.
I checked all my before_filters, all my authentication logic, I tried using different jQuery ajax functions (get, getJSON, etc.), but nothing. it's still reloading the page. also, the two routes are even on different controllers!
Does anybody know what might be going on?
EDIT:
RESOLVED.
I was using an $.ajax({}) function in addition to a $.get() function in order to set a before function. Something in the $.ajax must have been triggering the call, so I simply merged the new functions into one and it resolved my problem.
BTW, though, the xhr.request?, which I discovered in this process, is helpful for detecting javascript calls, and preventing certain actions from responding to javascript.
This jquery javascript was triggering the extra call:
$.getScript(correct_url, function({
$.ajax({beforeSend: function(){}...)}
callback code
)}
You can't use the ajax shortcuts inside the getScript shorthand function like that. The inner .ajax was making its own call. So I simply combined them into one .ajax function
$.ajax({
url: correct_url,
type: 'get',
dataType: 'script',
beforeSend: function(){
}),
success: function (){
<callback code>
}
})
Related
I have a WebApp that does repeated calculations in one Controller Action. I want the page to update, every time a part of the result has been calculated.
So for example at the start of the calculation the browser loads a view that says "Calculations are running", then after the first calculation it says "A has been calculated" and when it's done it loads a View that says "Completed".
SignalR seems like overkill for this, is there any way in Asp.Net?
You can achieve this by using multiple JQuery AJAX Posts. AJAX Posts by default will run asynchronously, therefore you could run all of your Posts at the same time, perhaps when the form loads or on button click. As they complete you can change the text that is displayed on the screen to reflect the result from the last request that completed.
$.ajax({
type: "GET",
url: url,
data: {},
success: function (data) {
$("#calculationStatus").html(data);
}
});
You can also use a HTML progress bar along with any message related to the completed calculation.
I'm not even sure how to ask my question.
I know the basics of ruby on rails and I can make a web app. but I now have a project where I want to have a button on a view that sends data to the controller, but I don't want the controller to send me to a different view, instead I want it to send data back to me (maybe in Json format) and populate something in the view with that data retrieved from the database.
Is this possible? If so how would I go about doing it? What tools do I need if this kind of functionality isn't built into rails itself? I don't know anything about it but could ajax help?
Thanks for the guidance!
You have to make it with javascript.
In your case I advise you to use a simple ajax request with jQuery.
http://api.jquery.com/jquery.ajax/
Jquery is a javascript library that allow you to do this.
1) Include jquery in your html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
2) Make the ajax query:
$.ajax({
url: "/api/your_url",
data: {
test: "parameter send to the rails controller and stored into params"
},
success: function( data ) {
console.log(data);
}
});
What you are referring to is called Ajax. You can use XmlHttpRequest in your client side javascript to send an asynchronous request to the server and register a callback function that will be called on the client when the server responds. In the callback function you can update your webpage with the new information.
I'm a complete Ajax noob and I'm finding myself a little lost in how to best approach things, I've been looking over SO and found a post about Ajax that included this JavaScript:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
I incorporated this into my scripts file for a form on one of the pages in my site and quickly realised this actually attaches to ALL the forms, site wide including the login form.
I want to treat the login form as a special case and actually perform a redirect rather than simply insert the returned HTML fragment into an element on the page.
I'm presuming that replacing 'form' with the ID of the login form will differentiate the login form from 'general' form handling processes and was wondering what are the accepted best practices for this.
Do you have a 'general' Ajax hander like the one above or is it better to have specific JavaScript functions for each form depending on what they need to do with the response?
It sounds to me like you included something generic for a situation which should have been localized. In my opinion blanket approaches like this are not really desirable, especially not with something which is going to affect every form in your application.
The real meat of this to take away is the $.ajax code. Use ajax when you want, and use formal posting otherwise (which is default).
Using an exact reference will of course differentiate certain forms in your application, but this is something which should be done in a view's script, and not in one blanket script which is included application wide.
What I tend to do is use ajax when I want to provide a preview, or if I want to post without the user navigating away from the page.
Sometimes in rare occasions I will have a page which is replaced with a few sliding windows via ajax and then at the end of the series I will want to redirect. When that is the case, I will have my controller return a string which allows the view to redirect to that string in the success function of the ajax call.
I tend to keep mine separate, though others may do differently. They post to different URLs and do different things with the data.
I refer to the form by id:
$('#myformid")
You may wish to use the not equal selector if you just want to apply your function to all forms except your login form.
$('form[id!="loginform"]')...
I've never done ajax stuff myself, and this seems like an ideal feature to add to my app to learn how to do it...
My app maintains a database of jokes.
I'd like to provide a simple way for anyone to add a small banner to the html on their webpage that will display a new joke every N seconds.
It seems the two approaches are:
1) iframe where the url/view hit by the iframe has a meta refresh tag and randomly pulls a joke each time the url is hit. But iframes can resize to fit content, and I'm not sure if browsers will refresh the contents of the iframe.
2) the right way ... ajax. But I have no idea if this is a "big" or "trivial" job for a rails 3 app, and no idea where to get started.
Any pointers on doing this would be deeply appreciated!
I'll use jQuery for this example but the overall technique should work pretty much the same with any other AJAX framework.
In your JavaScript, you'll want to use $.ajax to grab a new quote from your server and setTimeout to get periodic updates; something like this:
var n_seconds = 5; // Or whatever you want.
var timer = null;
function replace_quote() {
// Do a $.ajax call to your server.
$.ajax({
url: '/some/route',
type: 'get',
dateType: 'htm;',
success: function(data) {
// Replace the quote with the new one.
$('#quote-container').html(data);
// And restart the timer.
timer = setTimeout(replace_quote, 1000 * n_seconds);
}
});
}
replace_quote();
If you start out with an empty quote box then you can simply call replace_quote() to give it an initial value through your AJAX call.
You could also use setInterval to call your quote replacer. Then you wouldn't need to manually restart the timer with the setTimeout call but you would run the risk our updates fighting each other if an AJAX call takes longer than n_seconds.
If you still want to provide a link for updating the quote then bind the link to a JavaScript function something like this:
function manually_replace() {
clearTimeout(timer);
replace_quote();
}
Calling clearTimeout will, effectively, reset the timer when they change the quote themselves.
Then, in your Rails app, you'd add a route for /some/route and the controller would simply grab a random quote from your database and then use render :partial => 'quote' to send back just the HTML snippet for the quote without all the usual layout wrapping.
Handling AJAX requests in Rails (or any other framework) is pretty much the same as handling any other request, the only difference is that you won't send back a full page, you just send back a little piece of HTML or a blob of JSON (or XML) for the client to process and render. Hence the size difference between the client-side and server-side outlines above.
Old hand with Prototype, new to jQuery, and writing a simple app to get a feel for the framework (and because I want to use it). I've got an HTML fragment that I load via AJAX, and I want to stick this at the top of a div, with a slide-in transition animation.
This bit works, and does the prepending bit:
// Get the HTML fragment and stick it at the top of the containing div.
$.post("/create_new_thing", function(data) {
$('#container_div').prepend(data);
});
What I'd like to do, and can't figure out, is animate the newly added HTML fragment with a show() effect.
Any suggestions?
Try something like this...
$('#div').load('file.html').fadeIn("slow");
The load function is better suited to your needs, as it's main purpose is to load HTML from a remote file and inject it into the DOM.
Using the "post" function is better for loading a remote page using a POST request (posting data via a form and returning dynamic data based on your post request).
See below...
$.post("file.php", { name: "superuntitled", time: "2am" },
function(data){
$('#div').fadeIn("slow").append(data);
});
jQuery has no support yet for "PUT" requests. So if you really need to use a put request, I can recommend extending the jQuery functionality with a custom function that adds support for "PUT". That said, there are some work arounds! See here for more details! ... http://homework.nwsnet.de/news/9132_put-and-delete-with-jquery
This is what I use for adding a new post to the list:
success: function(data){
$("#posts-container").prepend(data).children().first().hide().show('slow');
}
This assumes the added element is wrapped in a div and is first in the #posts-container.
I am using this
$.post("yourdocument.php", {parameter:"caucana.com"}, function(data) {
$('#contiene_resultados').prepend(data);
});