Strange jquery post problem, wrong post url is used - ruby-on-rails

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?

Related

jquery mobile 1.4 not updating content on page transition

From the index page, a user clicks a navigation link, the data attribute is passed via ajax, the data is retrieved from the server but the content is not being updated on the new page.
Been stuck for hours, really appreciate any help!
js
$('a.navLink').on('click', function() {
var cat = $(this).data("cat");
console.log(cat);
$.ajax({
url: 'scripts/categoryGet.php',
type: 'POST',
dataType: "json",
data: {'cat': cat},
success: function(data) {
var title = data[0][0],
description = data[0][1];
console.log(title);
$('#categoryTitle').html(title);
$('#categoryTitle').trigger("refresh");
$('#categoryDescription').html(description);
$('#categoryDescription').trigger("refresh");
}
});
});
Im getting the correct responses back on both console logs, so I know the works, but neither divs categoryTitle or categoryDescription are being updated. I've tried .trigger('refresh'), .trigger('updatelayout') but no luck!
This was not intended to be an answer (but I can't comment yet.. (weird SO rules)
You should specify in the question description that the above code IS working, that your problem occurs WHEN your playing back and forth on that page/code aka, using the JQM ajax navigation.
From what I understood in the above comment, you're probably "stacking" the ajax function every time you return to the page, thus getting weird results, if nothing at all.
Is your example code wrapped into something ? If not, (assuming you use JQM v1.4) you should consider wrapping it into $( 'body' ).on( 'pagecontainercreate', function( event, ui ) {... which I'm trying to figure out myself how to best play with..
Simple solution to prevent stacking the ajax definition would be to create/use a control var, here is a way to do so:
var navLinkCatchClick = {
loaded: false,
launchAjax: function(){
if ( !this.loaded ){
this.ajaxCall();
}
},
ajaxCall: function(){
// paste you example code here..
this.loaded = true;
}
}
navLinkCatchClick.launchAjax();

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.

Rails 4: How to upload files with AJAX

I want to upload files with AJAX. In the past I accomplished this by using the magical jQuery form plugin and it worked great. Currently I'm building a Rails app and trying to do things "The Rails Way" so I'm using the Form Helper and the paperclip gem to add file attachments.
The rails docs warn that the Form Helper does not work for AJAX file uploads:
Unlike other forms making an asynchronous file upload form is not as
simple as providing form_for with remote: true. With an Ajax form the
serialization is done by JavaScript running inside the browser and
since JavaScript cannot read files from your hard drive the file
cannot be uploaded. The most common workaround is to use an invisible
iframe that serves as the target for the form submission.
It seems clear there's no off-the-shelf solution. So I'm wondering what's the smartest thing to do. Seems like I have several options:
Use the form helper and the iframe trick.
Use the form helper + load jQuery form plugin to submit the file (not sure if this will play nice with Rails's authenticity token, etc)
Use the form helper + paperclip + [some other gem] to extend it's functionality to allow AJAX form submission.
All three seem possible. I know the least about #3, specifically the [some other gem] part. I found two similar questions (this and this) which mention a branch of Pic-Upload called Uploadify but those are both 2 years old and deal with Rails 2 and 3 (and Uploadify hasn't been updated in years). So given how much has changed, I think this is really a whole new question:
What's the best way to upload files with AJAX in Rails 4?
Have a look into the remotipart gem: https://github.com/JangoSteve/remotipart -- may get you all of the way there with very little work!
Using #rails/ujs.
view (.html.erb):
<%= file_field_tag :file, { id: "ajax_file_upload"} %>
controller(_controller.rb):
def update
#record = YourModel.find(params[:id])
respond_to do |format|
if #record.update_attributes(params[:your_model])
format.json { render json: { success: true } }
else
error_messages = #record.errors.messages.values.flatten
format.json { render json: { success: false, errors: error_messages } }
end
end
end
javascript(.js)
const uploadFile = element => {
const formData = new FormData();
formData.append("your_model[attribute_name]", element.target.files[0]);
Rails.ajax({
url: "your_model/:id",
type: "PUT",
beforeSend(xhr, options) {
options.data = formData;
return true;
},
success: response => {
if (response.success) {
alert("File uploaded successfully");
}
else {
alert(response.errors.join("<br>"));
}
},
error: () => {
alert("ajax send error");
}
});
};
const documentOnReady = () => {
const fileField = document.getElementById("ajax_file_upload");
if (fileField) {
fileField.addEventListener("change", uploadFile);
}
}
document.addEventListener("turbolinks:load", documentOnReady);
Note: No need to setRequestHeader in ajax while using FormData.
FormData uses the same format a form would use if the encoding type were set to "multipart/form-data"
IMHO Rails is not perfect when dealing with upload files using AJAX, especially if you want a progress bar. My suggestion is to use Javascript for the form submission over an AJAX request like you suggested in (2). If you are comfortable with Javascript you will not have many problems.
I recently used the same approach by using this very simple JS library https://github.com/hayageek/jquery-upload-file and I wrote more details here http://www.alfredo.motta.name/upload-video-files-with-rails-paperclip-and-jquery-upload-file/
For an application with a form to upload a movie with title and description the JS code looks like follow:
$(document).ready(function() {
var uploadObj = $("#movie_video").uploadFile({
url: "/movies",
multiple: false,
fileName: "movie[video]",
autoSubmit: false,
formData: {
"movie[title]": $('#movie_title').text(),
"movie[description]": $('#movie_description').text()
},
onSuccess:function(files,data,xhr)
{
window.location.href = data.to;
}
});
$("#fileUpload").click(function(e) {
e.preventDefault();
$.rails.disableFormElements($($.rails.formSubmitSelector));
uploadObj.startUpload();
});
});
Far from perfect, but gives you flexibility on your frontend.

ajax request in rails 2 not working

function ajaxRequest(){
$.ajax({
type: 'GET',
url: 'client/orders/send_mail_to_notaries',
data: { subject: "hi" }
});
return false;
}
It doesn't pass any params in controller.Can any one trigger this out?
Following the question that you have asked today morning page.replace_html method in rails 2 i guess you are using prototype.
Can you check if jQuery is included? Unless jQuery is included this ajax request will not work.
I just tried the method you're using and it worked for me. Perhaps there's a problem with the router/controller?
When debugging ajax it's very handy to use the Chrome developer toolbar. Bring it up, run the javascript and see what happens.
To see the response from the server you can then flip to the Network tab to see what the response is.

Jquery AJAX from remote host

Hi I am trying to get json from a remote host using this piece of code Example at fiddle,
Here i want to add that i am using jquery cross domain ajax plugin
$("button").click(function() {
jQuery.ajax({
url: "http://50.116.19.49/rest/user.json",
type: 'GET',
success: function(result) {
$("div").html(result.responseText);
}
});
});​
I am using jquery AJAX GET method. The problem is when i try to use POST instead of GET it stops working, Need help.!
Thanks
It's possible to limit request by method on server side.
So that doesn't mean If it works with GET than that also must work with POST. As I see your web service doesn't allow origin access for POST method.
Here is an example how it's allowed for different type of request in PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET")
header("Access-Control-Allow-Origin: *");
echo "lan";
else {
echo "disabled";
}
?>

Resources