AJAX load animation for chat? - javascript

How do I add the slideDown jquery animation when I knew message is loaded? Perhaps I can't with my method for loading... A file takes user input and inserts into database. Another file pulls from database onto chatbox and styles.
Javascript Code:
var form = document.querySelector('form[name="chatbox"]');
form.addEventListener("submit", function (event) {
event.preventDefault();
});
function submitChat() {
if(chatbox.message.value == '') {
alert('Error: Missing Fields.');
return;
}
var message = chatbox.message.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4&&xmlhttp.status==100) {
document.getElementById('chatlog').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','chat.php?message='+message, true);
xmlhttp.send();
chatbox.reset();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlog').load('logs.php');}, 200);
});
Please let me know if you need the PHP attached.. Thanks for the help! :)

Related

Javascript data getting sent letter by letter instead of complete word in search

Trying to access yahoo weather api using ajax and jquery. Works fine if searched and submitted using submit button but i wish to search it using enter keypress only. It takes one letter at a time instead of the complete search term.
function makeAjaxCall(url, methodType,callback){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
console.log("xhr done successfully");
var resp = xhr.responseText;
var respJson = JSON.parse(resp);
callback(respJson);
} else {
console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
}
function processUserDetailsResponse(userData){ //Callback function
console.log(userData.query.results.channel.astronomy);
}
$('#inpt_search').keypress(function(e){
if(e === 'Enter'){
var city = $("#sunrise").value;
console.log(city);
e.preventDefault();
}
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20astronomy%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+ city +'%2C%20%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
makeAjaxCall(url, "GET", processUserDetailsResponse); enter code here //calling api using ajax
});
As I understand you need to make the ajax call and update once Enter is pressed. Try the following code, it only calls the API when enter is pressed.
$('#inpt_search').keypress(function(e){
if(e.which === 13){
var city = $("#sunrise").value;
e.preventDefault();
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20astronomy%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+ city +'%2C%20%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
makeAjaxCall(url, "GET", processUserDetailsResponse);
}
});
I would not use the "keypress" event since it's not intended for non printable characters, and you can't prevent its default behaviour without freezing the entire field. Rather use "keyup". Here is a possible solution (replace the submit function with whatever suits your needs) :
$("input").focus().on("keyup", function (ev) {
ev.preventDefault();
// if key is ENTER
if (ev.which === 13) {
submit($(this).val());
}
});
function submit (val) {
$("p").text(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input></input> <span>Press <kbd>ENTER</kbd> when you're done.</span>
<p style="border:1px solid black;padding:1em"></p>
As an alternative, you could submit along the way when the user stops writing for a given delay :
$("input").focus().on("keyup", debounce(250, function (ev) {
ev.preventDefault();
submit($(this).val());
}));
function submit (val) {
$("p").text(val);
}
function debounce (ms, f) {
var tid = null;
return function () {
var subject = this;
var args = arguments;
if (tid) clearTimeout(tid);
tid = setTimeout(function () {
tid = null;
f.apply(subject, args);
}, ms);
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input></input> <span>No need to press <kbd>ENTER</kbd>.</span>
<p style="border:1px solid black;padding:1em"></p>

Using AJAX to change div content - how do I display navigation as hash / anchor

I want to create a page that refreshes content within a div async alongside providing a user with an anchor to enable direct access to the content within the div. (e.g. www.website.co.uk/#page1)
I've managed to make it so that the content can be updated for 1 page, however, if I add multiple pages it stops working
Additionally - if I was to navigate to the URL website.co.uk/#page1 it wont display #page1.
Can anyone help?
This is my current code:
HTML :
<h5> Test</h5>
<h5> Test2</h5>
JS :
<script type="text/javascript">
var routes = {
'#page1' : '{{site.url}}/page1'
'#page2' : '{{site.url}}/page2'
};
var routeHandler = function( event ) {
var hash = window.location.hash,
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
</script>
You made some small js errors.
So here is you fixed code
html:
<h5> Test</h5>
<h5> Test2</h5>
<div id="div1"></div>
javascript:
//change these routs
var routes = {
'#page1': '/page1.html',
'#page2': '/page2.html'
};
var routeHandler = function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[window.location.hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(window.location.hash)) routeHandler();
});
You usually use a router-like object for this. Instead of the hyperlink you're using, set the href to the actual page hash Button Title. Then create an event listener for the hashchange on the window object where you will fetch the content.
And finally add a list of webpages you want to be able to navigate to, so you can translate '#page1' to the actual url.
The result is that you can use simple hrefs in your hyperlinks and the current page will be shown in the url bar at the top.
ps: add a check into the hashchange listener for routes that aren't listed, so you can still link to offsite pages as well.
pps: If you want to be able to directly navigate to a page, you'll need to add a manual check of the hash at document load.
// html mockup
Button Title
// js mockup
var routes = {
'#page1' : '{{site.url}}/webpage.html'
};
window.addEventListener('hashchange', function( event ) {
var hash = window.location.hash, // gives you '#page1'
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
});
Updated with a load listener:
// html mockup
Button Title
// js mockup
var routes = {
'#page1' : '{{site.url}}/webpage.html'
};
var routeHandler = function( event ) {
var hash = window.location.hash, // gives you '#page1'
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
since you have tagged the question with jquery, iassume you have jQuery available, in this case you could do something like:
$(window).on('hashchange', refreshContent);
function refreshContent() {
$.get(getBaseUrl() + location.hash, function(data) {
$('#div1').html(data);
});
}
But please be aware that there are a lot more sophisticated solutions out there
I given directly on onclick its working. It may help you.
<h5> Test</h5>
<h5> Test2</h5>
<div id="div1"></div>
<script type="text/javascript">
var routes = {
'#page1' : 'page1.html',
'#page2' : 'page2.html'
};
function test(page) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[page], true);
xhttp.send();
}
</script>
I used .html for pages for check. You use your own.

Timing on GET info from PHP/SQL

Just for you to know I'm less than a newbie!
I have the following javascript code:
window.onload = function() {
renderTime();
getsec(myHandler);
countdown('countdown');
...
}
function myHandler(resultado) {
seconds = resultado;
}
function reqListener () {
console.log(this.responseText);
}
function getsec(callback) {
var indice = 1;
var oReq = new XMLHttpRequest();
oReq.onload = function() {
var variarr = JSON.parse(this.responseText);
callback(variarr[0]);
};
oReq.open("GET", "getsec.php?lei="+indice, true);
oReq.send();
}
This works perfectly for me. The intention is to get data from MySQL table through getsec.php every second. As you can see I have function countdown('countdown') that looks like this:
function countdown(element) {
...
interval = setInterval(function() {
...
if( runned == false){ // This condition happens
...
} else {
...
}
}, 1000);
}
I tryed to put function getsec(myHandler) inside function countdown('countdown')
if( runned == false){ // This condition happens
getsec(myHandler);
and I stop getting the information I want.
Can anyone explain me why?

AJAX function parameter is null?

i got a problem with JS:
On line 1 to 4 I take all "a"-Elements from the DOM and get their hrefs.
later I want to reload the URL via AJAX, but the href does not arrive correctly... Whats wrong?
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
function ajaxReload(href) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", href, true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState != 4) {
document.write('loading');
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('hello');
//alert('getting '+xmlhttp.status+' for '+href);
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
var writeContent = document.getElementById('content');
writeContent.innerHTML = ajaxContent;
}
}
xmlhttp.send(null);
}
Sorry if I've misunderstood your code. I think that you simply need to (at least approximately) just remove code as commented below:
//$('a').click = function(href) {
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
$("content").html(ajaxContent);
// ajaxReload(href); //this would cause a loop?
// return false;
//}
To answer your later question - you can change your event propagation handling to:
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
And for the further comments, maybe try changing your:
document.write('loading');
To:
$("content").html(xmlhttp.status); //so now you can see the loading status for testing

"Object doesn't support..." IE8 stops at declaring ordinary variable

I'm trying to make a form send its data through AJAX and cancel the event sans jQuery, just for learning native JavaScript, which can never be bad, I figured. Anyway, this code is returning the error:
"Object doesn't support this property or method"
in IE8 at the line where I declare variables s and r in the send() function. I figured the problem must actually be elsewhere? Code works in both Firefox and Chrome, returning no errors. Ideas?
// Function to serialize form
function serialize() {
var a = document.getElementsByTagName('input'), b = '';
for (i = 0; i < a.length; i++) {
b += a[i].name + '=' + a[i].value + '&';
}
return b.substring(0, b.length - 1);
}
// Function to execute when user submits form
function send(evt) {
// Prevent the page from reloading
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
// Declare DOM variables for quick access
var s = document.getElementsByClassName('skicka')[0], r = document.getElementById('return');
// Hides the submit button and return text
s.style.visibility = 'hidden';
r.style.visibility = 'hidden';
// Initialize and send data and request to login.php
var xhr = new XMLHttpRequest();
xhr.open('POST', 'login.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(serialize());
// Check for return value from login.php
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.responseText == true) {
// If response if true, reload page
window.location.reload(true);
} else {
// If response is false, reset form and show response
s.style.visibility = 'visible';
r.style.visibility = 'visible';
r.innerHTML = xhr.responseText;
}
}
};
return false;
}
// Declare event listeners
if (window.addEventListener) {
window.addEventListener('load', function() {
document.forms[0].addEventListener('submit', send, false);
}, false);
} else {
window.attachEvent('onload', function() {
document.forms[0].attachEvent('onsubmit', function() {
send(window.event);
});
});
}
IE8 does not support .getElementsByClassName(). See the Ultimate GetElementsByClassName for a pure JavaScript implementation that will work in IE.

Categories