Auto ajax selectors with Jquery - css

I'm trying to make a proof of concept website, but I want perfect degradation. As such I'm going to code the website in plain XHTML first and then add classes & ids to hook them in jQuery.
One thing I want to do is eventually enable Ajax xmlhttprequest for all my links, so they display in a viewport div. I want this viewport to be a "universal" dump for any xmlhttprequest from multiple external pages.
I was wondering if I'm able to hardcode something like:
<a href="blah.html" class="ajax">, <a href="bleat.html" class="ajax">
etc. So as you can see, I give all link tags that I want to call Ajax requests from with the class ajax. In my JS based on jQuery, I want to be able to code it such that all positive ${"a").filter(".ajax") will automatically load their respective hrefs [variable] as a ajax request.
Please help. I'm a n00b.

With your example, you should be able to do:
$('.ajax').click(function () {
// Your code here. You should be able to get the href variable and
// do your ajax request based on it. Something like:
var url = $(this).attr('href');
$.ajax({
type: "GET",
url: url
});
return false; // You need to return false so the link
// doesn't actually fire.
});
I would suggest using a class different from "ajax" because it makes the code a little strange to read, because $('.ajax') could be misread as $.ajax().
The $('.ajax').click() part registers an onClick event handler for every element on the page with the class "ajax" which is exactly what you want. Then you use $(this).attr('href') to get the href of the particular link clicked and then do whatever you need!

Something like:
function callback(responseText){
//load the returned html into a dom object and get the contents of #content
var html = $('#content',responseText)[0].innerHTML;
//assign it to the #content div
$('#content').html(html);
}
$('a.ajax').click(function(){
$.get(this.href, callback);
return false;
});
You need to parse out everything that is outside of the #content div so that the navigation isn't displayed more than once. I was thinking about a regexp but probable easier to use jQuery to do it so I updated the example.

Related

FlowRouter without page reload

I am following this example https://kadira.io/academy/meteor-routing-guide/content/rendering-blaze-templates
When I click on my links the whole page is being reloaded. Is there any way to load only the template part that is needed and not the whole page?
Edit: Also I noted another problem. Everything that is outside {{> Template.dynamic}} is being rendered twice.
Here is my project sample. https://github.com/hayk94/UbMvp/tree/routing
EDIT: Putting the contents in the mainLayout template and starting the rendering from there fixed the double render problems. However the reload problems happen because of this code
Template.mainLayout.events({
"click *": function(event, template){
event.stopPropagation();
console.log('body all click log');
// console.log(c0nnIp);
var clickedOne = $(event.target).html().toString();
console.log('This click ' + clickedOne);
//getting the connID
var clientIp = null // headers.getClientIP(); // no need for this anymore
var clientConnId = Meteor.connection._lastSessionId;
console.log(clientIp);
console.log(clientConnId);
Meteor.call("updateDB", {clientIp,clientConnId,clickedOne}, function(error, result){
if(error){
console.log("error", error);
}
if(result){
}
});
}, // click *
});//events
Without this event attached to the template the routing works without any reloads, however as soon as I attach it the problem persists.
Do you have any ideas why this code causes such problems?
EDIT 2 following question Rev 3:
event.stopPropagation() on "click *" event probably prevents the router from intercepting the click on link.
Then your browser performs the default behaviour, i.e. navigates to that link, reloading the whole page.
EDIT following question Rev 2:
Not sure you can directly use your body as BlazeLayout target layout.
Notice in the first code sample of BlazeLayout Usage that they use an actual template as layout (<template name="layout1">), targeted in JS as BlazeLayout.render('layout1', {});.
In the tutorial you mention, they similarly use <template name="mainLayout">.
That layout template is then appended to your page's body and filled accordingly. You can also change the placeholder for that layout with BlazeLayout.setRoot() by the way.
But strange things may happen if you try to directly target the body? In particular, that may explain why you have content rendered twice.
Original answer:
If your page is actually reloaded, then your router might not be configured properly, as your link is not being intercepted and your browser makes you actually navigate to that page. In that case, we would need to see your actual code if you need further help.
In case your page does not actually reload, but only your whole content is changed (whereas you wanted to change just a part of it), then you should make sure you properly point your dynamic templates.
You can refer to kadira:blaze-layout package doc to see how you set up different dynamic template targets in your layout, and how you can change each of them separately (or several of them simultaneously).
You should have something similar in case you use kadira:react-layout package.

Possible to make tabs that link to discrete HTML files and that don't reload entire page?

