Jquery applying class and removing class - javascript

The code which changes the active class to the currently clicked pagination class. Removing it works but adding the new class doesn't work.
http://jsfiddle.net/spadez/qKyNL/35/
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
$('#pagination li.active').removeClass("active");
$(this).parent().addClass("active");
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
$('#content').fadeTo(500, 1);
}
});
});
Can anyone please tell me where I am going wrong?

The problem is that this in the success callback isn't your element.
You may do this :
$('a').click(function(event){
var element = this; // <= save the clicked element in a variable
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
...
success: function (data, textStatus) {
...
$('#pagination li.active').removeClass("active");
$(element).parent().addClass("active"); // <= use it
},
...
});
});

This this in ajax callback isn't what you expect it to be. Add this to your ajax parameters:
context: this,
No need to build custom object saving system and making code more messy, as jQuery already has this functionality.
Edit: In this case it should look like:
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
context: this,
url: "/ajax_json_echo/",
...

Related

jQuery event binding with dynamically loaded elements when scroll down at the end of window

<script type="text/javascript">
$(document).ready(function() {
var page = 0;
$(window).scroll(function () {
if ($(document).height()-$(document).height()*0.2 <= $(window).scrollTop() + $(window).height()) {
$.ajax({
type: "POST",
url: "/",
dataType: "json",
data: { 'page' : page, 'csrfmiddlewaretoken': '{{csrf_token}}'},
success: function(data) {
obj1 = JSON.parse(data.fulldata);
var newHTML = '<a href = "" >somecode</a>';
$(".newdata").append(newHTML);
},
error: function(data) {
// alert("error")
}
});
}
}
});
</script>
i have readed this link for dynamically added elements, that we must bind the function to one of it's parents
...but no success
i am not pasting the entire code here. suppose code is correct and working fine. only when i am clicking the loaded element its not working..
Thanks in advance
full code

why this code is not loading pages ajax jquery

Guys What I am trying to do is load a page on navigation click with ajax and put some delay in it loading
when nothing is clicked I want load home page following loading animation with jquery and a delay with PHP code
and if something on nav is clicked I want to load that particular file
but this code don't seem to be working
var res = {
loader: $('<div />', {class: 'loader' } ),
container: $('.content')
};
$(document).ready(function(){
$.ajax({
url: 'templates/delay.php',
beforeSend, function(){
res.container.append(res.loader);
},
success, function(){
res.container.find(res.loader).remove();
$('.content').load('templates/pages/home.php');
}
});
$('ul#nav_a li a').click(function(){
$.ajax({
url: 'templates/delay.php',
beforeSend, function(){
res.container.append(res.loader);
},
success, function(){
res.container.find(res.loader).remove();
var page=$(this).attr('href');
$('.content').load('templates/pages/'+page+'.php');
return false;
});
});
}
});
I will not discuss the code itself, but just improve it.
Try this code and tell me if you get what you want : ( comments inside the js code )
$(document).ready(function(){
$.ajax({
url: 'templates/delay.php',
// old code : beforeSend,
beforeSend: function(){
res.container.append(res.loader);
},
// old code : success,
success: function(){
res.container.find(res.loader).remove();
$('.content').load('templates/pages/home.php');
}
// beforeSend and success are keys with functions as values that's why we use ":" and not ","
// the "," comma is used to separate ajax settings
});
$('ul#nav_a li a').click(function(){
var page = $(this).attr('href');
$.ajax({
url: 'templates/delay.php',
// old code : beforeSend,
beforeSend: function(){
res.container.append(res.loader);
},
// old code : success,
success: function(){
res.container.find(res.loader).remove();
$('.content').load('templates/pages/'+page+'.php');
// old code
// return false;
// });
// we close our ajax.success function
}
})
// old code
// }
// return false is used to prevent browser to run the a href that's why we use it in the a.click function and not inside the ajax block
return false;
})
})
var res = {
loader: $('<div />', {class: 'loader' } ),
container: $('.content')
};
$(document).ready(function(){
res.container.append(res.loader);
$('.content').load( "templates/pages/home.php", function() {
res.container.find(res.loader).remove();
});
$('ul#nav_a li a').click(function(){
var page=$(this).attr('href');
$('.content').load( 'templates/pages/'+page+'.php', function() {
res.container.find(res.loader).remove();
});
});
}
});
Just copy and paste it.

