I have the following in a .js.erb file, being returned after a form being submitted with remote: true.
create.js.erb
$("#flash-notices").html(" <%= escape_javascript(render(partial: "/shared/flash_messages", locals: { form_errors: #artist.errors.full_messages } )) %> ");
$("#flash-notices").fadeIn(300).delay(3000).fadeOut(300);
...
However, what is being returned to the browser is this:
<textarea data-type="text/javascript" response-code="200">
$("#flash-notices").html(" <ul>\n <div class=\"alert alert-success\">\n <li class=\"alert-item\">Artwork saved<\/li>\n <\/div>\n <\/ul>\n ");
$("#flash-notices").fadeIn(300).delay(3000).fadeOut(300);
...
</textarea>
How can I stop the first level of JS escaping which is stopping the jQuery from executing?
Related
I'm trying to build a kind of calculator with rails 5.2.
I need to update results fields while I'm writing my input fields. Everything is working perfect with AJAX if I press enter Key on my keyboard but it doesn't work if I try to automaticly submit the form as soon as a field is modified.
the view input.html.erb
<%= form_with url: achatproprietaire_output_path do |form| %>
<div class="form-group mb-3">
<%= form.label :credits_conso, "Montant des crédits conso", for:"example-helping" %>
<%= form.text_field :credits_conso, id: "example-helping", placeholder: "crédits conso", class: "form-control", id: "crédit_conso" %>
<span class="help-block"><small>en euros par mois</small></span>
</div>
js file calles un application.js
$(document).ready(function(){
$("#crédit_conso").keypress(function(){
//this.form.trigger('submit.rails');
Rails.fire(form, 'submit');
});
});
js.erb file correctly called with enter key
$('#output_col').replaceWith("<%= j render 'output', capacité_emprunt_maximal: #capacité_emprunt_maximal,
montant_mensuel_maximal: #montant_mensuel_maximal,
taux_interet: #taux_interet,
taux_assurance: #taux_assurance %>");
And I have no render or redirect_to in my controller.
I've also tried to put onchange: "Rails.fire(this.form, 'submit')" in the form fields but it submit the form without AJAX.
In some...controller.rb i have string
redirect_to posts_path, notice: 'Login or register'
In some...views.html.erb
<% if notice.present? %>
<div class="alert alert-info fade in">
×
<strong><%= notice %></strong>
</div>
<% end %>
In application.js i add
$(".alert-info" ).fadeOut(3000);
$(".alert" ).fadeOut(3000);
$(".alert-success" ).fadeOut(3000);
$(".alert-danger" ).fadeOut(3000);
but alert , do not want to close itself
what am I doing wrong ?
I think you are using jquery. You have to call $('.alert').delay(5000).fadeOut(); with in jquery $(document).ready method that ensure script executed after DOM loading.
First be sure that you add your application.js to your layout page.
Add following code
$(document).ready( function() {
$('.alert').delay(5000).fadeOut();
});
demo
I just want to do like this.
<p><form blabla></form><form blabla></form></p>
so, on rails 2.8.3 I wrote like this.
<p>
<%- form_tag blabla -%><%- end -%>
<%- form_tag blabla -%><%- end -%>
</p>
but the result is like this.
<p></p>
<form blabla></form>
<form blabla></form>
<p></p>
How can I avoid paragraph tag automatically inserted?
It's not valid html to nest form tags inside a p tag so your browser is trying to fix it for you. http://www.w3.org/TR/html401/struct/text.html#h-9.3.1
You can verify that the browser is altering this this by:
telnet localhost 3000
GET /wherever/this/is HTTP/1.0
And you will see something like:
<p>
<form action="/dog" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="HxzAQS/UMwdXmcMzX+qk9eV49JCmwnds9bekrr3YKj0=" /></div></form><form action="/dog" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="HxzAQS/UMwdXmcMzX+qk9eV49JCmwnds9bekrr3YKj0=" /></div></form></p>
I have a partial which returns results from the Amazon-ecs API (searches for books). It takes about 2.5 seconds to return values, so I want to add a spinner (and ideally hide the search button) but I've had a tough time getting it to work.
I already have javascript refreshing the partial with the results. I'd just like the button to give me a spinner (and hide the search button) until the partial finishes reloading.
Here is my main view (index.html.erb) which renders a partial of search results, each of which is added temporarily as an object in AmazonItems:
<%= form_tag amazon_items_path, :method => :get, :remote => true do %>
<p>
<%= text_field_tag :query, params[:query] %>
<span id="spinner" style="display:none">
<%= image_tag 'ajax-loader.gif' %>
</span>
<span id="search_button">
<%= submit_tag "Search" %>
</span>
</p>
<% end %>
<h1>Searching Amazon</h1>
<div id="amazon_returned">
<%= render 'amazon_returned' %>
</div>
My only JS code is in the update.js.erb file, which looks like:
$("#amazon_returned").html("<%=j render 'amazon_returned' %>");
I'm sure this is easy, but I can't get it work. Thanks!
EDIT: my partial "_amazon_returned.html.erb" looks like
<table>
<% for amazon_item in #amazon_items %>
<td> amazon_item.title </td>
...ETC...
<% end %>
</table>
You can hook into the before event to do this:
$(function() {
$("form").on("ajax:before", function() {
$("#spinner, #search_button").toggle();
});
});
Then, in your update.js.erb, add this again to toggle them back:
$("#spinner, #search_button").toggle();
Went with Dylan's answer, added the toggle to the update.js.erb and inserted the following into the view:
<script>
$(function() {
$("#search_button").click(function() {
$("#spinner, #search_button").toggle();
});
});
</script>
Very cool! Thanks again for the help.
I have this markup in an MVC app.
<div id="ingredientlistdiv">
<% Recipe recipe = (Recipe)Model; %>
<% Html.RenderPartial("IngredientsListControl", recipe.Ingredients); %>
</div>
<div id="ingrediententrydiv" align="left">
<% using (Ajax.BeginForm("Add Ingredient", "Recipes/UpdateStep2", new AjaxOptions { UpdateTargetId = "ingredientlistdiv" }))
{ %>
<p>
<label for="Units">Units:</label><br />
<%= Html.TextBox("Units", 0)%>
<%= Html.ValidationMessage("Units", "*")%>
</p>
<p>
<label for="Measure">Measure:</label><br />
<%= Html.TextBox("Measure")%>
<%= Html.ValidationMessage("Measure", "*")%>
</p>
<p>
<label for="IngredientName">Ingredient Name:</label><br />
<%= Html.TextBox("IngredientName")%>
<%= Html.ValidationMessage("IngredientName", "*")%>
</p>
<p>Save Ingredient</p>
<%= Html.Hidden("RecipeID", recipe.RecipeID.ToString())%>
<% } %>
</div>
When this runs the IngredientsListControl.ascx displayas a new page
in the browser and does not update the ingredientlistdiv.
This is my controller action
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateStep2(FormCollection form)
{
var factory = SessionFactoryCreator.Create();
using (var session = factory.OpenSession())
{
Recipe recipe = GetRecipe(session, Convert.ToInt32(form["RecipeID"]));
Ingredient ingredient = new Ingredient();
ingredient.UpdateFromForm(form);
ingredient.Validate(ViewData);
if (ViewData.ModelState.Count == 0)
{
recipe.Ingredients.Add(ingredient);
session.Save(recipe);
return PartialView("IngredientsListControl", recipe.Ingredients);
}
return Content("Error");
}
}
Am I doing the right thing on this line?
return PartialView("IngredientsListControl", recipe.Ingredients);
Is that how I render the control into the div so it does
not load new page.???
Malcolm
When you use this:
<a href="javascript:document.forms[0].submit()">
...you should be aware that it's not the same as
<input type="submit" />
It doesn't raise the onsubmit event, and MVC's AJAX eventhandler is not called.
To confirm this is the issue, add
<input type="submit" />
inside the form and try it out.
Finally, just call onsubmit() from your link
<a href="#" onclick="document.forms[0].onsubmit()">
Might be worth ensuring that you have correctly referenced the ajaxmvc and jquery scripts in your page (master page). If these are incorrect a new page will be displayed instead of the correct output in the target div.
RenderPartial takes an action name, not the name of the user control, so replace "IngredientsListControl" with "UpdateStep2", your action name.