Pusher scrolling the latest message - laravel

Chat is no displaying latest message sent or receive. When it come to some point it just stop scrolling for the new message.
This part is the sending.
function send(to_user, message){
let chat_box = $("#chat_box_" + to_user);
let chat_area = chat_box.find(".chat-area");
$.ajax({
url: base_url + "/send",
data: {to_user: to_user, message: message, _token: $("meta[name='csrf-token']").attr("content")},
method: "POST",
dataType: "json",
beforeSend: function () {
// console.log('adfasdf');
if(chat_area.find(".loader").length == 0) {
chat_area.append(loaderHtml());
}
},
success: function (response) {
},
complete: function () {
chat_area.find(".loader").remove();
chat_box.find(".btn-chat").prop("disabled", true);
chat_box.find(".chat_input").val("");
chat_area.animate({scrollTop: chat_area.offset().top + $(document).height()}, 800, 'swing');
}
});}
this for receiving
function displayMessage(message){
// let alert_sound = document.getElementById("chat-alert-sound");
if($("#current_user").val() == message.from_user_id) {
let messageLine = getMessageSenderHtml(message);
$("#chat_box_" + message.to_user_id).find(".chat-area").append(messageLine);
} else if($("#current_user").val() == message.to_user_id) {
// alert_sound.play();
// for the receiver user check if the chat box is already opened otherwise open it
cloneChatBox(message.from_user_id, message.fromUserName, function () {
let chatBox = $("#chat_box_" + message.from_user_id);
if(!chatBox.hasClass("chat-opened")) {
chatBox.addClass("chat-opened").slideDown("fast");
loadLatestMessages(chatBox, message.from_user_id);
chatBox.find(".chat-area").animate({scrollTop: chatBox.find(".chat-area").offset().top + $(document).height()}, 800, 'swing');
} else {
let messageLine = getMessageReceiverHtml(message);
// append the message for the receiver user
$("#chat_box_" + message.from_user_id).find(".chat-area").append(messageLine);
}
});
}}
Problem is when i send or receive message it dont display the latest message. It go back on a certain point.

Related

XMLHTTPRequest dealing with event

I am performing an Ajax (JQuery) request on a php script which iterates. At each iteration I do an "echo" of the value of the loop counter, encoded in JSon. The goal is to manage the display of a progress bar.
By doing this I hoped to intercept and retrieve each of the counter values in a separate response thanks to the "progress" event.
Actually I only have one answer which contains all the counter values.
My research always leads me to information about downloading files, which is not my situation.
Maybe I should use the "onreadystatechange" event, but I don't see how to fit it into my code: $ Ajax parameter or separate function?
If anyone has an idea to solve my problem.
Here is my JS code
function DiffuseOffre(envoi, tab, paquet, dest) {
//$('#cover-spin').show(0);
$("#xhr-rep").css("display", "block");
var server = '/Admin/Offres/DiffuseOffre.php';
$.ajax({
url: server,
type: 'Post',
dataType: 'json',
data: {
envoi: envoi,
tab: tab,
paquet: paquet,
dest: dest
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var compteur = evt.text;
$("#xhr-rep").html(compteur);
}
}, false);
return xhr;
},
success: function(msg) {
//$('#cover-spin').css("display", "none");
$('#xhr-rep').css("display", "none");
if (msg.hasOwnProperty('erreur')) {
$("#dialog-erreur").html(msg.erreur);
$("#dialog-erreur").dialog("open");
$("#dialog-erreur").dialog({
width: '600px',
title: msg.title
})
} else {
$("#dialog-message").html(msg.message);
$("#dialog-message").dialog("open");
$("#dialog-message").dialog({
width: '600px',
title: msg.title
})
if (paquet == 1) {
$("#envoi_" + dest).remove();
$("#diffuser").remove();
}
if (msg.hasOwnProperty('encours')) {
$("#en_cours").html(msg.encours);
}
if (msg.hasOwnProperty('fieldset')) {
$("#" + msg.fieldset).remove();
}
}
}
})
}

Ext.Msg.show in ajax not append the page

