Here is my blog_post_inner.js :\
$(document).ready(function () {
// when the load more link is clicked
$('a.load-more').click(function (e) {
// prevent the default click action
e.preventDefault();
// hide load more link
$('.load-more').hide();
// show loading gif
$('.loading-gif').show();
// get the last id and save it in a variable 'last-id'
var last_id = $('.record').last().attr('data-id');
// make an ajax call passing along our last user id
$.ajax({
// make a get request to the server
type: "GET",
// get the url from the href attribute of our link
url: $(this).attr('href'),
// send the last id to our rails app
data: {
id: last_id
},
// the response will be a script
dataType: "script",
// upon success
success: function () {
// hide the loading gif
$('.loading-gif').hide();
// show our load more link
$('.load-more').show();
}
});
});
});
Inside blog_post_inner my main ajax is defined.
I am calling it here inside blog_post_inner.html.erb:
<div class="load-more-container">
<!-- hide our loading gif image so that we show it when making ajax call via jquery -->
<%= image_tag "ajax-loader.gif", style: "display:none;", class: "loading-gif" %>
<%= link_to_next_page articles,"Load More" ,class: "load-more" %>
</div>
But the main problem is my ajax is not loading the page in the same webpage istead its reloading/refreshing/redirecting to second page.
What to do?
I have tried changing link_to_next_page to link_to but it's giving an error:
undefined method `to_model' for #
Did you mean? to_xml
Please help my ajax is not working i have tried so many different methods but none of them prove to be useful.
I followed this article to implement this:
http://josephndungu.com/tutorials/rails-load-more-results-using-jquery-ajax
Related
I'm using JQuery tabs. Every tab loads a different file.
In one of the tabs, there's a form that is ajax - submitted. After the form is successfully submitted, a message appears in that tab: "successful!!" and I have a link for reloading the original form, in case you want to make another form submission.
I need to re-load that tab, not just "relocate", because on the load method some things are initialized, like a JS date-picker.
This is how the tabs are created:
<div id="tabs" style="border:0px;">
<ul>
<li>title 1</li>
<li>title 2</li>
<li>title 3</li>
</ul>
</div>
This is the code for the tabs loading. If "theCalendar()" function is not invoked, then the date-picker that uses this form is not available, so it has to be there:
$('#tabs').tabs({
cache: true,
load: function(event, ui) {
var active = $('#tabs').tabs( "option", "active" );
if (active == 2){
$('#amstart').addClass('selectedRadio');
$( "input[type=submit]" ).button();
theCalendar();
}
}
});
The form I'm talking about is in the 3rd tab (createMeeting.jsp) and then the submit code is:
$('#ui-tabs-3').on('click', '#submitBtn', function(event) {
event.preventDefault();
... //many validations...
myData = $("#formMeeting").serialize();
$.ajax({
url: './meeting_details.jsp',
type: 'POST',
data: myData,
success: function(data){
$('#ui-tabs-3').html(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
So far, everything works fine, the form is submitted and the resulting html is shown on that very same tab.
Finally, in that resulting html there's a link for loading the form again in case you want to add another record:
<a id="createAnotherMeeting" class="vacanteItem" href="createMeeting.jsp">Add another one</a>
And is handled like this from the main file:
$("#ui-tabs-3").on("click", "#createAnotherMeeting", function(e){
e.preventDefault();
$("#tabs").tabs("load",2); // option 1
$("#tabs").tabs("load",$(this).attr('href')); // option 2
$(this).parent().tabs("load",2); // option 3
});
There's an "option 1,2 and 3" comments because I've tried all of those (one at the time), however I keep getting this error:
Uncaught Error: Method load does not exist on jQuery.tabs
at Function.error (jquery-3.2.1.min.js?_=1675464032676:2:1979)
at jQuery.fn.<computed> [as tabs] (materialize.min.js?_=1675464032678:6:13237)
at HTMLAnchorElement.<anonymous> (videoConferencias.jsp:242:20)
at HTMLDivElement.dispatch (jquery-1.8.3.js:3058:9)
at HTMLDivElement.eventHandle (jquery-1.8.3.js:2676:28)
...
...
I was able to change the location of the tab so the createMeeting.jsp file is shown, however, that didn't solve my problem since the date-picker function wasn't loaded, and the submit button wasn't recognized by JQuery (these things are done when the tab is loaded)
All I need is to reload that tab when the link is clicked.
Any help will be really appreciated.
it turns out that I had a reference to another version of jQuery and materialize at the bottom of 'hidden' in another page (createMeeting.jsp):
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
I deleted them and the error disappeared ;)
In order to re-load the tab using that link, I did another ajax submit, so I could invoke the date-picker and the other stuff:
$("#ui-tabs-3").on("click", "#createAnotherMeeting", function(e){
e.preventDefault();
$.ajax({
url: './crearMeeting.jsp',
type: 'POST',
data: '',
success: function(data){
$('#ui-tabs-3').html(data);
$('#amstart').addClass('selectedRadio');
$( "input[type=submit]" ).button();
theCalendar();
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
Maybe it's not the cleanest solution, but it works.
I'm working on a webapp using Ruby on Rails as framework. For all the partial renders, we used link_to with remote true as explained in this answer. However, I would like to bind the all those links to something equivalent to ajax:beforeSend and ajax:complete in order to implement a loader anytime a page is called in jQuery. So far I tried the following but it is not working :
$('a').on('ajax:beforeSend', function() {
alert("BEFORE");
});
$('a').bind('ajax:complete', function() {
alert("AFTER");
});
So if you have any other ideas it would be really appreciated if you could let me know. Thanks in advance.
EDIT: Here's an example of how I have been using link_to :
<%= link_to({action: "show_card", controller: "pages", id: activ.id, method: :get, :remote => true}, class: "nav-link p-0") %>
What is not working ajax or loader if your ajax is working then for loader it should be like this
<div id="mySpinner" style="displany:none;">
<img src="loader.gif">
</div>
$(function () {
$(document).ajaxStart(function() {
//$("#mySpinner").show();
alert("BEFORE");
}).ajaxStop(function() {
//$("#mySpinner").hide();
alert("AFTER");
});
});
How about to show loader on element onclick event and hide it on ajax:success?
$('a').on('click', function() {
alert("BEFORE");
});
$('a').ob('ajax:success', function() {
alert("AFTER");
});
Make sure to also cover ajax:error
You might also try to subscribe to ajax:send instead of ajax:beforeSend. Because ajax:beforeSend is a local event and can be subscribed to only within the Ajax request object as docs say
I found out what it was, when I render new staff partially, I need to rebind it to the event, and apparently even using
$( window ).load(function() {
$('a').on('ajax:beforeSend', function() {
alert("BEFORE");
});
$('a').bind('ajax:complete', function() {
alert("AFTER");
});
});
In the application.js file did not work, so basically to bind it initially I had to put a script tag at the bottom of my page which binds everything once it already rendered everything. Furthermore, anytime I do any remote partial rendering, I also need to rebind everything in the .js.erb file, that way it actually works. I'm there has to be a better way because this seems an awful solution; it is however, a solution for now.
I've implemented a tumblr post button following their docs, and the popup works great. However, I need to pass in an image URL that is dynamically created on the page, rather than hardcoding in an image url. I'm trying to do this with jQuery.
HOWEVER, the inline script required to launch the 'post' popup fires, and prevents my jQuery (being triggered by clicking the 'post' button) from firing. I tried moving the inline tumblr script to my js, which allowed my jQuery to fire, but not the tumblr popup.
Ideally, the inline script would fire AFTER my jQuery, since the jQuery is the bit that generates the image URL I need to pass in.
Is there a way to do this, maybe with onLoad or something?
My button, as generated by Tumblr is this (sorry I can't get it on multiple lines for some reason):
<a class='tumblr-share-button' data-color='blue' data-notes='right' data-posttype='photo' data-content='image URL will go here' href='https://embed.tumblr.com/share'></a> <script>!function(d,s,id){var js,ajs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src='https://assets.tumblr.com/share-button.js';ajs.parentNode.insertBefore(js,ajs);}}(document, 'script', 'tumblr-js');</script>
And my jQuery (that is not executing) is:
$('.tumblr-share-button').click(function(e){
var svg = $("#svg")[0];
svg.toDataURL("image/png", {
callback: function(img) {
var img = img.replace("data:image/png;base64,", "");
var imgurTitle = $("meta[property='og:title']").attr("content");
$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {'Authorization': 'Client-ID ******'},
type: 'POST',
data: {'image': img, 'type': 'base64', 'title': imgurTitle},
success: function(result) {
imageURL = result.data.link;
$('.tumblr-share-button').data('data-content',imageURL);
},
error: function(){
console.log('error');
}
});
}
});
});
Any help would be tremendously appreciated!!!
I can't find a solution for this plugin since I cannot find any working demo or documentation for external content via Ajax.
Basically I have a simple div with a mouse hover JS function:
<div onmouseover="myFunct(this,'.$comment['id'].');" >Hover Me</div>
And this is my JS function:
function myFunct(element, id){
$(element).tooltipster({
contentCloning: true,
interactive:true,
maxWidth:250,
contentAsHTML:true,
content: 'Loading...',
// 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section.
functionBefore: function(instance, helper) {
var $origin = $(helper.origin);
// we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens
if ($origin.data('loaded') !== true) {
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+id+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
// to remember that the data has been loaded
$origin.html('loaded', true);
}
});
}
}
});
}
Why the tooltip is shown only at the 2nd mouse hover?
Here is a similar Eg. JSFiddle
UPDATE
Thanks to the support this has solved my issue:
<div class="tooltip" data-id="'.$comment['id'].'">Hover me!</div>
<script type="text/javascript">
$(document).ready(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250
});
});
</script>
Anyway this doesn't work on Ajax dynamic content, and I don't know why (I tried to insert it on Ajax page, no way)
I'd recommend a few things: first, separate your JS from your HTML (this is considered best practice), second, initialize Tooltipster on page load, and last, remove the wrapper function. Once the tooltip is initialized your code will trigger by default on hover.
Separate JS from HTML
<div class="hover-me tool-tip" data-commentId="12345">Hover Me</div>
Initalize Tooltipster on Document Ready
$(document).ready(function() {
$('.tooltip').tooltipster();
});
Trigger Tooltipster with Hover
$('.hover-me').tooltipster({
// all of your code from above
functionBefore: function(){
var commentId = $(this).attr('data-commentId');
}
});
Note:
The default trigger for Tooltipster is hover (as seen in the documentation), however, you could explicitly set it by passing in trigger: hover, which would make your code slightly more readable and as such maintainable.
Tooltipster Support Recommendation (as seen in the comments)
I add this because it reinforces my solution above and adds context for future devs...that, and it might be overlooked in the comments section.
You initialize your tooltip when the mouseover event has already been fired, so Tooltipster cannot "hear" this first event and open the tooltip. You'd better initialize your tooltips at page load and put your comment id in a data-id attribute that you'll retrieve in functionBefore when you prepare your ajax call.
In my view I have a link_to for downloading an excel file:
<%= link_to 'Download Excel', url_for( :controller => "my_controller", :action => "file", :format => 'xlsx', :params => params ) %>
The controller uses axlsx to render the file like:
format.xlsx {
render xlsx: 'file', filename: 'filename', disposition: 'inline'
}
Now it can take a bit of time to generate and return that file, so I'd like to give the user an indication that the site's working.
I have a hidden div in the view code:
<div id="loader"><img src="/assets/loading.gif" ></div>
When someone clicks on the link, I can show the div with this jQuery:
$('#excel_export').click(function() {
$("#loader").show();
});
My question is: how can I .hide() that div when the file download starts? Maybe an ajax callback of some sort?
I don't know if this may help you. I found this code helpful to show spinner while an ajax request is performed.
$(document)
.ajaxStart(function() {
$("#loader").show();
})
.ajaxStop(function() {
$('#loader').hide();
});
You can get more samples from the following link.
You can use setTimeout() function by checking general time taken for download to start
Like this
$('#excel_export').click(function() {
$("#loader").show();
setTimeout($("#loader").hide();, 1000);
});
So it will be automatically close after 1000ms