Ajax With JQuery MVC Form Posting - asp.net-mvc

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

Related

Can I capture a param but avoid showing it in the url?

I would like to capture the id of an element that is clicked on and then pass that id to the controller, all without showing the id in either the link or the url param, and without having to write custom ajax loading. Anything like that available in rails out of the box?
What are you trying to achieve (what's the end goal)? It sounds like you want to communicate between the client and server without using ajax or encoding params in the user's url.
The usual ways of doing that, with those constraints, would be:
1) Wrap the click target in a form, and set the id to a hidden value. On click, just post the form. This will require a page refresh, but since it's a POST, won't muck up the url.
2) Set the id in a cookie, force a page refresh, read the id on the server and unset it. This will obviously also require a page refresh, but won't encode anything in the url.
3) Use an invisible iFrame to load a url with the param of interest. This won't require a refresh and the url can be anything, since the user will never see it.
If a page refresh/change is fine, the form route is probably best. If you don't want the page to refresh though, an xhr request is clearly the best solution. It's really simple to do, but an iFrame solution would be a hack that probably meets your needs too.
I am assuming you don't want to show the ID to the user but you need the element ID to hit the server.
You could use a custom request header, but that would require an AJAX approach. Here's a sketch with JQuery
$("a.sends_element_id").click(function(e){
e.preventDefault();
$.ajax({
url: $(e.target).attr("href"),
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('X-Element-ID', $(e.target).attr("id");},
success: function(result) {
// Do something here to display the page
// Eg. http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page
}
});

Ruby on rails ajax request with arbitrary amount of parameters

I'd been working on my little project for several month before I thought that may be my way of handling following problem is 'somewhat' not elegant in RoR and there are more conventional ways:
My service use some javaScript API to retrieve information from particular social network service and processing of information is performed on client side and JS environment stores result of processing. so I need to interact with user without reloading the page: particularly there are some filters I need to work.
let's say I need to filter results of request by age of publication. And there are categories selectors. I want my application works in the following way:
1. user types number of days within publication's age should be - there's no any 'submit' or 'apply' filter buttons
2. filters are being applied after user clicks on category-selectors: they are main UI controllers, formed by RoR helper:
<li class="cat_selector"><%= link_to category.name, posts_path(:cat_id => category.id), :remote => true%></li>
what is the 'usual' method to address this problem? How can I easily 'gather' all control's values in one ajax request by clicking on one of particular links?
thank you!
I would abandon the default rails Ajax handling and write your own, something along the lines of
$('.cat_selector a').click(function(){
$.ajax({
url: this.href,
data: $("#some_form").serialize()
})
})
This would cause matching links to submit themselves over ajax adding data from the form with the id some_form. You could of course build up an arbitrary data object but it's a lot easier to use a form if you can.

Normal pattern for handling Struts 2 Actions in Jquery post/get/ajax calls

I know I am missing something conceptually here and it keeps tripping me up but I will present a use case and would appreciate a best practice response.
$.ajax({
type: "POST",
url: "/myapp/FilterRecord.action",
data: "pageSource=list_edit_add&table=" + table + "&output=" + output + "&selectedIds=" + json_text,
success: function(data) {
document.close();
document.open();
document.write(data);
}
});
In this case, the ajax method of jquery is being called. A Struts 2 action is being performed using the default result type, that is Dispatcher Result. Upon Action.SUCCESS, the success function above is entered. The data being passed in is a complete jsp page, head and body both. In the code above, we are sort of manipulating document.write() in a way which it is not necessarily meant to be used for. The aim of the above is to get both the head section and body section. Some other approaches for setting parts of the page which jquery is better set up for are:
document.all[0].innerHTML = data
${'#someRandomSection'}.html(data)
but neither of them capture the full content being passed to us. What then is the proper way to display the result of a DispatcherResult, that is the entire jsp page which is passed back to us? I have some involved javascript going on for this page, and it is not correctly rendering with the approach I presented in the use case above.
first of all the way you are passing the data is incorrect.. it looks like you are passing it as if its a querystring.. you need to change it to follows:
data: {
pageSource:list_edit_add,
table:table,
output:output,
selectedIds: json_text
}
and you need to specify the dataType
dataType: "html".
Can you setup a jsfiddle for your page..

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