Prepending and animating text loaded via AJAX with jQuery - jquery-ui

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

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

Howto process Ajax returned data using rails3.1 and jquery

I'm using the data-remote along with data-URL to make an Ajax call via jquery ujs and it is working.
However, I can't understand how I'm to process the returned value.
For example, I have a controller action which returns some HTML - how do I attach a JS function (I presume) to replace the HTML in an existing div when the Ajax call finishes? I've set data-type to :html btw.
I can see the HTML is being returned by sniffing the network traffic.
I've got it to work by writing my own Ajax call (rather than using jquerys ujs version) but it feels as though I've reinvented the wheel - but I can't find how to use jquerys data-remote to make the call for me, and to then have it update a div (for example).
Thanks,
Ian
i presume that you have a button with the id "button" and a div with the id "add_some_content"
$("#button").click( function(){
$.get("some_random_url", function(data) {
$("#add_some_content").html(data);
});
});
or as jxpx777 pointed out:
$("#button").click(function(){
$("#add_some_content").load("some_random_url");
});
if you now press on the button, an ajax get request for your url is made. the answer from that page is attached to the div.

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