Show loading screen while performing task in Rails 3 - ruby-on-rails

If my 'create' action takes a while to load (due to doing an API call and then a calculation) what's the best way to show the user a 'loading screen' while this task is performed in the background?

Write some AJAX magic ;) Show the loading image when activated and hide it when the AJAX call is complete. And if you don't want to use AJAX, well, hmm, you could check out this:
http://yehudakatz.com/2010/09/07/automatic-flushing-the-rails-3-1-plan/
There's also a gem out there, that somewhat does that.
But I don't have any experience with that.
I would go for the AJAX method =)
EDIT:
Yeah, you should call the create action with AJAX in jQuery. You could do:
function create() {
$('#loading_image').show();
$.ajax({
type: 'POST',
url: /* URL to your create action: e.g. '/user/create/' */,
data: $('form').serialize(),
success: createSuccessHandler,
error: createErrorHandler,
complete: hideLoadingImage
});
}
function createSuccessHandler(data) {
alert("User created!")
}
function createErrorHandler(data) {
alert("It failed, ffs!")
}
function hideLoadingImage() {
$('#loading_image').hide()
}

Related

Multiple AJAX in one window.onload

I'm sure this question must have been asked before but I'm really struggling
to find the answer anywhere so have finally given up and will consult
the stackoverflow community - hopefully there's someone out there who's seen
it all before and can help me out!
I have a webpage which needs to make some function calls as the page loads. It is an ajax method which calls the Json method from the controller which supplies the data that will be used to draw the chart.
I've successfully displayed one chart on my page but still need to display two more charts. Is it possible to have multiple ajax methods on window.onload function?
Here is my code so far.
window.onload = function () {
$.ajax(
{
datatype: "json",
type: "POST",
url: "/CRM/GetIndustryTypeData",
data: JSON,
success: function (data) {
IndTypePieChart(data);
},
error: function () { alert("Error"); }
});
}
Stephen Muecke's answer will work 100%. Get rid of window.onload = function(){ and have any number of $.ajax() calls - positioned at the bottom of the page or wrapped in $(document).ready(){
}).

Perform RedirectToAction in AJAX post call

