how to implement a scrollbar - javascript

I'm new to jquery and javascript and have no idea how to solve this problem: I have a simply jquery chat and there is a div with the id 'show_messages' in which I load all the messages from my ajax request. All works fine, the only problem ist, that the div for show messages gets longer and longer and I have absolutely no idea how to implement a scrollbar. I tried to use the jquery scroll function, but I hasn't worked and I don't know how to use it right. How can I make a simple scrollbar like in the facebook messenger or in similar messengers.
My Code:
<div id="message_dialog" class="message_box">
<div id="show_messages"></div>
<div id="feedback"></div>
<form action="#" method="post" id="message_form">
<label>Say something:</label>
<textarea id="message"></textarea>
<input type="submit" id="send_message" value="Send Message">
</form>
</div>
...
$(document).ready(function(){
$('#start_conversation').click(function() {
$('#message_dialog').dialog();
var interval = setInterval(function() {
$.ajax({
type : "POST",
url: 'get_messages.php',
success: function(data) {
$('#show_messages').html(data);
}
});
}, 1000);
return false;
});
});
$('#message_form').submit(function() {
var username = ...
var message = ...
$.ajax({
type : "POST",
url: 'send_message.php',
data: { 'username' : username, 'message' : message },
success: function(data) {
$('#feedback').html(data);
$('#feedback').fadeIn('slow', function() {
$('#feedback').fadeOut(6000);
});
$('#message').val('');
}
});
return false;
});

Setting a max-height property and overflow-y to auto doesn't solve the problem ?
#show_messages{
max-height:200px;
overflow-y:auto;
}
Let's say for example that a message is displayed within his proper div, you can scroll to the last message by using this function.
$("#show_messages").scrollTop($("#show_messages").children('div').last().offset().top);

I suggest to use AlternateScroll jquery plugin:
http://www.dynamicdrive.com/dynamicindex11/facescroll/
It's very useful and you can easily customize it. Hope this helps.

Related

Unable to get data from Wikipedia API

I am working on a 'Wikipedia Viewer' project, where you enter a search term and see a list of Wikipedia search results, but it is far from complete.
Until now I have just written the code to display the first search term. But it doesn't work.
My HTML:
<div class="container-fluid">
<div class="searchAndButtons">
<input type="text" id="search">
<button class="btn" id="searchBut">Search</button>
<form action="https://en.wikipedia.org/wiki/Special:Random"><button class="btn">Random Wiki Article</button>
</form>
</div>
<div class="searchResults">
</div>
</div>
My CSS:
.container-fluid{
padding:5%;
}
.searchAndButtons{
text-align:center;
}
My Javascript:
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("#search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Where am I going wrong? When I run the code in Codepen and check the console, it shows an error "TypeError: document.getElementById(...) is null".
My project on codepen - link
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Update your JS code with this. id gets value by 'search' not '#search'
UPDATE: To add headers you can do the following
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1', //your request URL
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo'); //your header key and value
}
});
});

jquery event (on submit) is affecting all my divs and not the only one where the button was clicked?

what's up guys? look... I have a comment system for my web page... and I've been dealing with this little problem for a entire week. I really need some help here x_x ... the thing is that when a user leave a comment on my page, this comment is showed automatically thanks to ajax, that's ok...
each comment can be voted. and here's my problem... these divs that contain the forms for voting are build dynamically and the thing is that when I do click on the button for sending the form in any comment... the resulting data appears in all the comments! instead of appear in the specific one where the submit button was clicked, so I don't know what to do at this point, I hope you can give me a hand. this is my code
the form:
<label > Vote </label>
<form action="vote.php" method="POST" class="form-vote" id="form-vote">
<button class="icon-thumbs-up" id="icon-thumbs-up"></button>
<input hidden="hidden" type="text" name="num-comment" id="num-comment" value="'.$d['id'].'" >
<input hidden="hidden" type="text" name="point" id="point" value="'.$d['point'].'" >
<p id="actual-points" class="actual-points"> '.$d['point'].'</p>
<div id="result" class="result"> </div>
</form>
the script:
<script type="text/javascript">
$(document).ready function() {
$('.form-vote')on('submit', function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('.actual-points').hide();
$('.result').html(data).fadeIn('slow');
}
})
return false;
});
})
</script>
Have you tried saving the 'this' object of the original event and using it inside the success function like this:
$('.form-vote')on('submit', function(e) {
e.preventDefault();
var $form = $(this); // Save here
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// use here
$form.find('.actual-points').hide();
$form.find('.result').html(data).fadeIn('slow');
}
})
return false;
});
change this:
$('.result').html(data).fadeIn('slow');
to this:
$(this).find('.result').html(data).fadeIn('slow');

JQuery sends empty values

I dont get it... I reviewed my code hundred times and I dont get the error...
I am actually testing a bit with JQuery and AJAX and made a simple form with a textarea to submit. Without AJAX it works fine, but with, it sends always an empty value of my textarea...
The Javascript Code:
$(document).ready(function(e) {
$("#formPost input").attr("disabled", false);
$("#formPost input:submit").click(function() {
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: $('#formPost').serialize(),
beforeSend: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", true);
$("#formPost .ajaxloader").show();
},
success: function(data) {
var message = $("#flashMessage");
message.text(data.msg);
if(data.error) {
message.addClass("fail");
}
else {
message.addClass("success");
}
message.show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#formPost .ajaxloader').hide();
$('#flashMessage').removeClass().
addClass('fail').text('There was an error.').show();
},
complete: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", false);
$("#formPost .ajaxloader").hide();
}
});
return false;
});
});
The HTML:
<div>
<h1>Add new post</h1>
<div id="flashMessage"></div>
<form id="formPost" method="post" action="post.php">
<textarea id="post" name="post"></textarea>
<input type="submit" value="Save" />
<div class="ajaxloader">
<img src="ajax-loader.gif" />
</div>
<div class="clear"></div>
</form>
</div>
I use Firebug and look under "Network" -> "XHR" -> "Post" and under Source he shows post=
So where is the value gone?
Your problem is related with CKEditor (as you said in the comment), because WYSIWYG editors replace the appearance of textarea and update value on form submit. So you have to use built-in functions of CKEditor for updating textarea's value manually as you are using Ajax. I can't help you specifically with CKEditor but this thread may help: CKEditor, AJAX Save .
You are disabling the form elements in the beforeSend method, but JQuery's serialize will ignore those disabled elements. Try removing that first to test. This SO question has some ways to get around it.

jQuery: While ajax request block element

So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after doubleĀ“s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.ajax.

using jquery to make ajax call and update element on form submit

Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});

Categories