Rails | add ajax loading icon to remote: true - javascript

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?

Related

AJAX multiple responses

I'm diving into JavaScript and AJAX technologies now, and I understand AJAX and POST well with it. Now I wonder whether there's something like a broadcasting channel that my PHP code (in this case, Laravel controller) broadcast to, which then is received by JavaScript on the client side in order to manipulate something, say a process like this:
User clicks a button, a spinner is shown inside the button. Next to the button, there's a status label indicating the current process/task being processed. Finally, the button becomes a link or something else. So, what I want now is that I can update the status multiple times, since my current AJAX code will only receive one message, or one status, at the end of the process and that's it, nothing in between:
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
success: function(result)
{
console.log(result.status);
}
});
Now I wonder how this further works.
You can make use of beforeSend event of ajax and use to start a progress bar and when it completes you can make progress bar width to 100%
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
beforeSend : {
// start progress bar
},
success: function(result)
{
console.log(result.status);
// complete progress bar
}
});
Additionally, you could use css to apply transition to give the feeling the of progress in progress bar.
Use the concept of javascript callback or promise. You can creatw a script where when the button is clicked , a onclick function will run and change the content inside of tge button and when changed do the ajax call and if success call the promise again

Open file upload dialog after Ajax post success

I have functionality in which it is required to open file upload dialog after Ajax call success event.
What I tried:
I tried applying below simple code in ajax success: and complete: event but it is not working.
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: { id: eoid },
contentType: 'application/json; charset=utf-8',
success: function (data) {
// some logic
$("#fileupload").click();
}
});
What is problem:
If I put simple button and try to execute above code, it is working fine and opening dialog - but it is not working in case of ajax post afterwards.
Any guesses or am I missing something?
Thank you.
The problem is at dataType: 'json' . You are loading html with your ajax request so you should change it to dataType: 'html' else in any other format it will not be considered success. Or you can delete this property as stated in Jquery doc that Jquery does default: Intelligent Guess (xml, json, script, or html).

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

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
});

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.

how to transfer the control during success: of jquery to html form

I'm using following jquery statements to validate the user details.
$.ajax({
type: "POST",
url: "Login",
data:'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass),
dataType: "json",
//if received a response from the server
success: function( data, textStatus, jqXHR) {
if(data==true)
{
$("#error").show(1500).css({visibility: "visible"});
$("#error").append("<b>success!</b>");
}
but i nee to transfer the control to other html page during success.
$("#error").show(1500).css({visibility: "visible"});
$("#error").append("<b>success!</b>");
I'm trying to change the above statements to transfer the control. Please anyone help me to solve this.
within your successful login condition use:
window.location ='index1.html';
/* or whatever url you want and make sure path is correct relative to page or use absolute url */
This tells browser to open that url using javascript

Categories

Resources