I am writing code to make a basic chatroom. The code I have takes lines entered into the input textbox, then uses Ajax to write to a random filename, then I have javascript loop every second using setInterval to load and display from the text file.
After the user logs in with information that populates a MySQL database I want to have a basic welcoming message automatically saved to the text file upon entering the chat. I do this by calling my saveData function with username as 'Host' and then the welcoming message which is declared in a variable.
The function that sends the login information to the database and the function that saves the welcoming message are both called under the login() function. The login() function is called after submitting the info form.
Here is the problem: I cannot get the functions, saveLogin() and saveData(), to BOTH fully execute when called under login(). If I comment one out and NOT the other, the function will work fine. So they work independently, but not together. If both functions are called then saveData() works fine, but saveLogin() will not. I have no idea why.
I was able to narrow the problem down to the 'XMLHttpRequestObject.send' event under the saveLogin() function. The rest of that function appears to be executed. I thought maybe it was a problem with the variable names or something, so I tried some variations, but nothing has resolved the issue.
<script language = "javascript">
// loads XML HTTP per browser type
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
//create random string
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
rString = randomString(128);
filename = rString;
// loads chat lines from file using POST method with timer
function getData(geturl)
{
if(XMLHttpRequestObject) {
geturl = "getdata.php";
XMLHttpRequestObject.open("POST", geturl);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
document.formChat2.textarea1.value = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send("filename=" + filename);
}
}
// saves new chat line to file
function saveData(filename, username, newline)
{
if(XMLHttpRequestObject && document.formChat1.txtLine.value != "" || username == "Host") {
var url = "savedata.php";
XMLHttpRequestObject.open("POST", url);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
}
}
XMLHttpRequestObject.send("filename=" + filename + "&username=" + username + "&newline=" + newline);
document.formChat1.btnDisplay.click();
document.formChat1.txtLine.value = "";
}
}
// saves login info to database
function saveLogin(filename, username, email, phone, weburl)
{
if(XMLHttpRequestObject) {
var loginurl = "login.php";
XMLHttpRequestObject.open("POST", loginurl);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
}
}
XMLHttpRequestObject.send("filename=" + filename + "&username=" + username + "&email=" + email + "&phone=" + phone + "&weburl=" + weburl);
}
}
function login(divID) {
username = document.formLogin.txtLogin.value;
email = document.formLogin.txtEmail.value;
phone = document.formLogin.txtPhone.value;
weburl = document.formLogin.txtURL.value;
saveLogin(filename, username, email, phone, weburl);
var obj = document.getElementById(divID);
obj.innerHTML = "<div id='targetDiv'><form name='formChat1' method='POST' onSubmit='return false;'><input type='text' name='txtLine' id='txtLine' size='30'><input type='button' name='btnDisplay' value='Display Message' onclick=\"setInterval('getData(filename)', 1000);\"><input type='button' name='btnSave' value='Send Message' onclick='saveData(filename, username, txtLine.value)'></form><form name='formChat2'><textarea name='textarea1' id='textarea1' rows='10' cols='50'></textarea></form></div>";
welcome = "Welcome to the chat.";
saveData(filename, 'Host', welcome);
}
</script>
<div id="targetDiv">
<form name="formLogin" method="POST">
Please enter your info:<br>
<input type="text" name="txtLogin" id="txtLogin" size="50" value="Name (Required)" onfocus="document.formLogin.txtLogin.value=''"><br>
<input type="text" name="txtEmail" id="txtEmail" size="50" value="Email Address (Required)" onfocus="document.formLogin.txtEmail.value=''"><br>
<input type="text" name="txtPhone" id="txtPhone" size="50" value="Phone Number (Optional)" onfocus="document.formLogin.txtPhone.value=''"><br>
<input type="text" name="txtURL" id="txtURL" size="50" value="Website URL (Optional)" onfocus="document.formLogin.txtURL.value=''"><br>
<input type="button" name="btnLogin" value="Login"
onclick="login('targetDiv');">
</form>
</div>
You need to use different XHR objects, so that you can get both responses, since you're sending both AJAX requests at the same time.
Write a function like:
function getXHR() {
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
return XMLHttpRequestObject;
}
Then call it in each of the functions that performs AJAX requests, with:
var XHRObject = getXHR();
and use that within the function.
Related
I have a website, and all its files (html/js/css/php) are on the same remote host. I have a button on the site, when clicked it sends a httprequest to a PHP file, waiting for a response.
My site works perfect almost everywhere, but there is one place which when I connect to the wi-fi, when clicking the button it return whit the error ERR_EMPTY_RESPONSE. Other buttons and PHP files work. It is only this specific button and in this specific wi-fi.
Does anyone know why does it happen and how to fix it?
details:
the button is <button class="btn btn-default col-sm-5" type="submit">
the onClick function:
function search() {
var param = "";
var firstParam = true;
var form = document.getElementById("formCS");
var name = document.getElementById("songName").value.trim();
if (name != "") {
firstParam = false;
param += "name=" + name;
}
var creator = document.getElementById("creator").value.trim();
if (creator != "") {
if (firstParam) {
param += "creator=" + creator;
firstParam = false;
} else {
param += "&creator=" + creator;
}
}
var type;
if (document.getElementById("partners").checked) {
type = "partners";
} else if (document.getElementById("circle").checked) {
type = "circle";
} else if (document.getElementById("lines").checked) {
type = "lines";
} else if (document.getElementById("none").checked) {
type = "";
}
if (type != "") {
if (firstParam) {
param += "type=" + type;
firstParam = false;
} else {
param += "&type=" + type;
}
}
var year = document.getElementById("year").value;
if (year != "none") {
if (firstParam) {
param += "year=" + year;
} else {
param += "&year=" + year;
}
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
handleResponse(xhttp.response);
}
};
xhttp.open("GET", "search.php?" + param, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
the search.php file connects to a DB on the remote host and runs a sql query. nothing different from other buttons on the site.
the wi-fi is a free wi-fi provided by an academic institue.
after clicking the button there is an error in the console:
GET http://rikudim.info/search.php? net::ERR_EMPTY_REPONSE
Hi I am creating a wordpress plugin and i am a little bit stack here. there's text box number 1 which is the order number and number 2 which is the order name. This is what i want. If the customer enters a number in textbox number 1 which is order number, the value he or she entered will check into the database and get the corresponding order name of that order number. Its realtime. No need to submit before it appears. Everytime they input something it will immediate check to the database and display it in text box number 2(order name). I research this and try using ajax in wordpress but i dont know how to use. Thanks.
Here's some boilerplate code to get you started....
<script type="text/javascript" charset="utf-8">
var req;
function handler_orderNumberField_onchange(fld) {
var text = fld.value;
if (text.length == 8) {
queryForOrderName(text);
}
}
function queryForOrderName(orderNumber) {
document.getElementById('orderNameField').value = "Please wait..."
req = new XMLHttpRequest();
var url = "http://www.mydomain.com/getordername.php?ordernumber=" + orderNumber;
req.onreadystatechange = function() {
var field = document.getElementById('orderNameField');
var rs = this.readyState;
var status = this.status;
if (rs == 4 && status == 200) {
field.value = req.responseText;
}
};
req.ontimeout = function() {
document.getElementById('orderNameField').value = 'Timeout.';
}
req.timeout = 10000;
req.open("GET", url, true);
req.send();
}
</script>
<p>Order Number: <input type="text" name="orderNumber" value="" id="orderNumberField" onchange="handler_orderNumberField_onchange(this)"></p>
<p>Order Name: <input type="text" name="orderName" value="" id="orderNameField"></p>
Note that you need to implement a getordername.php script yourself; example:
<?php
$ordernr = (int) $_GET["ordernumber"];
$result = sprintf("Testorder - Order Number %d", $ordernr);
header("Content-type: text/plain; charset=UTF-8");
echo $result;
exit;
?>
I have build an instant search with AJAX, It is like when you start typing result appears, then if you click anywhere on the body result disappear, onmouse over at input field result re appear. when clicked inside input field result disappers.
I want this result to stays open after onmouse event when clicked in input field. for that i have added a click event, but it is not working.
Please see the codes and suggest any possible way to do this.
<script type="text/javascript">
function showResult(str) {
if (str.length == 0) {
document.getElementById("search-result").innerHTML = "";
document.getElementById("search-result").style.border = "0px";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("search-result").innerHTML = xmlhttp.responseText;
document.getElementById("search-result").style.border = "1px solid #A5ACB2";
document.getElementById("search-result").style.display = "block";
document.getElementById("search-input").onmouseover = function() {
show_box()
};
document.getElementById("search-input").onclick = function() {
show_box()
};
}
}
xmlhttp.open("GET", "instant-search.php?keyword=" + str, true);
xmlhttp.send();
}
function close_box() {
fadeOut();
document.getElementById("search-result").style.display = "none";
}
function show_box() {
setOpacity(0);
document.getElementById("search-result").style.display = "block";
fadeIn();
}
document.onclick = function() {
close_box()
};
function setOpacity(value) {
document.getElementById("search-result").style.opacity = value / 10;
document.getElementById("search-result").style.filter = 'alpha(opacity=' + value * 10 + ')';
}
function fadeIn() {
for (var i = 20; i <= 100; i++)
setTimeout('setOpacity(' + (i / 5) + ')', 5 * i);
}
function fadeOut() {
for (var i = 20; i <= 100; i++)
setTimeout('setOpacity(' + (5 - i / 5) + ')', 5 * i);
}
</script>
HTML Code
<input name="keyword" type="text" size="50" id="search-input" onkeydown="showResult(this.value)" autocomplete="off" />
<div id="search-result"></div>
I'm so into jQuery that I forgot there is a difference on IE.
if(!e) {
e = window.event;
}
if(e.stopPropagation && e.preventDefault) {
e.stopPropagation();
e.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
try this?
<input name="keyword" type="text" size="50" id="search-input" onclick="showResult(this.value)" autocomplete="off" />
or to test if onclick works
<input name="keyword" type="text" size="50" id="search-input" onclick="alert('replace this with your function you want to call');" autocomplete="off" />
I'm new to jQuery and have tried looking around for an answer on how to do this. I have 2 functions and I would like both to work together. The one function is submitHandler and its used to hide a form and at the same time add a class to a hidden element to unhide it - ie a thank you for submitting h1. The other function is to grab the input data and display it onsubmit in the form. So the problem is that I can get that one to work but then the other doesnt. Ie on form submit I can see the data input but not the h1 Thank you message.
Here are the functions:
SubmitHandler:
submitHandler: function() {
$("#content").empty();
$("#content").append(
"<p>If you want to be kept in the loop...</p>" +
"<p>Or you can contact...</p>"
);
$('h1.success_').removeClass('success_').addClass('success_form');
$('#contactform').hide();
},
onsubmit="return inputdata()"
function inputdata(){
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
return true;
},
The form uses PHP and jQuery - I dont know about AJAX but after some reading even less sure. Please help me out I dont know what I'm doing and at the moment I am learning but its a long road for me still.
Thank you
The form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform" onsubmit="return inputdata()">
<div class="_required"><p class="label_left">Name*</p><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><p class="label_left">E-mail address*</p><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<p class="label_left">Message</p><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<input type="submit" value="submit" name="submit" id="submit" />
</form>
The PHP bit:
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The Jquery Validate bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
Here is the full jQuery bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
});
});
Latest edit - Looks like this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
function submitHandler() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
function inputdata() {
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
},
$(document).ready(function(){
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
});
});
I know this question has already been answered and this isn't directly regarding the question itself; more so regarding the code in the question. However, I can't post comments as I'm a brand new member, but I just thought I'd highlight a few things in your code! Mainly consistency regarding the use of jQuery.
In the function supplied for 'submitHandler' - you empty $('#content') and then append HTML to it. This will work, but an easier method would be using the .html() function; note that this function can be used to return the HTML contained inside an element; but that's when no arguments are supplied. When you supply an argument, it re-writes the content of the html element. Additionally, I would most likely use the .show() method on the h1 success element; if only for code readability.
For example:
submitHandler: function(){
$('#content').html( "<p>If you want to be kept in the loop...</p>"
+ "<p>Or you can contact...</p>");
$('h1.success_').show();
$('contactform').hide();
}
As for inputdata() - you seem to have strayed off of the jQuery ethos here a little again, I'd aim for consistency when using jQuery personally - but also as the jQuery syntax makes the traditional javascript 'document.getElemen...' object look a bit outdated/it's extra to type. At its most basic jQuery is essentially best viewed as a wrapper for the document object - just with added syntactical sugar. Additionally, it allows you to chain methods - so the last two expressions can essentially be "dressed up" to look as one when using jQuery.
I'd personally use .val(), .html() and .css() functions; example:
function inputdata(){
var usr = $('#contactname').val();
var eml = $('#email').val();
var msg = $('#message').val();
$('#out').html( usr + " " + eml + msg )
.css('display', 'block');
return true;
}
Your submitHandler function isn't called. That's why it doesn't work.
Add this to your code:
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
EDIT:
try this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
CHange return true, to return false in the inputdata function
I've the following input text box and a button.
<div id="sender" onKeyUp="keypressed(event);">
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>
The keypressed(event) function actually detects if the key being pressed is "Enter" and calls the doWork() function.
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
This code seems to work fine in Chrome & Firefox. But in IE, the function seems to called twice.
Can anyone help me tweak the code so that it works properly in IE also.
Thanks
EDITED:
Whole ajax codes
<!--
var httpObject = null;
var link = "";
var timerID = 0;
var nickName = "Unname"; //"<?php echo $nickname; ?>";
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML += response;
objDiv.scrollTop = objDiv.scrollHeight;
var inpObj = document.getElementById("msg");
inpObj.value = "";
inpObj.focus();
}
}
// Change the value of the outputText field
function setAll(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML = response;
objDiv.scrollTop = objDiv.scrollHeight;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
link = "message.php?nick="+nickName+"&msg="+encodeURIComponent(document.getElementById('msg').value);
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);
}
}
// Implement business logic
function doReload(){
httpObject = getHTTPObject();
var randomnumber=Math.floor(Math.random()*10000);
if (httpObject != null) {
link = "message.php?all=1&rnd="+randomnumber;
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setAll;
httpObject.send(null);
}
}
function UpdateTimer() {
doReload();
timerID = setTimeout("UpdateTimer()", 5000);
}
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
//-->
If someone is facing a similar problem, this could be useful.
I solved the problem by detecting IE browser using PHP script and discarding the onKeyUp() function while rendering HTML for IE.
IE Detection PHP script
//Detect IE function
function detectIE() {
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
return true;
else
return false;
}
And this is how i changed the event handling.
<div id="sender" <?php if (detectIE()) { /*do nothing */ } else { echo "onKeyUp=\"keypressed(event);\""; } ?> >
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>