How to send ajax request in rails app without using remote - ruby-on-rails

This is working just fine
<%#= link_to t('.add_html'), 'javascript:void(0);', :class => "line-item", :product => product.id %>
$('document').ready(function(){
$(".line-item").click(function(){
var prod = $(this).attr('product');
$.ajax({
url:'<%#= line_items_url %>',
data: {product_id: prod},
type: 'POST',
dataType: 'script'
});
});
});
But when I use button nothing happens. Please let me know what am I missing here?
<%= button_to t('.add_html'), 'javascript:void(0);', :class => "line-item", :product => product.id %>

:remote => :true just creates an ajax request; you can do your own ajax request no problem:
$("button").on("click", function(){
$.ajax({
url: $(this).attr("href");
success: function(data) { //handle returned data },
error: function(data) { //handle errors }
});
});
I think you are asking a different question (how to get your call working), which I can update the answer to reflect if you wish

You need to prevent default:
$(document).ready(function(){
$("button").click(function(ev){
$.post(this.url); // I'm not sure this is correct
ev.preventDefault();
});
});

Related

How use rails wikedpdf gem with ajax

I'm using the wikedpdf gem on a rails project to get my reports.
But to one report I need to use an ajax request
$.ajax({
type: "POST",
url: url,
dataType: 'pdf',
data: { ids: getIdsJavascriptMethod() },
success(data) { $("#load-app").hide(); return false; },
error(data) { $("#load-app").hide(); return false; }
});
I'm calling the ajax reques wth a link_to
<%= link_to "PDF", "#", onclick: "pdf()", target: :_blank %>
But are rendering the same page "#" on a _blank target, how to render a PDF file using wikedpdf gem with an ajax request?
It's opening a new tab because that's the default behavior of clicking a link with target="_blank". Use e.preventDefault() first thing in your pdf() function to prevent this behavior.
function pdf(e) {
e.preventDefault();
// make Ajax request
}
And replace "#" with the js call on link_to:
= link_to "PDF", "javascript:pdf()", target: :_blank
Or, better yet in IMO, add an id to your link event:
<%= link_to "PDF", "#", id: "pdf-link", target: :_blank %>
And listen to the click (code assumes you have jQuery loaded):
$(document).ready(function() {
$('#pdf-link').click(function(e) {
e.preventDefault();
pdf();
});
});

send data from view to controller in rails

I want to send some data from view to controller in rails through ajax.
I have the following code in
app/view/static/home.html.erb
<script type="text/javascript">
var dummy = "testtext";
$('#finish').click(function() {
$.ajax( {
url: '/finish',
type: 'POST',
data: dummy,
dataType: 'text'
});
});
</script>
<body>
<%= button_to "Finish", {:action => 'finish', :controller => 'static'}, :method => :post, id => 'finish' %>
</body>
in
app/view/static/finish.html.erb
<p><%= #data %></p>
app/controller/static_controller.rb
def finish
#data = params[:data]
end
in routes.rb
post 'finish' => 'static#finish'
My understanding is that on button click the ajax script will be executed and rails action will store the data passed from view. This doesn't seem to work. I'm not sure if my understanding of the flow is right.
Because you are calling params[:data] in the controller, you need to specify that {data: dummy} in the AJAX data section
<script type="text/javascript">
var dummy = "testtext";
$('#finish').click(function() {
$.ajax( {
url: '/finish',
type: 'POST',
data: {data: dummy},
dataType: 'text'
});
});
</script>
Also you might want to respond to your AJAX call in your controller using the following
def finish
#data = params[:data]
respond_to do |format|
format.json { insert_your_code_here }
end
end

Rails - having a ajax button to make call

Say I have a button on my form, it doesn't submit the form, but it basically goes off to get some more information:
<%= f.button '', class:'hidden', id: 'do_calculation', remote: true %>
How do I tie this up so that when it is clicked it calls a controller action and returns the data?
Should I have something like this on the same page?
<script>
function calculate_close() {
var id = '<%= #thing.id %>';
$.ajax({
url: "<%= calculate_path %>",
data: {
id: id
},
dataType: "script"
})
}
</script>
Here you can create a html button without using form builder like.
<button id="do_calculation">Button</button>
Then you can bind the click event to that button and call the ajax inside that event, like:
$("#do_calculation").on('click', function(){
var id = '<%= #thing.id %>';
$.ajax({
url: "<%= calculate_path %>",
data: {
id: id
},
dataType: "json"
})
})
and in the controller you can use something like:
respond_to do |format|
format.json { render :json => {:message => "success"} }
end
Hope this will help!

Rails AJAX (JSON) response reloads the page

In the controller a response to an AJAX Request is following:
#response = {resp: "ack"}
render json: #response
JS which handles AJAX is:
$('#some_btn').click(function() {
var valuesToSubmit = $('#some_form').serialize();
var url = $('#some_form').attr('action');
console.log("VALUE: " + valuesToSubmit);
console.log("URL: " + search_url);
$.ajax({
type: 'POST',
url: url, //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON",
success: function(data) {
console.log("saved");
console.log(data);
}
});
return false;
});
But the problem is that I don't get console messages, instead the page reloads and I get json as text on a new page. How to prevent this "non-true-AJAX" behaviour?
So, I had almost the same problem. In my case, I was using the folliwing link to send the request:
<td>
<%= link_to add_item_path(item),
class: 'ui icon button',
id: "add-item-#{item.id}",
method: :post do %>
<%= fa_icon 'shopping-cart' %>
<% end %>
</td>
My js to send the ajax was:
$(document).ready(function() {
$("a:regex(id,add-item-[0-9]+)").click(function(event) {
event.preventDefault();
var link = $(this).attr("href");
$.ajax({
url: link,
method: "POST",
dataType: "json",
success: function(data) {
console.log(data);
$('#notice-modal').modal('show');
}
});
})
});
and my rails controller action was:
def add
#item = Item.find(params[:item_id])
current_cart << { item_id: #item.id, quantity: 1 }
render json: {quantity: 1}
end
So the problem was I using only event.preventDefault() but wasn't enought. For working fine, I need to use event.stopPropagation(). Like this:
$("a:regex(id,add-item-[0-9]+)").click(function(event) {
event.preventDefault();
event.stopPropagation();
var link = $(this).attr("href");
$.ajax({
url: link,
method: "GET",
dataType: "json",
success: function(data) {
console.log(data);
$('#notice-modal').modal('show');
}
});
})
The event.stopPropagation() is needed because rails component (rails-ujs I think) sent the request elsewhere. You can also remove the method: :post, and will work fine.
Hope I helped!
Do you need to prevent the default form submit action?
$('#some_btn').click(function(event) {
event.preventDefault();
//...
});
I had this problem myself. Turns out, I'd just forgotten to add "//= require jquery_ujs" to my application.js file. As soon as I added it, everything worked fine.

Ajax submit without :remote => true

I have a form in my application which I need to submit via Ajax (JQuery), however It needs to get submitted remotely from my JavaScript (i.e. I can not user :remote => true).
I can locate my form in my JavaScript no problems:
my_form = $("#the_id_of_the_form");
Then I create my Ajax request:
$.post('hardcoded path?', function(data) {
// how would I serialize my parameters?
});
Many thanks.
from jquery api
Example: send form data using ajax requests
$.post("test.php", $("#testform").serialize());
In your situation it can be something like that.
$('#your_form').submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "JSON"
});
});
Do not hardcode the url, instead use the url as stored in the form.
You can do this as follows:
$("#the_id_of_the_form").submit(function() {
$.post({
url: $(this).attr('action'),
data: $(this).serialize()
});
});
Hope this helps.
Use jQuery(<FORM_ID>).ajaxSubmit
Your form should be something like following
<%= form_for #user,:url=>{:controller=>:logins, :action => 'sign_up'}, :html=>{ :onSubmit => "return checkSignupValidation()",:id=>"signup_form"} do |f|%>
<% end %>
And your js
function checkSignupValidation()
{
jQuery('#signup_form').ajaxSubmit({
url:"/logins/sign_up",
iframe: true,
dataType: 'script',
success: function(data){
//console.log(data)
}
});
}
Try not to use $.post or $.get, it is not agile and cause troubles in debug and refactoring/
$.ajax({
url: 'only_hardcore_path/' + my_form.serialize(),
type: 'POST'
});
or may be:
$.ajax({
url: 'only_hardcore_path/',
type: 'POST',
data: my_form.serialize()
});

Resources