Howto process Ajax returned data using rails3.1 and jquery - ruby-on-rails

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.

Related

Rails ujs for partial DOM replacement?

My front-end structure is like below:
<div id='item-list'>
# List of items to be replaced every time
</div>
<form>
<submit/>
</form>
The idea is that, every time when the submit button is clicked, my JS would send AJAX request, and the server would return an HTML partial for the item-list, and in my front-end, the item-list would be replaced with the ajax return.
However, since there're also some use of UJS in my item-list, the bindings no longer works after the replacement.
I believe it's the problem that the UJS code didn't execute when the replacement happens. I want to ask how to force the execution of UJS code?
Thanks a lot
You'll need to delegate your event bindings from an element which is always going to be present on your page (typically document):
$(document).on("submit", ".element", function(){
//stuff
});
The problem you have is that Javascript only works with elements in the actual DOM. It doesn't, nor can it work with, elements which are appended after the DOM has been loaded
This means you have to bind the javascript events to elements which will always be present in the DOM, and delegate from them
--
That's the best I can do with what you've sent so far - if you give more context, I'll be able to provide a richer answer

Sending form contents as both html and ajax?

I have an admin form that updates a model via a html submit. I'd like to be able to send the form's contents to an Ajax modal dialog for a 'preview' via a link or button in the admin form.
Is there a way to send the form's contents to the modal dialog via Ajax without breaking the html submit? So far all I can do is get the data into the modal as html which breaks the js rendering. All the Ajax submit examples I find attach to the form which will break the html submit.
Suggestions and/or pointers are appreciated.
We are using Rails 3.2.12 for what it's worth.
I suppose it depends on how you are rendering your modal. If you're doing it server side and just need to get the form values to your ajax controller action you could do something like this with jquery"
$.post(ajaxUrl + "?" + $("#myform").serialize())
to generate a query string of your form values that you could sent to you ajax model.
Or if you're building the modal client side try
$("#myform").serializeArray()
to get an array of name, value pairs
This is what it took to get this to work under Rails 3.2.12
View:
<%= link_to 'Preview Promotion UI', admin_preview_promotion_url, id: :promotion_preview %>
The above link is inside the form do/end.
Javascript in application.js
$("#promotion_preview").live('click', (function (event) {
event.preventDefault();
$.post("/store/admin/promotions/preview",
$(event.currentTarget.parentElement).serialize().replace('=put&', '=post&'),
{},
"script"
);
}));
Rails.js injects some hidden code in the page that sets the type of response to PUT and then gets in the way of the routing. At least in this case simply replacing PUT with POST fixes things.
With this bit of code I can post my form updates as usual and activate a modal dialog "preview" using the form data.

Passing data between pages with jQuery Mobile?

So I've just started learning jQuery Mobile, and I've learned how it loads all links via ajax without actually loading the next page. Several of my pages use forms and GET to pass data on to the next page-- How can I do this while using jQuery Mobile?
One thing that I think is cool about JQM is that you don't have to use parameters to pass data between pages. Since you're in the same DOM as the first page, you can access data using plain old variables, i.e.
field1 = $('[name=field1]').val();
field2 = $('[name=field2]').val();
And so long as you're using the ajax feature of JQM you could do the following in the next page:
$('.title').text(field1);
I made a jsfiddle example for you.
Other ways would be to use the localStorage or sessionStorage api or there are also some plugins mentioned in the docs.
page params
JQM router plugin
Commonly, there 2 method for transfer parameter between jQuery Mobile page.
Modify Ajax address at first page, and parse the ajax to get parameter in next page.
Using HTML5 sessionStorage, a kind of WebStorage, to transfer parameter.
This is the method use ajax address to transfer parameter.
How to pass and get Parameters between two Pages in Jquery Mobile?
Using sessionStorage/localStorage to transfer parameter, you can add this code at first page,
<a href="#page_Parameter1" onclick="sessionStorage.ParameterID=123">
Before go to next page, parameter id is storaged into sessionStorage.
</a>
In next page, you can use this method to take parameter content,
$('#page_Parameter1').live('pageshow', function(event, ui) {
alert('Parameter ID: ' + sessionStorage.ParameterID);
});

How to make getJSON to update correctly an element after page loaded in jQuery Mobile?

I'm trying to get a getJSON result to update an HTML element on page load, within a jquery mobile loaded website.
Now, I've read I should not rely on ready(), but bind to pageInit. So I tried, but it just won't work. I've tried many other events that could be logical to try within the API event documentation, without any success.
The closest I come to success is after the page is loaded, via ajax, if I refresh the page manually (with the browser's refresh button), getJSON does update the corresponding HTML element. And you guess, it's not what I want to achieve. Here is what the code looks like now, and where it is placed...
<div data-role="page">
<script>
$( '#pageContainer' ).live( 'pageinit',function(event){
//an alert() here does fire right before the page is shown in the browser
//here is the getJSON code.
});
</script>
Now, I need help to try to figure how to make it work. I only want an element X in the page to update with the text returned from a jSON when the page appears in the browser! Like a normal ready() function would have done !
(Maybe it is relevant to specify I'm running RC2 ?)
If you can't use JSONP here, have you tried setting a setTimeout()? You have to trigger a callback after the json object is loaded so timing is essential.

Prepending and animating text loaded via AJAX with jQuery

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

Resources