.js.erb file is not executing although rendered in rails - javascript

I use rails and haml. I send data via Ajax post to a controller in rails:
$.ajax({
type: 'POST',
url: '/preview-image-upload',
processData: false,
contentType: false,
dataType : 'json',
data: data
});
Then I execute the data and render js in the controller:
respond_to do |format|
if #previewupload.save
format.js
end
The object is saved correctly. Also the .js.erb file is correctly rendered according to the server log:
Rendered path/preview_image_upload.js.erb (0.2ms)
Completed 200 OK in 603ms (Views: 8.1ms | ActiveRecord: 8.5ms)
For testing reasons, I put an alert into the preview_image_upload.js.erb file:
alert("Hello World");
but nothing happens. It looks like the .js.erb file is rendered but not executed.
Tried the solution from here:
js.erb not executing javascript but is processed rails
{ render layout: false, content_type: 'text/javascript' }
But that did not work.

The datatype to execute a Rails javascript response from a jQuery AJAX call is script

I found the solution. I simply have to remove the dataType attribute in the Ajax request. Makes it look like this:
$.ajax({
type: 'POST',
url: '/preview-image-upload',
processData: false,
contentType: false,
data: data
});

Related

Rails: Respond with js to Ajax request

I encountered some weird behaviour when using an ajax request to get a response from a rails controller action.
$.ajax({
type: 'GET',
url: '/notifications',
success: function(result) {
eval(result);
}
});
def index
respond_to do |format|
format.html { redirect_to root_url, alert: 'Page not accessible' }
format.js
end
end
So this respond_to block works fine when using requests with rails' remote: true option, but with the ajax call it just redirects the request to root_url.
When specifying json as dataType of the Ajax request. The so returns the JavaScript just fine, but because it is not valid json, eval() does not run it.
Is there a way too either start a rails remote request from within JavaScript or specify a data type with which the returned JavaScript is executable?
Even specifying dataType: 'text/javascript', in the ajax call does not do the trick.
So this respond_to block works fine when using requests with rails'
remote: true option, but with the ajax call it just redirects the
request to root_url
So the request format that is coming to the controller is HTML not JS. Using dataType: 'script' generates the request as JS and should fix your problem.
$.ajax({
type: 'GET',
dataType: 'script',
url: '/notifications'
});

Rails | add ajax loading icon to remote: true

I have a link with remote: true attribute. It goes to the function then the js.erb file. My question is how can I add loading icon rails way?
For instance, if I put ajax request it is easy;
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
dataType: 'json',
beforeSend: function() {//add icon here}
success: function(data){
},
error: function() {
}
});
But when I work with remote: true with link or button where should I put the loading icon.
PS: I do not want to add smth like below to the dom.
$('#mybutton').on('click', function(){$('#div-to-loading').prepend('.loading-icon')})
EDIT
Please read my question carefully. I know how to add loading icon with ajax call. I am asking how to do it with rails way. I have a link with remore:true option. It goes to controller action then rendering js file myfunc.js.erb.
Where should I put loading icon?

Rails render partial as widget over ajax using jsonp

