scroll div down on specific event - javascript

I have a simple chat application using Ajax and HTML.
Whenever I load new messages, I want to scroll the div to show the most recent message, so I'm doing the following:
jQuery:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}
});
}
}
I use this line to scroll the div down to the maximum:
$("#conversation").scrollTop($("#conversation").outerHeight()*1000);
My problem is, it scrolls down to the maximum WITHOUT showing the new messages. It scrolls down till the last message before the new one. Which is weird, because I'm calling it after updating the chat. Here's the function that updates the chat:
function UpdateChat(){
$.ajax({
// URL that gives a JSON of all new messages:
url: "url",
success: function(result)
{
var objects = JSON.parse(result);
$("#conversation").html("");
objects.forEach(function(key, index){
//append the messages to the div
$("#conversation").append("html here");
});
}
});
};

As mentioned in comments, you can use a setTimeout() to let the dom update add give some time before scrolling. See code below:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
setTimeout(function() {
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}, 500);
}
});
}
}

Assuming you insert a new element at the bottom, you could use scrollIntoView to make sure the new element is visible:
$.ajax({
// ...
success: function(data) {
var lastElement = $('#conversation :last-child');
lastElement[0].scrollIntoView();
}
});

Try putting the scroll line inside a setTimeout() method to allow about 500ms for things to update before scrolling down.
jQuery:
function SendMessage(){
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '') {
$.ajax({
type: 'POST',
url: url,
data: {
email: email,
message: clientmsg
},
success: function (data) {
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
setTimeout(performScroll, 500);
}
});
}
}
and the scroll function
function performScroll() {
$("#conversation").scrollTop($("#conversation").outerHeight()*1000);
}

Related

How to use refresh div correctly?

Hi,
Can you explain why my refresh div does not work? When clicked submit it seems the div is trying to refresh by removing all rows data but it is then not returning anything which leaves the div blank instead. The data stored to DB fine but I need the div to refresh and show all new submitted data
$('#submitBtm').on('click', onSubmit = () => {
const first_nameV = document.getElementById("first_name").value;
const last_nameV = document.getElementById("last_name").value;
const emailV = document.getElementById("email").value;
const departmentV = document.getElementById("department").value;
$.ajax({
type: "POST",
url: `companydirectory/libs/php/insertAll.php?first_name=${first_nameV}&last_name=${last_nameV}&email=${emailV}&departmentID=${departmentV}`,
success: function(data) {
},
error: function(request,error) {
console.log(request)
}
})
$("#id_data").load(location.href + " #id_data");
event.preventDefault();
})
on HTML page
<div class="listTable">
<tbody id="id_data">
</tbody>
</div>
It doesn't update because you're not appending the new data that you receive on the success callback
$.ajax({
type: "POST",
url: `companydirectory/libs/php/insertAll.php?first_name=${first_nameV}&last_name=${last_nameV}&email=${emailV}&departmentID=${departmentV}`,
success: function(data) {
// here you have the data and you can refresh the table
},
error: function(request,error) {
console.log(request)
}
})

Why do the ajax requests fire multiple times