I need menu tabs that link to separate HTML files on my server, with unique URLs. I know this by itself doesn't require anything but CSS, but I would also like to retain the "instant load" effect of Javascript-enable menus, as well as loading only the relevant section of the page. (a CSS-only menu, I think, would reload the entire page). Is this possible?
It's possible with the help of Knockout.js and/or JQuery.
You could do it all with JQuery using the Tabs plugin provided by JQuery UI. You would have to write all of your own CSS so that you don't get the default "tabbed" look but something that resemble a menu.
Or, you could use Knockout.js to create a client-side view model with a set of commands that are bound to your menu items. Each command would then trigger a page update, most likely using JQuery.
Here's a very high-level example of how this might work starting with a basic menu:
<ul>
<li data-bind="menuOption1">
...
</li>
</li>
A Knockout.js view model
var MenuViewModel = function ()
{
this.menuOption1 = function () {
// TODO: show the discreet HTML page
}
}
ko.applyBindings(new MenuViewModel());
How you actually show the page is up to you. It's probably easiest to use a JQuery AJAX call to load the page contents.
How you make/style the menu does not have any effect on how the pages linked in the menu are loaded once clicked. In order to avoid a page reload upon click, you'll need to make an ajax request to that page and load it into your current page.
I suggest using jQuery's AJAX so as to avoid cross-browser issues.
Example:
$('#menu a').click(function(ev){
$.ajax({
url: "test.html",
cache: false
}).done(function( html ) {
$("#results").append(html);
});
ev.preventDefalt();
});

Manipulate event URL <a> tags

I am passing a URL to my fullCalendar implementation via a JSON string.
fullCalendar wraps all the event data inside the tags of this URL.
I was wondering if there is a way to manipulate this as to add a call to a javascript function.
Something like:
my Link
Thanks
You could probably use the "eventRender" to add a .click() event or .bind(click)...
Something like this might work...
eventRender: function(event, element) {
$("a").click(function(){
myFunction();
});
}
Let me know if this is what you were looking for...

Submit form via AJAX with loading progress?

just need tips on how to make forms where request are submitted via AJAX with a loading progress image. I am using update panels with AJAX framework. I would like to know about the recommended approach. Through JQuery or AJAX toolkit ?
Please advice, examples would be an added bonus for me.
1- Prepare a client side div with "display:none" style property. put your loading image inside.
2 - when the user or page submits a request, change that divs display property to "block".
3- Add some kind of "information received" sign to the response and check this response from the client side and then change that divs display property back to "none"
I would like to know about the
recommended approach
Well, that depends on what you are doing, what parts of the form are you updating, how big is the form, what values are you sending to the server.
Generally speaking, if you want to update something simple (dropdownlist, listbox, etc), youd generally use JavaScript (or jQuery) to call an AJAX-enabled web service. This way, you're only sending to the server the data it needs, things like ViewState/cookies are not sent over the wire. You also have full control over the pre/post execution events (so you can add your loading images, call the WS, then clear them).
However, if you want to asynchronously update an entire form (which has a lot of controls), you're probably right in using an UpdatePanel. Things like a GridView are a good case for an UpdatePanel (as you usually need to handle editing, binding and paging all asynchronously).
The progress image is made easy with the following code:
<ProgressTemplate>
<img src="someloadingimage.gif" alt="Loading" />
</ProgressTemplate>
Stick that inside your UpdatePanel, and whenever an AJAX call is made, the loading image will be shown.
HTH
If you use JQuery for AJAX request then you can use the following events -
$.ajax({ url: "test.html",
type: "GET",
beforeSend: function(){
-----load your loader here-----
});,
success: function(){
------remove your loader here -----------
Remaining code
}});
You can also use POST. in above example i have used GET.
For detailed documentation you can refer - http://api.jquery.com/jQuery.ajax/
Create a small plug-in for your loader like so.
$.fn.ShowLoader = function(on){
switch(on)
{
case true:
$(this).show();
break;
default:
$(this).hide();
break;
}
}
then use the following:
$('form').submit(function(){
var Form = $(this);
$('.loader',Form).ShowLoader(true);
//Gather some params
Location = Form.attr('src');
Data = Form.Serialize();
$.post(Location,Data,function(result){
result = result || false;
if(result)
{
$('.loader',Form).ShowLoader(false); //Disable the loader
//Process result
}
});
})
html would just be a regular form, with an image / div inside with the class of loader

ASP.NET MVC Ajax ActionLink OnComplete callback invoked before replace is done?

I have a fairly simple ajax action link. The purpose of the action link is to fetch a partial view from the server and replace the contents of a div with new content.
The code looks something like:
<%= Ajax.ActionLink("click me", "GetThing",
new { Mode = "Simple"},
new AjaxOptions {
UpdateTargetId = "thingDiv",
OnComplete = "completeGetThing"
})%>
As you can see, the action link just replaces the content of a div tag in the page (thingDiv) with new content from the server.
I also have a javascript function being called for the OnComplete event. The callback function here needs to do some things with the content that is loaded into thingDiv.
Here is a simplified example of what I'm doing in javascript:
function completeGetThing{
if($("#thingDiv #subThing").length > -1){
doOtherThing();
}
}
I'm just using jQuery to fetch an element called "subThing" from within the div that we are updating.
But what I've discovered is that the OnComplete function appears to fire off before the HTML in thingDiv is actually replaced... so when my callback goes to look for the "subThing" element, it doesn't find it.
This is a VERY simplistic example of what I'm doing.
I am looking for good recommendation for how I might go about solving this problem, or better yet somone to point out something I've overlooked that can get the job done.
Thanks!
You can try to find out if completeGetThing is actually running (put alert there). We had a problem with that and end up with using OnSuccess event instead of OnComplete. We are using this event to colorize loaded tables and it works.
I use OnSuccess. Same as Sly and it works.

Resources