Reset Bootstrap loading state button when AJAX call is completed

I have a simple AJAX request and I'm wondering if it's possible to combine the loading state button with my request. Is it possible to make the button reset to default when the request is completed, instead of choosing for example 5 seconds before reset as per now?
Loading state button
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
AJAX request
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType:'html',
url: '/m/core/_processEditEntry.php',
data: $('form').serialize(),
success: function () {
$(".message").fadeIn(0);
$(".message").delay(5000).fadeOut('slow');
}
});
});
});
It's best to keep your code in the same place. Remove the click handler and add these lines to the ajax call:
$(function () {
$('form').on('submit', function (e) {
//save button so we can use later
var my_button = $(this).find("button");
//give button loading state
my_button.button('loading');
e.preventDefault();
$.ajax({
type: 'POST',
dataType:'html',
url: '/m/core/_processEditEntry.php',
data: $('form').serialize(),
success: function () {
//reset state
my_button.button('reset');
$(".message").fadeIn(0);
$(".message").delay(5000).fadeOut('slow');
}
});
});
});
You can add a span with a class to the button when it was clicked
if ($(this).is(".btn, .page-link, .df-link")) {
// disable button
$(".btn").prop("disabled", true);
// add spinner to button
$(this).html(
`<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ` + $(this).text()
);
}
and then in Ajax complete remove that element:
complete: function(response) {
$(".btn").prop("disabled", false);
$(".spinner-border").remove();
}

E prevent default not working

This is the code I am working with: http://jsfiddle.net/qKyNL/12/
$('a').click(function(){
event.preventDefault();
var number = $(this).attr('href');
alert(number);
// AJAX
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
// Fadeout the existing content
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
// Scroll to top
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
// Fade in content
$('#content').fadeTo(500, 1);
}
});
});
I am trying to create a degradable pagination, using Jquery but the problem is that the "e prevent default" doesn't seem to trigger and instead it still follows the link. Could anyone please show me how I can have this link degradable so if Jquery is disabled it still works.
You're not passing in the event object. Try this:
$('a').click(function(event){ // <-- notice 'event' passed to handler
event.preventDefault();
Should be
$('a').click(function(event){
on first line. Note that event is passed as an argument to anonymous function.
No event passing in callback.
Try
$('a').click(function(event){
------------------------------^
event.preventDefault();
}
As the other answers have said you need to pass the event variable to the callback
$('a').click(function(event) {
event.preventDefault();
});
You also need to wrap all of your code in to the ready function jQuery so that the event listeners are assigned only when jQuery is ready to handle them.
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
// the rest of your code
});
});

Why is my jQuery having an error when I put this line in?

Why is my jQuery having an error when I put this line in?
<script type="text/javascript">
$(function(){
$(".arrowbutton").click(function(){
id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
$(this).hide();
}
});
return false;
});
});
</script>
When I remove $(this).hide(); it's fine. But, I want it to hide!!!
Because this doesn't refer to you arrow button, but it refers to the AJAX Request object.
$(".arrowbutton").click(function(){
var that = this;
var id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
$(that).hide();
}
});
return false;
});
jQuery calls your success function more or less like this:
handleSuccess: function( s, xhr, status, data ) {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( s.context, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
}
},
The first argument of the call method sets the this keyword in the success function to s.context
Because $(this) doesn't return what you think it does in the success callback. You could use a closure:
$(function(){
$('.arrowbutton').click(function(){
var button = $(this);
$.ajax({
type: 'POST',
url: '/upvote',
data: { id: this.rel },
beforeSend:function() {
},
success:function(html) {
button.hide();
}
});
return false;
});
});
$(this) is referring to the Ajax request, not the surrounding button.
Try using a closure like so:
<script type="text/javascript">
$(function(){
$(".arrowbutton").click(function(){
var arrowbutton = $(this);
id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
arrowbutton.hide();
}
});
return false;
});
});
</script>
"this" does mean this in all situations, because you are inside a new function that is the new this.
Check this tutorial out to learn all the different ways you can deal with it:
http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/

Categories

Resources