So I was wondering something.
In a IM/chat website I'm making, I have it check the database every 10 seconds or so to see if any new data has come in. And also, when the user posts a new comment, it automatically sends it to the database and adds it to the comment list without reloading. But it loads all the comments each time.
I was wondering if its possible to add an effect to the new comment (such as fading in) without doing that to all the old comments as well.
function update(){
oldhtml = $('#listposts');
$.ajax({
type: "POST",
data: "",
url: "update.php",
success: function(msg){
$("#listposts").html(msg);
$('.comment_date').each(function(){
$(this).text('[' + prettyDate($(this).text())+']');
if(oldhtml == )
});
}
});
}
var intervalID = window.setInterval(update, 10000);
That's my update code. Here's my post code:
$("#postbutton").click(function () {
if(!$('#post').val()==""){
$.ajax({
type: "POST",
data: "data=" + $("#post").val(),
url: "post.php",
success: function(msg){
$("#listposts").html(msg);
$('.comment_date').each(function(){
$(this).text('[' + prettyDate($(this).text())+']');
});
}
});
$("#post").val("");
}
});
I'm also using prettyDate, as you can see. But that has nothing to do with this problem.
So as the title states, I was gonna try to save the current html in a variable (oldhtml) and then load the new stuff. Then I would compare the two and just use the new comment to fade in. Am I way out there? Am I missing the point?
Oh and please don't down vote me just cause I missed an obvious solution. I thought you're supposed to use it if I don't explain well, which I think I did.
You can do this in your success handler:
var $dv = $('<div />').css('display', 'none').html(msg);
$("#listposts").append($dv);
$dv.fadeIn();
Of course you can use a <span> instead of <div> depending on your needs.
Similar to Blaster's...
$('<div />').html(msg).appendTo('#posts').hide().fadeIn();
Related
I have a website where you can edit inline by clicking the table cell. After click and type the string, you need to press enter in order to update the data. My problem is, I want to automatically send the data without pressing enter. What key event should i use with this one? onkeypress? and how would i remove the enter key event?
$('td.edit').keydown(function(event){
arr = $(this).attr('class').split( " " );
if(event.which == 13)
{
$.ajax({type: "POST",
url: "../../controller/inline.php",
data: "value="+$('.ajax input').val()+"&rownum="+arr[2]+"&field="+arr[1]+"&ids="+'<?php echo isset($_POST['frmID'])?$_POST['frmID']:$_GET['id']; ?>'+"&dFrom="+'<?php echo isset($_POST['frmDateFrom']) ? $_POST['frmDateFrom']:date('n\/j\/Y', strtotime("-15 days")); ?>'+"&dTo="+'<?php echo isset($_POST['frmDateTo'])?$_POST['frmDateTo']:date('n\/j\/Y'); ?>',
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}});
}
});
Well, I experienced same situation too.
You really need to save automatically?
Simple solution is 'focusout()' or 'onBlur()' maybe.
But it is too risky.
It means just single miss click or miss key press firing save event.
If you have multiple columns to input somthing.
Don't do that.
But just single column, try 'onBlur()' or 'focusout()'
I'll waiting your wise solution. :3
I believe an onBlur event is what you're looking for. http://api.jquery.com/blur/
What you can do (although I wouldn't recommend it) is to use a setTimeout to save the data. This way the user can keep on typing without saving, but once he stops typing for a second or so it will save the data.
Take a look at the example here (http://jsfiddle.net/G2LxD):
var timer;
$('input').keyup(function() {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
$.ajax({
type: "POST",
url: "../../controller/inline.php",
data: "[your-data]",
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
}, 1000);
});
Having some serious troubles with making a Live update after a Live call. The event is added to the dBase, but I don't seem to get to change the contents of the changed.
As you can see, we have a unique div id in which we want the confirmation to show (being: '#yvr_add'+id).
Just to be clear: this takes place within a
"live('click',function()"
. Tried everything so far (even live reloading divs), but I just don't get it running.
Yes sir (#Ohgodwhy),
This is the code, passing two vars: a YouTube videoId and a personal videobookID on our server.
$('.yt_add_vid').live('click',function(){
var addItem = $(this).attr('id');
var selectVal = $('#album'+addItem + ' :selected').val();
var dataString = 'ytid='+ addItem + '&bookid=' + selectVal;
$.ajax({
type: "POST",
url: "/xxx/do_my_update.php",
cache: false,
data: dataString,
success: function(data){
$('#yvr_add'+ytid).html('added your entry.');
},
error : function(data) {
alert('Dude, stay focussed now!');
}
});
});
fixed it with the return of
success: function(data){...
you can do anything after that.
Thanks for the respones guys!
I have a problem with my JQuery script. I am making a 2d chat where people have their own figure like Habbo hotel, but the JQuery script that is suppose to move the figures is bugging.
I think it is easier to show the problem:
Click here to see the problem
I am using the following script to update the figures:
function UpdateRoom() {
var data = 'roomId='+roomId;
$.ajax({
type: "GET",
url: "chatfunctions/updateroom.php",
dataType: 'json',
data: data,
success: function(data){
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).append('<div class="user" id="'+charId+'" />');
});
}
});
}
The #f+temp is the id of the field that the figure should be places at. The charId is the id of the figure.
And then I am calling the script every 500 miliseconds:
window.setInterval(function() {
UpdateRoom();
}, 500 );
Im not sure if this is enough code and example for you guys to help me. If not please tell me if I need to provide more for you to help me. My guess is that it is the .append(); function that is used wrong, but I'm no expert in JQuery.
You are only continuing to append but not replacing anything.
Try to either use .html() or .empty().
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).html('<div class="user" id="'+charId+'" />');
});
or
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).empty(); // clear out all content
$('#f' + temp).append('<div class="user" id="'+charId+'" />');
});
not knowing your code you might need to move the call to .empty() outside your each loop.
I have put together an ajax powered chat/social network with jquery, PHP - but am having problems with the javascript.
I have a js file in the main page which loads the php in a div container, the js file is underneath the div. But only one function for posting a msg seems to work but the others do not.
I have tried including the js file with the dynamically loaded php at the end of the ajax load the functions work fine but am getting mutiple entries of the same message/comment.
I am pretty sure its not the PHP as it seems to work fine with no ajax involvment. Is there a way to solve this?
this is the function that works fine:
$("#newmsgsend").click(function(){
var username = $("#loggedin").html();
var userid = $("#loggedin").attr("uid");
var message = $("#newmsgcontent").val();
if(message == "" || message == "Enter Message..."){
return false;
}
var datastring = 'username=' + username + '&message=' + message + '&uid=' + userid;
//alert(datastring);
$.ajax({
type: "POST",
url: "uploadmsgimage.php",
data: datastring,
success: function(data){
document.newmessage.newmsgcontent.value="";
//need to clear browse value too
$('.msgimage').hide('slow');
$('#addmsgimage').show('slow');
$(".usermsg").html(data);
$("#control").replaceWith('<input type="file" name="file"/>');
$(".msgimage").remove();
}
});
});
And this is one of them that does not work:
//like btn
$(".like").click(function(){
var postid = $(this).attr("pid");
var datastring = 'likeid=' + postid;
$.ajax({
type: "POST",
url: "addlike.php",
data: datastring,
success: function(data){
$(".usermsg").html(data);
}
});
});
From your post, I'm guessing that each message has a "Like" button, but you have 1 main submit button. When messages load dynamically, you have to assign the .like to each one when they come in, otherwise it will only be assigned to the existing messages.
The problem, from what I gather (and this is a guess) would probably be fixed using live so jQuery will automatically assign the click function to all messages including dynamically loaded messages; so instead of:
$(".like").click(function(){
Try this:
$(".like").live('click', function(){
If that doesn't solve the problem, then I'm probably not understanding what it is.
Hy,
I have a live username validation using ajax :
<td id="user_process_live"><input type="text" id="user_live_ver" name="user" /></td>
abnd the following java :
$("input#user_live_ver").blur(function() {
var username=$(this).val();
var dataString = 'username=' + username;
$.ajax({
type: "POST",
url: "ajax/login_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$("td#user_process_live").html(html);
}
});
});
The login_ajax.php returns the same <input type=text id=user_live_ver name=user /> but with different styles applied (background-color and border-color) : red if username already exist and green if user does not exist ...
The problem is the script does this just one time .. just one .blur() ...
If i remove the .ajax({ ... etc }); and insert alert(dataString); every time i click out that input the alert() is triggered but not the same for the .ajax() ...
What seems to be the problem ? Thanks a lot
The problem is that you are replacing the input after the first ajax request returns so your blur event isn't bound anymore. Try using delegate to bind your event:
var process_live = $("#user_process_live");
process_live.delegate("#user_live_ver", "blur", function() {
var username = $(this).val(),
dataString = {'username': username};
$.ajax({
type: "POST",
url: "ajax/login_ajax.php",
data: dataString,
cache: false,
success: function(html) {
process_live.html(html);
}
});
});
When you add the html string back in with the success function, you loose the event handler attached to the input element.
Maybe try changing the styles on the input depending on what you get back in the success function rather than replacing the HTML entirely.
success: function(result) {
if (result) {
$("input#user_live_ver").addClass("valid");
} else {
$("input#user_live_ver").addClass("invalid");
}
}
All your PHP script has to do now is return true if the username is valid and false if not.
Use json_encode($result)
Maybe the reference for blur event was lost after the html replace, I dont try so I dont know.
but did you try to set the blur event again?
This is probably happening because you're removing the element that $("input#user_live_ver") references and then adding a new one to the DOM, so that blur event binding goes away.
You have two options:
Use .live() to bind the event so that it also binds to future matching elements. More info here.
Don't replace the DOM element in the response from the AJAX resource. Just re-style it. (This will offer slightly better performance as well.)
java*SCRIPT*... they are VERY different things! And, instead of returning an input, why not return a success or fail message and update the class accordingly? Saves a few DOM calls