I have a form inside a modal that either saves a memo when one button is clicked or deletes it when another is clicked. The items get saved/deleted but the request count multiplies with each click. I'm getting 4 of the same request etc. How do i stop this. do i have to unbind something?
$('#modal').on('show.bs.modal', function (e) {
var origin = $(e.relatedTarget);
var memoId = origin.attr('data-id');
$('#modal').click(function(event){
if($(event.target).hasClass('memo-save')) {
event.preventDefault();
var memoText = $(event.target).parent().parent().find('textarea').val();
var memo = {
memo: memoText,
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/add-memo?memo=' +memo+'&id=' + memoId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Saved');
}
});
} else if($(event.target).hasClass('memo-delete')) {
event.preventDefault();
var memoText = "";
var memo = {
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/remove-memo?id=' + itemId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Deleted');
}
});
}
});
});
you can move the $('#modal').click outside the $('#modal').on('show.bs.modal' that way it will not re-add the listener each time the modal is shown

stopping a function after first click, to prevent more executions

I have this function
function display() {
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
and it serves its purpose, the only problem is, a user can click on for as many times as possible, and it will send just as many requests to new.php.
What I want is to restrict this to just 1 click and maybe till the next page refresh or cache clear.
Simple example would be :
<script>
var exec=true;
function display() {
if(exec){
alert("test");
exec=false;
}
}
</script>
<button onclick="javascript:display();">Click</button>
In your case it would be :
var exec=true;
function display() {
if(exec){
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
exec=false;
}
});
}
}
This should do what you want:
Set a global var, that stores if the function already was called/executed.
onceClicked=false;
function display() {
if(!onceClicked) {
onceClicked=true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
}
During onclick, set a boolean flag to true to indicate that user clicked the link before invoking the display() function. Inside the display() function, check the boolean flag and continue only if it is true. Reset the flag to false after the AJAX completed processing (successful or failed).
You can use Lock variable like below.
var lock = false;
function display() {
if (lock == true) {
return;
}
lock = true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function (data) {
$('.daily').html(data);
lock = false;
}
});
}
you can implement this with that way too
$(function() {
$('#link').one('click', function() {
alert('your execution one occured');
$(this).removeAttr('onclick');
$(this).removeAttr('href');
});
});
function display(){
alert('your execution two occured');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="display();" id='link'>Have you only one chance</a>

How to redirect in ajax after successfully post of data

I am submitting form data using Ajax and they are successfully saved in the database and I am able to alert the response data. I now want to use the returned data as response to call another function using Ajax and pass them as parameters so that to the called function they can be used to fetch data and and display them on the web page.
The problem is that when the data have been alerted, the function I call using Ajax is not responding even when I use some functions like window.location.href, window.location.replace, window.location.reload they are not executed
Here is the sample code
submitHandler: function(form) {
/*errorHandler.hide(); */
var el = $(div);
el.block({
overlayCSS: {
backgroundColor: '#fff'
},
message: '<i class="fa fa-refresh fa-spin"></i>',
css: {
border: 'none',
color: '#333',
background: 'none'
}
});
/*Set off for database validation */
$('#name1').removeClass('has-error');
$('#name1 .help-block').empty();
$('#date1').removeClass('has-error');
$('#date1 .help-block').empty();
/*end database validation */
/*ajax options */
var options = {
/*target: '#output2', target element(s) to be updated with server response */
success: function(data, textStatus, XMLHttpRequest) {
el.unblock();
if (!data.success) {
/*append error message on the form for each control and database validation*/
console.log(data);
if (data.errors.name1) {
$('#name1').addClass('has-error');
$('#name1 .help-block').html(data.errors.name1);
}
} else {
var business_id = data.business_id;
var bnm_app_id = data.bnm_app_id;
var name = data.name;
var doc = data.doc;
alert(business_id);
alert(bnm_app_id);
alert(name);
alert(doc);
if (window.XMLHttpRequest) {
myObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
myObject = new ActiveXObject('Micrsoft.XMLHTTP');
myObject.overrideMimeType('text/xml');
}
myObject.onreadystatechange = function() {
data = myObject.responseText;
if (myObject.readyState == 4) {
//document.getElementById('step-2').innerHTML = data;
window.location.reload(true);
}
}; //specify name of function that will handle server response........
myObject.open('GET', '<?php echo base_url()."bn_application/register";?>?bnm_app_id=' + bnm_app_id + '&doc=' + doc + '&business_id=' + business_id + '&name=' + name, true);
myObject.send();
}
},
error: function(xhr, textStatus, errorThrown) {
el.unblock();
if (xhr.responseText === undefined) {
$.gritter.add({
/* (string | mandatory) the heading of the notification */
title: 'Connection timed out',
class_name: 'gritter-black'
});
} else {
var myWindow = window.open("Error", "MsgWindow", "width=900, height=400");
myWindow.document.write(xhr.responseText);
}
/*clear controls that do not need to keep its previous info */
},
url: home + 'bn_application/save_clearance_name',
/* override for form's 'action' attribute*/
data: {
name1_percent: name1_percent
},
type: 'post',
/* 'get' or 'post', override for form's 'method' attribute*/
dataType: 'json',
/* 'xml', 'script', or 'json' (expected server response type)*/
beforeSend: function() {
},
uploadProgress: function(event, position, total, percentComplete) {
},
complete: function() {
}
};
/*submit form via ajax */
$('#bn_clearance').ajaxSubmit(options);
}
If i understand you right , you need something like this ?
$.ajax({
type: "GET",
url: baseUrl + 'api/cars',
success: function (firstResponse) {
$.ajax({
type: "GET",
url: baseUrl + 'api/cars/' + firstResponse[0].Id,
success: function (secondResponse) {
window.location.href = secondResponse[0].Make;
}
});
}
});
You can use window.open function
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
window.open("http://www.w3schools.com", "_self");
}});
});
You should put your redirecting url in success function of ajax. (if you are using jQuery). Because javascript runs codes asynchronously and probably your code tries to run before you get response from request.

jQuery AJAX: Update [LastVisitDate] Field on POST?

I have the below Login JavaScript for my MVC4 Application. I am attempting to add a value with my POST data to update the [LastVisitDate] each time a user logs in. However, whenever I login with my credentials, the value is still shown as 4/18/2014 10:04:47 AM. I have verified my cache has been cleared and am at a loss as to what I may be doing wrong.
Anyone have some thoughts on the matter?
function login()
{
var userName = $("#username").val();
var password = $("#password").val();
var rememberme = $("#rememberMe").is(':checked');
// NEWLY ADDED
var datestamp = Date.now();
var data =
{
Email: userName,
Password: password,
RememberMe: rememberme,
// NEWLY ADDED
LastVisitDate: datestamp
};
$.ajax(
{
url: "/Account/Login",
type: "POST",
data: data,
cache: false,
async: true,
success: function (data) {
$("#loginAlert").remove();
if (data.returnUrl != undefined) {
window.location.href(data.returnUrl);
}
else {
window.location.reload();
}
},
error: function (result) {
if ($("loginAlert").length() == 0) {
var errorMsg = 'There was an error.';
$("#navBar").after(errorMsg);
}
}
});
}
function EnterKeyPressed () {
if (event.keyCode == 13) {
login();
}
}
function closeAlert() {
$("#loginAlert").alert("close");
}
You have just posted the Ajax code and there is no clear information on what is going on in the background.
But based on your question I am assuming you are not returning the last logged in date. If its a SQL query then you need to perform a Order by date DESC. See if it helps :)

Categories

Resources