I have passed the Model object from the View to controller action method through the AJAX post call. Inside the action method, we have a some business logic to be perform based on the received input fields. if business logic fails, then we will return the error message to user else, then we need to redirect the user to some other page. in this case, Redirection to other page is not working in the AJAX post call.
Could you please provide me the any alternative approach on this?
Note:- i need to perform this post operation in the AJAX call.
Thanks
You can simply check if the status is an error and if so redirect in your ajax call
$.ajax({
url: '/ThingToDo/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (status) {
if (!status.error) { alert(!status.error); }
else { window.location.href = "/Redirecthere/"; }
}

Ajax call on ruby on rails

I have a ajax call using ruby on rails. I'm getting a success but I don't know how to use the data result of the ajax call.
$.ajax({
url: "/search/get_listing?listing_id" + id,
dataType: 'JSON',
success: function(data) {
var listing = JSON.parse(data);
$("#modalPrice").html(data.city);
}
});
Controller:
#listings_data = Listings.find_by(id: params[:id])
render :json => #listings_data.to_json
Using data.city won't work. I'm expecting to get the values retrieve from the model by simply putting . on the variable
var listing = JSON.parse(data);
Still no luck. Help guys. Thanks!
JSON.parse is Ruby code, API of JSON gem. How can you guys use that in Javascript :)
jQuery can process JSON object data directly. Just use:
success: function(data) {
$("#modalPrice").html(data.city);
}
For example, you can render in the controller:
render :json => { :city => #listings_data }
On the JS:
success: function(data) {
var listing = data.city;
}
I'm having similar problems everytime I use AJAX in rails since the response seems to differ depending on how you return the value or how you are handling the success in JS. Try this:
success: function(data, status, xhr) {
var listing = JSON.parse(xhr.responseText);
$("#modalPrice").html(data.city);
}
I usually use Firebug (Firefox Plugin) to set a breakpoint in my success handlers to check the arguments where exactly the response is in. Sometimes it's in the first value, sometimes in some other and then it may be xhr.response or even xhr.responseText. It's confusing me every time.
To use Firebug for this, press F12 on your page, select the 'Script' pane and find the code you want to check. Click next to the row number of your code where you want your breakpoint. In this case, you could've chosen the var listing line. When the code is executed (after your click), the browser will stop there and you can check the passed arguments on the right side.

Confused about passing parameters from JavaScript Ajax call back to controller to render a form

Scenario: I click on some objects,table rows,etc on my page and I get their IDs for example I click on Providers list and get provider_id. And then I click on a button on the page:
Now I have a service that accepts those parameters and passes back to me a JSON which I want to show it in a Table form in my next page. So this button click is responsible for that.
So the page I am gonna show that Table in it is Pharmacy/Patients so I have a
PatientsController#index method.
Now in JS side I am doing an Ajax call like this:
// provider_id is global var and coming from the clicks on other parts of the page.
//so we have some value like 234 for it.
$('.personlistbtn').click(function(e) {
$.ajax({
type: 'GET',
data : { 'provider' : provider_id, 'therapeutic_class' : 'all' },
url: '/pharmacy/patients',
async: false,
success: function (data) {
// not sure what to write in here really.
},
error: function () {
// show some oops error
}
}
});
});
So that makes the call to /pharmacy/patients
Now I am confused how to handle it from there?
PatientsController: Maybe something like this?
def index
if request.xhr?
#my_json = MyNetHTTPFunction.getMeBackJSON(params)
end
end
MyNetHTTPFunction.getMeBackJSON(params) is just a method I have written that accepts the query params I am passing to it ( which hopefully are coming from Ajax call right? and queries the web-service and returns me back the JSON I need to use in my View.

jQuery block UI exceptions

I am using JQuery UI plugin blockUI to block UI for every ajax request. It works like a charm, however, I don't want to block the UI (Or at least not show the "Please wait" message) when I am making ajax calls to fetch autocomplete suggest items. How do I do that? I am using jquery autocomplete plugin for autocomplete functionality.
Is there a way I can tell the block UI plug-in to not block UI for autocomplete?
$('#myWidget').autocomplete({
source: function(data, callback) {
$.ajax({
global: false, // <-- this is the key!
url: 'http:...',
dataType: 'json',
data: data,
success: callback
});
}
});
Hm, looks to be a missing feature in jquery :)
You could use a global flag to indicate if it is a autocomplete call and wrap it in a general autcompletefunction
var isAutoComplete = false;
function autoComplete(autocomplete){
isAutoComplete = true;
if($(autocomplete).isfunction())
autocomplete();
}
$(document).ajaxStart(function(){if(!isAutoComplete)$.blockUI();}).ajaxStop(function(){isAutoComplete = false;$.unblockUI();});
It's not a nice solution but it should work...
try using a decorator
$.blockUI = function() {
if (condition_you_dont_want_to_block) {
return;
}
return $.blockUI.apply(this, arguments);
}
or you can write your own block function that is smarter
function my_blockUI() {
if (condition_you_dont_want_to_block) {
return;
}
$.blockUI();
}
$(document).ajaxStart(my_blockUI).ajaxStop($.unblockUI);
You can set blockUI to work for all functions on the page by adding to a global jQuery event handler. To make sure it doesn't get called on autocomplete ajax calls we have to determine if the call is an autocomplete call or not. The problem is that these global functions don't have that much information available to them. However ajaxSend does get some information. It gets the settings object used to make the ajax call. the settings object has the data string being sent. Therefore what you can do is append to every data string in every ajax request on your page something like:
&notautocomplete=notautocomplete
For example:
$.ajax({data:"bar=1&foo=2&notautocomplete=notautocomplete"})
Then we can put this code in your document ready section before anything else:
$(document).ajaxSend(
function (event, xhr, ajaxOptions){
if(ajaxOptions.data.indexOf("notautocomplete") !== -1){
$.blockUI;
}
});
$(document).ajaxStop($.unblockUI);
Of course the other better idea would be to look for something unique in the auto complete requests, like the url, but that depends on which autocomplete plug-in you are using and how you are using it.
using a modal block (block UI) means blocking any inputs from user, I'd suggest plain old throbber to show 'Please wait..' and to block ( set attributes readonly="readonly" ) ur input controls till the ajax request is complete.
The above UI seems to be self conflicting!

Resources