dustjs rendering client-side not working - dust.js

Using dustjs for templating engine within Expressjs 4. Want to render the template client-side when user fills out a form and clicks a search button using xhr. Everything seems to go fine so far as getting the json from xhr call but dust.render does not render the result.
Here is the dust template on the page:
&ltscript id="result-template">
// extra table tags removed for brevity
{#search_results}
{fname}
{lname}
{accountId}
{email}
{status}
{/search_results}
</script>
<div id="output">
Below is the js/jquery in an external js file making the xhr call to server-side. Inside the success callback is where I'm trying to render the result from the call, basically user fills-in a search form and clicks submit:
$(document).ready(function () {
$('#main').on('click', '#search-btn', function (e) {
e.preventDefault();
$.ajax({
url: '/support/search/ah',
type: "post",
headers: {token: sessionStorage.getItem('somekey')},
data: {'phone': $('#mobile').val(),
'email': $('#email').val(),
'fname': $('#fname').val(),
'lname': $('#lname').val()
},
success: function (data, textStatus, request) {
var source = $("#result-template").html();
var compiled = dust.compile(source, "intro");
dust.loadSource(compiled);
dust.render("intro", data, function(err, out) {
$("#output").html(out);
$('#search-result').dataTable();
});
},
error: function (data, textStatus, request) {
// handle error
})
})
xhr call is successful, and I can see that 'data' variable contains the json with values, however, I'm not able to render them using dust.render and there are no js errors being observed when the page loads or when the results come back.
Here is the json result from xhr call:
{"search_results":[{"fname":"Duke", "lname":"Wellington","accountId":"007","email":"duke_wellington","status":"Breathing"}]};
I tried the same template with same json results at atakdubya.github.io replacing its array example and it works fine.
If anyone can point out what I'm doing wrong it would be immensely appreciated.

Depending on your browser, you can't have a script tag with no type or it will be interpreted as Javascript, and Dust isn't valid Javascript.
Try adding type="text/dust" to your script tag. This JSFiddle works for me.
http://jsfiddle.net/Lutr4h2e/1/

Related

Rails Ajax call on ajax uploaded image

I'm learning Rails and I understand how ajax call works. But I have a problem: I don't know how can I bind an ajax function on object loaded in the DOM with another ajax function.
In my demo page I use Plupload plugin to upload some files: when the script finish to upload the files I load, with ajax, the thumbnails in my preview window. Everything works fine.
$("#multi_upload").pluploadQueue().bind('UploadComplete', function(up, files) {
$.ajax({
type: "GET",
dataType: 'html',
url: $('.wmk_grid#large_grid').data('gallery-url'),
success: function(result) {
$('.wmk_grid#large_grid').html(result);
}
});
});
$('.plupload_header').remove();
}
Every thumbnail has also a "delete" button: on this button I attach a rails ajax call to delete the single picture.
My coffeescript is this:
$ ->
$('.img_action_remove').bind 'ajax:success', (event, data, status, xhr) ->
$(this).closest('li').remove()
I know the issue: when I load my page I don't have any item with .img_action_remove class: i create them when I upload the pictures with plupload.
How can I fix the second ajax call?
Update: fixed with this script:
$(document).on "ajax:success", ".img_action_remove", (e) ->
$(e.currentTarget).closest("li").remove()
JQuery Delegation
When I load my page I don't have any item with .img_action_remove
class: i create them when I upload the pictures with plupload
$('document').on 'ajax:success', '.img_action_remove', (event, data, status, xhr) ->
$(this).closest('li').remove()
This binds the event to the document & delegates to the class. Means that you can create the class any time you want, and JS should always capture the event

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.

JQuery Mobile & URL Parameters white flash on reload

I am using query mobile for a phonegap application, I am passing through parameters through the url to the next page.
For example:
main.html?id=1, menu.html?id=2 etc
To allow this I have to turn ajaxEnabled to false to allow it to pass through the information I need. In doing so I am unable to use transitions from page to page which means I get a white flash as the page reloads.
I am generating these links dynamically.
$.ajax({
url: 'URLTO WEBSERVER',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var list = '<li><a href="menu.html?idcat='+item.id_cat+'">'+item.category_cat+'</li>'
output.append(list);
});
},
error: function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
output.text('There was an error loading the data.')
}
});
Is there a solution?
you can use method jquery serialize data for your paramater.
via changePage method in jquery
I hope solved :D
I think he is concerned about the "white plash page" that happens after the request is completed from server and then he calls changePage.
He is not worried about how to send parameters to server etc. This is assuming all that is working fine.

rails :remote ajax always triggers failure

I have a rails 3 remote form tag that I am trying to submit via ajax, from what I can see things seem to be working alright but for some reason the ajax:success event is never fired but the ajax:error always is. When I open Firebug I can see the request is returning with a 200 status... I thought a 200 status would trigger the ajax:success am I missing something? Here is my javascript:
$('#institution-select-form')
.bind("ajax:complete", function() {
alert('complete!');
})
.bind("ajax:beforeSend", function () {
alert('loading!');
})
.bind("ajax:error", function (xhr, status, error) {
alert('failure!');
})
.bind('ajax:success', function(event, data, status, xhr) {
alert('success!');
});
The error event can be triggered by other issues, not just a non-200 status. For example, if you're returning JSON or XML and the data being returned is invalid and can't be parsed, that will result in an error event.
To diagnose it, add to your ajax:error function:
alert(status);
alert(error);
You should add
data: { type: 'json' }
to your form

Strange jquery post problem, wrong post url is used

I have a form I wish to submit via ajax usind the jQuery $.post command.
The form looks like this:
<form action="/wine/merlot/reviews" class="new_review" id="new_review" method="post">
And the jquery call is:
$(document).ready(function() {
$('#new_review').submit(function() {
$.post($(this).attr('action'), $(this).serialize(), null, 'script');
return false;
});
});
I get the following error on the server:
ActionController::MethodNotAllowed (Only get, put, and delete requests are allowed.):
From what I can tell by digging in with firebugs console the problem is the post is posting to this url:
/wine/merlot instead of /wine/merlot/reviews
I can't for the life of me figure out why this is the case.
OK. It turns out I'm an idiot. I had another div on the page with the id "new_review" so I guess it was looking at the wrong element. Renamed and everything working now.
I could not get a form to submit via ajax using the jQuery $.post command with Rails 2.
I modified Ryan Bates' Railcast 136 to submit via a put instead. The kludge I used was to check the (params[:id] == 'update') in the update action to check for this ajax request.
episode-136/store/public/javascripts/application.js
jQuery.fn.blurWithAjax = function() {
this.blur(function() {
// GOOD .ajax javascript update action works even though create on Rails2 does not
jQuery.ajax({
type: "PUT",
url: "/reviews/update",
data: jQuery(this).serialize(),
dataType: "script",
callback: null
});
return false;
})
return this;
};
jQuery(document).ready(function() {
jQuery("#review_content").blurWithAjax();
});
You need to make the parallel changes also;
def create => def update
app/views/reviews/create.js.erb => app/views/reviews/update.js.erb
Not sure, but try /wine/merlot/reviews/ instead of /wine/merlot/reviews?

Resources