Activate jquery Ajax on click on list and pull number - javascript

This is my code that I have built from several different pieces of information online:
http://jsfiddle.net/spadez/qKyNL/6/
$.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);
},
});
My question is, how do I trigger the ajax request from clicking on one of the pagination list links (like 1 or 2) whilst using e.prevent default so it is degradable (it will still work if JavaScript is disabled). I guess what I am trying to do is the following in pseudo code:
Listen for a click of the pagination link
Grab the number of the link clicked (ie was 1 or 2 clicked)

try
$('a').click(function(){
var number = $(this).attr('href');//get the pg=1 value on the href
alert(number);
//ajax here
});

I'm not sure I completely understand your question, however something like this should work:
$(function() {
var clicks = {};
var sendAjax = function(href) {
//do something with href
$.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);
},
});
};
$('a').click(function() {
var href = $(this).attr('href');
clicks[href] = clicks[href] ? clicks[href] + 1 : 1;
sendAjax(href);
return false; //disable the link
});
});

can't you just set an onclick on those link 1 and link 2?
ex:
link1.click(function() {
// do stuff with the ajax
});

Related

Scroll up when you click on the pagination page

Can you please tell us how to make a scroll up when you click on the pagination page? There is a page of posts https://tvoidv.ru/culture/.
When you click on "Show more" (in itself) the page remains in place, but you need it to hide up or somehow it seems that the update has occurred. How can this be done?
Post loading code from json
$(document).on('click', '#more-news', function(e) {
e.preventDefault();
var _url = $(this).attr('data-url');
send = false; //убираем шумы
if (_url && !send) {
$.ajax({
url: _url,
type: 'GET',
dataType: 'json',
beforeSend: function() {
// включение прелоудера
send = false;
},
complete: function() {
// отключение прелоудера
},
success: function(obj) {
send = true;
$('#more-news').remove(); //удаляем текущю кнопку
$("#get_news").append(obj['html'])//добавляе готвую разметку
if('show_more' == true){
$('#more-news').show();
} else {
$('#more-news').hide();
} //добавляем кнопку если пришел флаг
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + xhr);
}
});
}
});
I cannot see your HTML, so assuming that #more-news is where you would want to dock to
Add this to the success block after the element is visible
var element = $('#more-news').get(0)
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
More options here - https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Smooth behavior is limited to certain browsers.

Chat box scroll bar not updating with new messages

I have a chat box which works well. It fetches the messages between two users and positions the scroll bar at the bottom until the user scrolls up. When a user sends a new message, the scroll bar jumps to the bottom and the new message is shown.
<script>
var currentID = null;
var chatTimer = null;
var scrolled;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
//fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#messages").show();
$('#messages').html(data);
$("div.area").show();
//chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time
if(!scrolled){
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
scrolled=true;
}
}
});
}
$(document).ready(function() {
$("#messages").on('scroll',function(){
scrolled=true;
});
fetch_data();
$(document).on('click', '.first_name', function() {
scrolled=false;
currentID = $(this).data("id1");
fetch_chat();
});
setInterval(function() {
fetch_chat();
}, 500);
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
});
});
});
</script>
I am using setInterval() to refresh fetch_chat() every time so that the user who is chatting sees the new message. The hiccup is that the setInterval() displays the chatbox, which I want to be displayed only when a user clicks on a name. The second thing is that when user 'a' sends a message to user 'b', the scroll bar remains at the bottom and the new text is shown on a's side but the scroll bar doesn't move to the bottom on b's side.

keep the scroll to bottom with appending text to it