I've looked at quite a few other answers on here, but I'm still struggling a bit to figure out how to set up my Rails widget.
I have this code in my widget controller:
def widget
status = Company.friendly.find(params[:id]).widget.active
body = to_json_value(render_to_string('companies/_widget', locals: { profile: self.profile }))
respond_to do |format|
format.js { render json: { status: status, html: body }, callback: params[:callback] }
end
end
private
def to_json_value(str)
str.gsub!("\"", "\\\"")
str.gsub!(/\n+/, " ")
str
end
The self.profile method just sets up a list of variables that get passed to the partial.
What I want to do is give a user a Javascript script tag that they can embed on their (external) website. When a user hits that page, the script will make an AJAX call to the widget controller and if the widget is turned on, it will receive a string of html to be rendered on the page.
So far I've got the widget controller to return a json object with the status and the html string. The problem is when I paste the localhost url into jsonlint.com, it says it is invalid. This is also confirmed when I insert a script tag into an html file and then open it in Chrome. I get an error saying there was an unexpected token :. So I then changed my controller and widget.js.erb to include a callback function. I added , callback: params[:callback] to my controller.
I also set up a callback function (doesn't do anything yet) in my widget.js.erb file. I then embed this file using a script tag in an html file and load that in Chrome. When I do, I get an error saying that showWidget is undefined.
I'm struggling to find resources that explain how to load data over jsonp from a rails app, and how callback functions come into play.
Here is my widget.js.erb:
function showWidget();
$.ajax({
type: 'GET',
url: 'http://localhost:3000/<%= params[:company] %>/widget?callback=?',
jsonpCallback: 'showWidget',
contentType: "application/json",
crossDomain: true,
dataType: 'JSONP',
success: function (data) {
var result = JSON.parse(data);
$('#company-widget').html(result.html);
},
error: function(e) {
console.log(e.message);
}
});
Here is my test.html:
<div id="company-widget"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="http://localhost:3000/taco-corp/widget.js?callback=showWidget" type="text/javascript"></script>
I'm also not sure where this widget.js.erb script should live in my rails app. Here is what I have so far for my widget.js.erb:
I figured out what the problem was. I needed to add a callback to my rails controller and to my $.ajax method. I didn't have the callback set up correctly in my ajax call. I also needed to specify the correct header (contentType) to get around an HTTP 406 error. Here is the working jQuery code below for reference:
$(document).ready(function(){
var company = 'taco-corp';
$.ajax({
type: 'GET',
url: 'http://localhost:3000/' + company + '/widget.js?callback=?',
contentType: "application/javascript",
crossDomain: true,
dataType: 'JSONP',
success: function(data) {
$('#company-widget').html(data.html);
},
error: function(e) {
console.log(e.message);
}
});
});
And here is my rails controller:
def widget
status = Company.friendly.find(params[:id]).widget.active
body = render_to_string('companies/_widget', layout: false, locals: { profile: self.profile })
respond_to do |format|
format.js { render json: { status: status, html: body }, callback: params[:callback] }
end
end

Ajax request inside ajax request with Laravel

I have a code that works like this:
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
contentType: false,
dataType: 'html',
This loads:
Route::post('/local/pdf', 'LocalController#subirPDF');
Which loads the controller:
return View::make(Config::get('rv.paginasPDF'));
Which loads:
$.get("{{Request::root()}}/local/actualizar_paginas/9/2");
Which loads the route:
Route::get('/local/actualizar_paginas/{id}/{paginas}', 'LocalController#actualizarPaginas')->where('id', '[0-9]+')->where('paginas', '[0-9]+');
That loads:
Auth::user()->perfil='penadaaaaaafe';
Auth::user()->save();
Don't worry if you see that I don't use some variables, because I have simplified the code to make it easier to explain.
Basically, if I load directly the route from the url everything works fine:
{{Request::root()}}/local/actualizar_paginas/9/2"
But if I load it with the ajax method that I have devoloped it doesn't work. If I console.log the data I recieve the right html code of the $.get page, but It doesn't make the get request.
Any idea how to fix it?
Thanks.

Grails GSP Ajax Call OnSuccess not called

I am performing an ajax call from a .gsp file in grails:
$.ajax({
async: false,
url: '<g:createLink controller="mycontroller" action="myaction"/>',
data: params,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
onSuccess: 'toggleSaveButton(false);'
});
mycontroller
def myaction() {
// do some funky stuff with params
// params are available, everything here works without a problem
}
outcome
the ajax call is performed and the controller function is called correctly with all attached data.
issue
my onSuccess: is ignored and never called
i already tried
using the more generic onComplete
change the onSuccess: to function(){toggleSaveButton(false);}
render (true as JSON) in my controller action
I believe it should be success: instead of onSuccess:, according to JQuery ajax docs.
To demonstrate:
http://jsfiddle.net/bL60Lta9/2/
Rewriting to :
onComplete: dataUpdatedOnSuccess()
did the trick.

Categories

Resources