This is the script I use for various purposes like scrolling, getting the data from php etc:
<script>
$(document).ready(function(){
$("#full_chat").animate({ scrollTop: $('#full_chat')[0].scrollHeight+1000}, 1500);
setInterval(function refreshPage() {
var user=$("#head").text();
$.post("retrieve.php",{ user:user }, function(data,status){
if($.trim(data)!="0"){
$("#full_chat").append("<span class='you'>"+data+"</span>");
$('#full_chat').emoticonize();
window.onblur = function () {
$('#full_chat').bind("DOMSubtreeModified",function(){
$.titleAlert("New Message!", {
requireBlur:true,
stopOnFocus:true,
//duration:10000,
//interval:500
});
});
}
}
}); }, 1500);
$("#form").on('submit',function (e) {
e.preventDefault();
var user=$("#head").text();
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var txt= $("#chat_input").val();
$.post("chat.php",{ txt:txt,user:user,time:time },function(data,status){
if(data=="OFFLINE"){
$("#full_chat").append("User not available right now<br>");
}else{
$("#full_chat").append("("+time+") ").append("<span class='me'>"+"Me: "+txt+"</span><br>").emoticonize({delay: 1,animate:false});
}
});
$("#full_chat").animate({ scrollTop: $('#full_chat')[0].scrollHeight+1000}, 1500);
$('#chat_input').val('');
});
});
</script>
This is the PHP code I use to get the chats from database:
<?php
session_start();
$other_user=$_POST['user'];
$flag=$_POST['flag'];
include_once('db.php');
$uname=$_SESSION['username'];
//date_default_timezone_set('Asia/Kolkata');
$q="select message,sender,time from chat where username='$uname' and delivered=0 and sender='$other_user' order by time ASC";
$qe = mysqli_query($con,$q);
$q1="UPDATE chat SET delivered=1 WHERE username='$uname' and sender='$other_user'" ;
$qe1 = mysqli_query($con,$q1);
if($r=mysqli_fetch_array($qe)) {
echo "(".$r['2'].") ". $r['1'].": ".$r['0']."<br>";
}else {
echo "0";
}
mysqli_close($con);
?>
What may be the reason for the problem? Is it the page refresh that happens every 1.5 seconds or something else?
This is just to give you an idea, it is not tested.
<script>
$(document).ready(function() {
var user = $("#head").text();
var postTimeout = 0;
var refreshPage = function(postInterval, postData) {
$.post("retrieve.php", postData, function(data, status) {
if (!postTimeout) {
postTimeout = setTimeout(function() {
refreshPage(postInterval, postData);
postTimeout = 0;
}, postInterval);
}
if ($.trim(data) != "0") {
$("#full_chat").append("<span class='you'>" + data + "</span>");
$('#full_chat').emoticonize();
window.onblur = function() {
$('#full_chat').bind("DOMSubtreeModified", function() {
$.titleAlert("New Message!", {
requireBlur: true,
stopOnFocus: true,
//duration:10000,
//interval:500
});
});
}
}
});
}
$("#full_chat").animate({
scrollTop: $('#full_chat')[0].scrollHeight + 1000
}, 1500);
refreshPage(1500, {user: user});
$("#form").on('submit', function(e) {
e.preventDefault();
var user = $("#head").text();
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var txt = $("#chat_input").val();
$.post("chat.php", {
txt: txt,
user: user,
time: time
}, function(data, status) {
if (data == "OFFLINE") {
$("#full_chat").append("User not available right now<br>");
} else {
$("#full_chat").append("(" + time + ") ").append("<span class='me'>" + "Me: " + txt + "</span><br>").emoticonize({
delay: 1,
animate: false
});
}
});
$("#full_chat").animate({
scrollTop: $('#full_chat')[0].scrollHeight + 1000
}, 1500);
$('#chat_input').val('');
});
});
</script>
Related
I am trying to query a large data from the database and I wish to display a progress bar. The code below returns data info from the server but the progress bar just jumps to 100% while the Ajax is still querying data.
I guess the proper way is to fake the progress bar timer or possibly make a timely ajax call eg per seconds to update the progress bar. Can someone help me out with my issue? Thanks
Below is the working code so far
<html>
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
function pf(event) {
if (event.lengthComputable) {
var percentComplete = Math.round((event.loaded/event.total)*100);
$(".progressbar").width(percentComplete + '%');
$(".progressbar").html('<span>' + percentComplete +' %</span>')
$(".progressbar").html('<span> ' + percentComplete +'% Completed</span>')
}
};
$("#sForm").on('submit',(function(e) {
e.preventDefault();
$('.progressbar').css('width', '0');
$.ajax({
url: "qdata.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", pf, false);
return xhr;
},
success: function(data)
{
if(data.trim() == "good"){
alert('completed now');
}
},
error: function()
{
}
});
}));
});
</script>
</head>
<body>
<div class="progressbar"></div>
<form id="sForm" action="qdata.php" method="post">
<div id="resultdata"></div>
<input type="submit" value="Submit now" />
</form>
</body>
</html>
qdata.php
// This is just sample db
//dbconfig.php
$result = $db->prepare('SELECT fullname FROM users');
$result->execute(array());
$count = $result->rowCount();
while ($row = $result->fetch()) {
$name=htmlentities($row['fullname'], ENT_QUOTES, "UTF-8");
}
echo 'good';
you can show percentage of progress in xhr as
xhr: function () {
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
console.log('percent', percent);
$('.progressbar').css("width", percent + '%');
}, true);
}
return xhr;
},
I am using setInterval and then unable to clearInterval in my code. Please see the code
I am getting the value of complete and it is true and also entering the if statement but clearInterval still not working. I am tired and trying for last 10 hours but not find the bug. I checking the console.log and it is not stopping the interval.
jQuery(document).ready(function() {
var complete = false;
var Interval;
jQuery( "#form" ).submit(function() {
Interval = setInterval(get, 100);
post();
return false;
});
function post(){
var url = "my/url/here";
var data = {
'action': 'action/here',
'name': 'value'
};
jQuery.post(url, data, function(response) {
jQuery("#emails").html(response);
}).done(function() {
//alert( "second success" );
})
.fail(function() {
//alert( "error" );
})
.always(function() {
complete = true;
//alert( "finished" );
});
} // End post()
function get(){
var url = "url/goes/here";
if(complete == true){
clearInterval(Interval);
}
var data = {
'action': 'action/here',
};
jQuery.get(url, data, function(response) {
console.log(response);
jQuery("#progress").html(response);
});
} // End get()
});
here is the original code below. ajax call is working fine but clearInterval() not working
<script type="text/javascript" >
jQuery(document).ready(function() {
jQuery(".juee_emails_row").hide();
var juee_complete = false;
var juee_Interval;
jQuery( "#juee_form" ).submit(function() {
jQuery(".juee_emails_row").show();
juee_Interval = setInterval(juee_get, 100);
juee_post();
return false;
});
function juee_post(){
var data = {
'action': 'juee_get_emails',
'juee_data_option': jQuery('input[name=juee_data_option]:checked', '#juee_form').val()
};
jQuery.post(ajaxurl, data, function(response) {
jQuery("#juee_emails_td").html(response);
}).done(function() {
//alert( "second success" );
})
.fail(function() {
//alert( "error" );
})
.always(function() {
juee_complete = true;
//alert( "finished" );
});
} // End juee_post()
function juee_get(){
if(juee_complete == true){
clearInterval(juee_Interval);
}
var data = {
'action': 'juee_progress',
};
jQuery.get(ajaxurl, data, function(response) {
console.log(response + " email found");
jQuery("#juee_progress_td").html("");
jQuery("#juee_progress_td").html(response);
});
} // End juee_get()
});
</script>
i am new to Jquery/Ajax and i am trying to have the source url for the json change based on the url parameters i setup, i have working version in PHP, but i don't know how to write it in JQuery
This is my PHP Code (what i am currently using
$id = urlencode($_GET['id']);
$page = urlencode($_GET['results']);
$url = "https://gdata.youtube.com/feeds/api/playlists/$id?alt=jsonc&v=2&max-results=25&&start-index={$results}";
This code grabs the id and includes it to alter the url of the source file used in the script
so how would i make this code act in the same way?
$(document).ready(function() {
startindex = 1;
loadmore = 20;
addMore(startindex, loadmore);
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore($('#list li').length, 20);
});
});
function addMore(startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/ID_WOULD_GO_HERE?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
Please help, Thanks!
Please try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="list"></div>
<script>
$(document).ready(function() {
startindex = 1;
loadmore = 20;
id = urlVar("id");
if (id!="") {
addMore(id, startindex, loadmore);
}
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore(id, $('#list li').size(), 20);
});
});
function urlVar(varName) {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars[varName]?vars[varName]:"";
}
function addMore(id, startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/"+ id +"?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
console.log(data);
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
</script>
To test: this_script.php?id=RD029cW4vF6U2Dc
Potentially you could also get PHP to put the variable into the URL before hand.
Example:
src = "https://gdata.youtube.com/feeds/api/playlists/<?php echo $_GET['id'];?>?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
I downloaded the script from here
http://www.webresourcesdepot.com/fly-to-basket-effect-with-jquery/
its good but some bugs like
Double Click => 3 Items add to basket
Tripple Click => 7 Items add to basket
i was trying to fix it but still cant get something .. then i see this link Disable Link while animated Basket
but i can understand where i place this code.. anybody help me to fix it please ...
$(document).ready(function(){
$("#basketItemsWrap li:first").hide();
$(".productPriceWrapRight a img").click(function() {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
var productX = $("#productImageWrapID_" + productIDVal).offset().left;
var productY = $("#productImageWrapID_" + productIDVal).offset().top;
if( $("#productID_" + productIDVal).length > 0){
var basketX = $("#productID_" + productIDVal).offset().left;
var basketY = $("#productID_" + productIDVal).offset().top;
} else {
var basketX = $("#basketTitleWrap").offset().left;
var basketY = $("#basketTitleWrap").offset().top;
}
var gotoX = basketX - productX;
var gotoY = basketY - productY;
var newImageWidth = $("#productImageWrapID_" + productIDVal).width() / 3;
var newImageHeight = $("#productImageWrapID_" + productIDVal).height() / 3;
$("#productImageWrapID_" + productIDVal + " img")
.clone()
.prependTo("#productImageWrapID_" + productIDVal)
.css({'position' : 'absolute'})
.animate({opacity: 0.4}, 100 )
.animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {
$(this).remove();
$("#notificationsLoader").html('<img src="images/loader.gif">');
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "addToBasket"},
success: function(theResponse) {
if( $("#productID_" + productIDVal).length > 0){
$("#productID_" + productIDVal).animate({ opacity: 0 }, 500);
$("#productID_" + productIDVal).before(theResponse).remove();
$("#productID_" + productIDVal).animate({ opacity: 0 }, 500);
$("#productID_" + productIDVal).animate({ opacity: 1 }, 500);
$("#notificationsLoader").empty();
} else {
$("#basketItemsWrap li:first").before(theResponse);
$("#basketItemsWrap li:first").hide();
$("#basketItemsWrap li:first").show("slow");
$("#notificationsLoader").empty();
}
}
});
});
});
$("#basketItemsWrap li img").live("click", function(event) {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
$("#notificationsLoader").html('<img src="images/loader.gif">');
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "deleteFromBasket"},
success: function(theResponse) {
$("#productID_" + productIDVal).hide("slow", function() {$(this).remove();});
$("#notificationsLoader").empty();
}
});
});
});
I think what you might have to-do is at the end of the click event function then unbind the event http://api.jquery.com/unbind/ $(this).unbind();
You could possibly bind it again once the ajax has finished
I have now managed to get a status posted when a user clicks a link. I would now like a status to be posted when they first login with Facebook and accept the permissions.
Please help! I am using this code for the login button:
<fb:login-button ></fb:login-button>
Be specific with me I'm new to the Facebook Connect.
Since you managed to authenticate a user and post from a link, then things will be easy, just on the auth.login event call your posting method, something like this would do:
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo $this->facebook->getAppId(); ?>', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('auth.login', function() {
postStatus();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function postStatus(){
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
Result:
EDIT:
Also make sure you have the right permissions in your case publish_stream:
<fb:login-button perms="read_stream,publish_stream"></fb:login-button>
Just modify this code
<div id="fb-root"></div>
<script type="text/javascript">
var uid;
window.fbAsyncInit = function() {
FB.init({appId: 'APP_ID', status: true, cookie: true, xfbml: false});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
window.fbAsyncInit = function() {
FB.init({appId: 'APP_ID', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
function graphStreamPublish(){
var body = document.getElementById("txtTextToPublish").value;
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name,email,hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
uid = rows[0].uid;
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'Your email: ' + rows[0].email + "<br />" +
'Your hometown_location: ' + rows[0].hometown_location + "<br />" +
'Your sex: ' + rows[0].sex + "<br />" +
'Your uid: ' + rows[0].uid + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />"
'<fb:multi-friend-selector actiontext="Select the friends you want to invite. (All of them.)" rows="3"/>';
});
});
}
function getFriends(){
var theword = '/me/friends';
var params = new Array(uid);
FB.api(theword,params, function(response) {
var divInfo = document.getElementById("divInfo");
var friends = response.data;
divInfo.innerHTML += '<h1 id="header">Friends</h1><ul id="list">';
for (var i = 0; i < friends.length; i++) {
divInfo.innerHTML += friends[i].id+" "+friends[i].name+"<img src=https://graph.facebook.com/"+friends[i].id+"/picture/>";
// divInfo.innerHTML+= '<fb:name useyou=false uid=100001248074891 firstnameonly=true></fb:name>';//'<fb:name useyou=false uid='+friends[i].id+' firstnameonly=true></fb:name>';
}
});
}
function share(){
var share = {
method: 'stream.share',
u: document.getElementById('txtShare').value
};
FB.ui(share, function(response) { console.log(response); });
}
</script>
<fb:login-button
autologoutlink="true"
perms="email,user_birthday,status_update,publish_stream"></fb:login-button>