I have created a chatbox which scrolls to bottom at first and the scroll bar remain their until user scrolls up.But a new text is inserted instead of scroll bar moving to downward it remain at the same position.
<script>
var currentID = null;
var chatTimer = null;
var scrolled=false;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
//fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#messages").show();
$('#messages').html(data);
$("div.area").show();
//chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time
if(!scrolled){
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
}
}
});
}
$(document).ready(function() {
$("#messages").on('scroll',function(){
scrolled=true;
});
fetch_data();
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
//immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
//clearTimeout(chatTimer);
fetch_chat();
});
function scrollToBottom() {
$("#messages").scrollTop(1e10); // Lazy hack
}
setInterval(function() {
fetch_chat();
}, 500);
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
scrollToBottom();
});
// alert(text);
});
//this will also trigger the first fetch_chat once it completes
});
</script>
I just want to keep that scroll at the bottom even after user enter a new text.
the scroll should always remain at bottom but should be scrollable when user wish to do so.
First read the height of current chat box using jQuery like this,
var scrollToheight = $("#message").height();
And then use this height to scrollTop jQuery function :
$("#message").scrollTop(scrollToheight);
This should work for you always.

autofocus(autotab) on next element is not working for dynamically created fields

$("#destination1" + countVar).autocomplete({
minLength : 3,
source : function(request, response) {
var url = configOptions.icaocodeUrl;
var term = request.term;
url=url+term;
console.log(url);
$.ajax({
url : url,
type : "GET",
data : request,
dataType : "json",
success : function(data) {
response(data.slice(0, 10));
//alert(data);
},error: function(xhr, textStatus) {
alert('error');
}
});
},
change:function(event,ui){
console.log("fired in dest2");
},close:function(event,ui){
console.log("close in dest2"+'#dof1'+countVar);
console.log(countVar);
$(this).parents('form').find('#dof1'+countVar)
.filter(function () { return $(this).val() === ''; })
.first().focus();
}
});
above is my code for autocomplete and autotab(autofocus) to next field for dynamically created elements.autotab(autofocus ) is working fine for normal html but it is not working for dynamically created elements only.
Are you trying to focus() on a tab that is being dynamically added? If so, you might be triggering focus() to soon and the DOM element might not be there.
Try wrapping the focus function into a setTimeout() function to test it out.
setTimeout(function () {
$(this).parents('form').find('#dof1'+countVar)
.filter(function () { return $(this).val() === ''; })
.first().focus();
}, 2000); // 2 seconds

Why does this JavaScript freeze IE6?

When you click, "Add to Bag" on this page, it freezes IE6 every time. How can I figure out why it is freezing? Does anyone have a more direct answer?
totallytrollbeads {dot} com {slash} Safety0.html
function update() {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/cgi-bin/ajax_cart_count.cgi',
timeout: 2000,
success: function (data) {
// If bag is empty, it's see through.
if (data.cart_count == 0) {
$(".shopping_bag").css("opacity", ".2");
}
// If bag is not empty, it's not see through.
else {
$(".shopping_bag").css("opacity", "1");
}
$("#bag_total").html(data.grand_total);
$("#bag_count").html(data.cart_count);
window.setTimeout(update, 15000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#bag_total").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
})
}
$(document).ready(update);
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// $(".add_to_cart_form").click(function () {
// $('.bypass_add_to_cart_form').ajaxForm({ success: myBox });
// });
function loading() {
$("#loadingContent").show();
}
function myBox(resptext, statustext) {
$("#loadingContent").hide();
Boxy.ask(resptext, ["View Bag", "Continue Shopping"], function (val) {
if (val == "View Bag") {
document.location.href = "/cgi-bin/store.cgi?action=view_cart";
}
if (val == "Continue Shopping" && product_detail == 1) {
history.go(-1);
}
}, {
title: "Add to Bag"
});
$('.bypass_add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
update();
return false;
}
/*
This tells the ajax-style add to cart that
it's on a product detail page so if the
user clicks "Continue Shopping" it takes
them back on step in their history.
*/
$('.search_view').click(function () {
product_detail = 0;
});
$('.product_view').click(function () {
product_detail = 1;
});
It's not easy to debug a thing that freezes immediately from the outside. But it's always a good idea to cleanup the whole, remove things that are not essential, check the functionality and then do the next step.
For example this:
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
It's not hard to see that have this part twice there.
Put a little more accuracy into your application instead of copy&paste.

Categories

Resources