I have a function for saving data. Before saving data there is dialog confirmation Yes or No. While I click option Yes the page behind this is back to the gridview (it's list). What i want is while click Yes the page behind is not change.
This is my function :
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
var str = "<br/><br/><span style='color:red;font-weight:bold'>Success add new PF !</span>";
MsgBox2("Budget Validation", result.Error + str);
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I add new dialog confirmation like this, but it does not work (didn't append the page after click Yes button):
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
$.post(root + "PF/GetSetupName", function (datas) {
if (datas == "FILTER_BRAND") {
Ext.Msg.show({
title: 'Over Budget',
msg: 'Budget is over. Modify or Not ?',
fn: function (btn) {
if (btn == "yes") {
SaveData("none");
}
else {
CancelData();
}
},
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION
});
}
});
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I try also separate this Ext.Msg.show in another function. but it doesn't work. Is there any idea please ?
I've found that when I try to do a mask and an ajax request at the same time, Ext gets overwhelmed and will not properly display the mask.
To fix this, I delay doing my ajax request until Ext & the browser have had enough time to properly display the mask. It generally does not need much time. In the example below, it waits 50 ms before posting.
Ext.get(document.body).mask("Updating data .. Please Wait ...", 'x-mask-loading');
Ext.defer(function() {
Ext.Ajax.request({ ... });
}, 50);
This gives the browser enough time to render the masking before it has to do anything else.

How to access the JSON on HTTP from an HTTPS page?

Here is my code I am trying to access the content on HTTP page from an HTTPS page it is giving me an error in browser console that it is an insecure content, following is an error ' Loading mixed (insecure) active content on a secure page "http://pnrbuddy.com/api/station_by_code/code/cnb/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/906544ca31f9c0048e80bde8127556af828e313b" ' , it is showing Json inbrowser console but unable to read it. How can I read that JSON?
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
//////////////////////////////////////////////
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
/* headers: {
"accept": "application/json;odata=verbose",
}, */
success: function (data) {
alert("Success");
alert(data.Station);
/* $.each(data.d.results, function (index, item)
{
alert("My ID"+index);
alert("Item"+item);
});
//var str=JSON.parse(data);
var myResults = [];
$.each(data, function (index, item) {
alert("dsfsd"+item.station_by_code)
myResults.push({
id: item.id,
//text: item.first_name + " " + item.last_name
});
}); */
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
/////////////////////////////////////////////
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
//////////////////////////////////////////////
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("Success");
alert(" Code : "data.stations[0].code+" Name : "+data.stations[0].name);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
/////////////////////////////////////////////
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();

Polling jQuery ajax for each. Check if element does not exist, if so prepend to div

I have a div #notification-data which on $(document).ready gets populated with multiple <li></li> from $.post.
The $.post then gets called setTimeout(poll_n,9000); so data is up-to-date.
So im not updating all the data every time, I would like to do check if the <li></li> already exists in #notification-data, if it does not exist then I would like to prepend() it to #notification-data.
The data comes in the form of:
<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>
As an extra question, is this the correct way of long polling?
Here is my code:
function poll_n(){
$.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {
$(data).find(".li_notification").each(function () {
var li_id = $(this).attr('id');
if ($(li_id).closest('#notification-data').length) {
//do nothing
} else {
$('#notification-data').append(??not_sure_what_goes_here??); // process results here
}
});
setTimeout(poll_n,9000);
});
}
EDIT - After answer I have now got this but it does not work (I get nothing in the console).
success: function(data){
$(data).find(".li_notification").each(function() {
var id = $(this).attr('id'),
notification = $('#notification-data');
console.log(id);
console.log('hello');
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend('#' + id);
}
});
},
You can try this:
function poll_n() {
$.ajax({
type: 'POST',
url: 'your url',
success: function(data){
var notification = $('#notification-data');
$.each($(data), function(){
var id = this.id;
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend(this);
}
});
},
complete: function(jqXHR, status) {
if (status === 'success') {
setTimeout(poll_n, 9000);
}
}
});
}
You must call poll_n() again after the request has been completed.

Jquery and live act wired but act ok after force refresh in IE

somthing is wrong with my code and i can't get what it is...
i have a div id = "personaltab"
i have a form in side it to login the user with username and password. if success the jquery empty the div and puts in the form of the bidding.
if the user try to bid the other ajax that assign to the button is working but for some reason skips the empty and just adding the responded ajax to the div
i have checked that in IE and chrome and it is working fine in chrome
here are my codes
$("#login").click(function() {
var id = $("input#pid").val();
var user = $("input#puser").val();
var pass = $("input#ppass").val();
var dataString = 'id='+ id + '&user='+ user + '&pass=' + pass;
if (user == "") {
alert("error");
$("input#puser").focus();
return false;
}
if (pass == "") {
alert("error");
$("input#ppass").focus();
return false;
}
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
if (msg=="False") {
alert("error");
$("#personaltab").show();
}
else {
$("#personaltab").fadeOut("normal",function(){
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").slideDown();
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
return false;
});
$("#sendbid").live("click", function(){
var startat = $("input[name=startat]").val();
var sprice = $("input[name=sprice]").val();
if (parseInt(sprice)<=parseInt(startat)) {
alert("error");
$("input[name=sprice]").focus();
return false;
}
else {
var payment = $("select[name=payment]").val();
if ($('input[name=credit]').is(':checked') ){
var credit = true;
}
var prodid = $("input[name=id]").val();
var dataString = 'id='+ prodid + '&price='+ sprice + '&payment=' + payment + '&credit=' + credit;
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
}
return false;
});
Solved:
i had inside a and for some reason the div that need to get the ajax by his id was duplicated
don't ask :-)

Resources