Calling different Views in one Controller Action? - asp.net-mvc

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.

Related

Rails 4 - if boolean is true then move object to true (without refreshing page)

I have been googling around, but maybe my terminology is not allowing me to find answers I am looking for as I'm quite new to programming.
Basically, if an object is true (my checkbox has been checked and the object is completed) how can I then move that object off of the main page, and sort of 'archive' it I guess, with the completed objects only. All whilst staying on the same page.
E.g. user clicks checkbox, marks completed > object moves to completed > user stays in same page and can rinse and repeat cycle.
I'm not asking anyone to create this for me, far from it -- my question is, can anyone point me in the right direction on maybe rails doc or something to what I want to do so I can read about it and figure out how to do it?
Thanks & Best Regards
You would use Ajax (Jquery library) and potentially .delegate().
Here's an example of Ajax:
Make a new JavaScript file in your javascript pipeline /app/assets/javascripts/my_new_ajax_file.js
In said file, you need to make the ajax call which has the capability of making an asynchronous call to a url which in your case I beleive you're looking for.
Let's say you have a route called /api/v1/checkbox which points to Api#check
(Assuming you have jquery included BEFORE this js file)
In your Javascripts file:
$(document).ready(function() {
$('.the_class_on_your_checkbox').click(function() {
myAjaxCall();
});
});
function myAjaxCall() {
$.ajax({
type: 'POST',
url: '/api/v1/checkbox/',
data: {
// Any data you need to send through
},
success: function(response) {
console.log(response);
},
error: function() {
console.log("Something went wrong");
}
});
}
Now, when you click on your checkbox, it will make a call to your route which I'm assuming you have defined in your controller.
You can now manipulate backend data in that action (Inside of your controller) and send and receive data from your database.
The way you send info back, it in the response (In the success function in the ajax call) you receive JSON from your controller like so...
def check
render json: "OK"
end
Now in the Ajax call you can manipulate the JSON you receive back (Put whatever you need to from the database instead of OK)
If you need clarification of anything let me know, I don't know how much you do or don't know so I just tried to cover a bunch.
EDIT: Function typo
as i understand you want to update object without refreshing page.
so you have to use ajax request

Ajax With JQuery MVC Form Posting

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"]')...

rails run first query over ajax (after view is loaded)

I have pagination + parameters set up over ajax, and working properly.
However, when first loading the page, it takes a while. Is it possible to first load the view, and then load the content over ajax (just like clicking page 2 would for pagination over ajax)?
EDIT/
Is it really stupid to use a parameter conditional? Like in my controller around my query if params[:load] == "ajax" as well as the parts of the view that use this data. And in jquery, when the document is ready (view loaded), call the parameter with a get: $.getScript(window.location.pathname + "?load=ajax");
???
I have done it quite a lot. Load the whole view first, which contains some basic layout, then load the actual important contents using ajax. So in my controller:
class PriceController < ApplicationController
def price
# do something in order to render the page price.html
end
def price_f
# render the partial which contains heavy sorting of datas
render :partial => "price_f"
end
end
in jquery
$(document).ready(function(){
$.ajax({
url : "/price_f.html?page=1"
success: function(data){
$("#price_container").html(data);
}
});
})
Assuming you're using jQuery, you should be able to just do something simple like this after the document is ready. Really, all you're doing is telling your pagination URL that you want Page 1 instead of Page 2, etc.
$(document).ready(function(){
$.get({
url: "/url/for/your/page/data"
});
});
To get rid of the current initial page load (I would have to see your specific code to tell you exactly what to remove/change):
Remove whatever code is in your controller that does the query, loads the data, etc.
Remove the parts of your view that are then using this initial data, maybe just sticking a loading gif in there until it's replaced by your ajax data.
Fire the ajax request -- the page will be loaded while it waits for the controller to sort and deliver the data.

rails 3: (probably ajax question) need embeddable a banner on a html page that pulls a different 'joke' from our app every N seconds

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.

Rails AJAX request also calling entire original page

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>
}
})

Resources