For some reason, onreadystatechange call back function is not being called in asynchronous mode. I tested the post in synchronous mode and confirmed that post itself is working fine (commented out testing code I used to check post in synchronous mode). The problem occurs both in safari and firefox latest version. Can someone please tell me what I am doing wrong here? Thank you.
<html>
<head>
<script>
function recordScore(str)
{
if (str.length==0)
{
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="http://hellworld3.appspot.com/findcountry";
var params = "screenname="+document.getElementById("screenname1").value+"&score="+document.getElementById("score1").value;
alert("params: "+params);
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange = function()
{
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
if (xmlHttp.readyState==4)
{
document.getElementById("message").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHttp.send(params);
//Testing code for synchronous mode
//alert("Http get status is: "+xmlHttp.status);
//alert("Http ready state value is: "+xmlHttp.readyState);
//alert("Http get response text is: "+xmlHttp.responseText);
//document.getElementById("message").innerHTML=xmlHttp.responseText;
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
</head>
<body>
<form name="testform">
Screename:
<input type="text" id="screenname1" name="screenname">
<br/>
Score:
<input type="text" id="score1" name="score" onchange="recordScore(this.value)">
<br/>
<p id="message">test</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
you have an error in the onreadystatechange function:
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
xmlHttpreadyState should be xmlHttp.readyState
After I fixed that, it worked for me in FF3
Correct me if I'm wrong, but for POST don't you need to do a setRequestHeader for Content-Length like so;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader('Content-length',(params?params.length:0));
xmlHttp.send(params);
This might correct your problem.
Related
I am trying to get a live chat working using PHP and mysql and AJAX. It is almost completely functioning, except I cant seem to figure out how to submit the chat message without reloading a page. I have a page, sendchat.php, that takes input from the previous page and enters the data into a database. I am trying to use a text input field and when the user clicks the enter key, it would execute the PHP page with the details needed to send to sendchat.php without actually loading or refreshing the page. This is what I have so far:
<form id="send-message-area">
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeydown="onChatEnter(this);"></textarea>
</form>
</div>
</td></tr></table>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
function onChatEnter(str) {
if(event.key === 'Enter') {
$.ajax({
type: "GET",
url: "sendchat.php?msg=" + str ,
success : function() {
// here is the code that will run on client side after running clear.php on server
}
});
}
</script>
All it does is try to load the url, but its not trying to find sendchat.php or send the data. Instead it just tries to load a blank page. Where am I going wrong here? Everything seems spelled correctly and case sensitive. I check if the user pressed enter when they press a key. If they did, I am loading an AJAX function to execute a PHP page. Yet, it is not doing that. Just for FYI, I do not want a button there to be clicked.
EDIT:
I tried the suggestions below and still nothing. I decided to try a different approach now. Still doesn't work.
<script>
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","sendchat.php?msg="+str,true);
xmlhttp.send();
}
}
</script>
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeypress="updatechat(this.value);"></input>
Try this:
$("#send-message-area").submit(function(e) {
e.preventDefault();
e.stopPropagation();
});
I am not sure how.. But I fixed it.. I think it had to do with giving the input a name along with the ID. See below:
<script language="javascript" type="text/javascript">
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
var planetloc = document.getElementById("loc").value;
chaturl = "sendchat.php?msg="+str+"&loc="+planetloc;
sendie.value="";
xmlhttp.open("GET",chaturl,true);
xmlhttp.send();
}
}
//-->
</script>
This was the code I used for the html:
<p>Your message: </p>
<input type='text' id='sendie' name='sendie' maxlength = '100' onkeypress='updatechat(this.value);'></input>
<input type='hidden' id='loc' name='loc' value='$chatroom'></input>";
I also added chaturl to combine the ajax page I needed along with the parameters passed to it. It seemed by creating a variable for that it solved other issues too.
I am following my old question post that I suddenly enter in a new problem that is: my code is not entering in this line "xmlhttp.onreadystatechange=function()". I also checked by marking alert. so I unable to understand. can somebody tell me why this is not happening?
<html>
<head>
<script>
function changeThis(){
xmlHttp = new XMLHttpRequest();
var formInput = document.getElementById('theInput').value;
/* formInput will be undefined */
document.getElementById('newText').innerHTML = formInput;
/* also undefined */
// var xmlHttp = null;
xmlhttp.onreadystatechange=function() //help
{
alert("y"); // not entering help?????
if (xmlhttp.readystate==4 && http.status==200)
{
document.getElemenById('newText').innerHTML=xmlhttp.reponseText;
}
if(xmlhttp.status == 404)
{
var temp = "NO file found";
document.getElementById('newText').innerHTML=temp;
}
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
}
}
</script>
</head>
<body>
<p>You wrote: <span id='newText'></span> </p>
<textarea id="theInput" style="height:200px;">Write Here</textarea>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>
Move this:
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
outside of the onreadystatechange handler; your current code won't try to submit the HTTP request until after the HTTP request is already making progress. (Hat-tip to judder for editing your question to indent your code properly, making this problem obvious.)
Edited to add: Also, as Pavlo points out, you need to consistently write xmlHttp. JavaScript variable-names are case-sensitive, so xmlhttp is a completely different variable.
I'm trying to use Ajax to tell me whether my server is up or not. I've made a simple page with just one Ajax call. When the server is up, it comes back with the xmlhttp.responseText. IF the server is down it is supposed to say "SERVER DOWN"...but when I load the page, then turn off Apache, it still says that the server is up. Is there some other way I should be doing this?
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
var url = "http://192.168.0.5/ajax_info.txt";
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc(url,function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else
{
document.getElementById("myDiv").innerHTML = "Server Down!";
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
Thanks for the help
Your page is probably cached, use a cache buster in the url. e.g.
xmlhttp.open("GET",url+'?_dc='+(new Date()).getTime(),true);
I'm using php on a linux machine. My html code issues an ajax request to the local apache server (http://localhost), and the data from the server should be printed out on the screen. However, nothing gets printed.
The code on the "client" side (the html file which I load in the browser) is:
<html>
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if( ajaxRequest.readyState == 4 ){
document.writeln( ajaxRequest.responseText );
}
}
ajaxRequest.open("GET", "http://localhost/s.php", true);
ajaxRequest.send(null);
}
</script>
</body>
</html>
and the "server" script (which is /var/www/s.php) is:
<html>
<body>
<?php
echo date("H:i:s");
?>
</body>
</html>
Any suggestions?
TIA
You should debug your code
Check Apache access log that s.php was loaded
If it loaded then add debug alert function to onreadystatechange callback function
If this function is called then check what return code it received: alert(ajaxRequest.readyState);
If code is 4 then check what content it returned: alert(ajaxRequest.responseText);
There doesn't seem to be anything calling ajaxFunction when the page loads, so the request is never sent.
I'm trying to pass a variable to a javascript function, but I'm not sure what's going on as I am primarily a PHP person.
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction( str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("emailconfirm").innerHTML= ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "Atest.php?Email="+str, true);
ajaxRequest.send(null);
}
//-->
</script>
the form
<form name='myForm'>
<input name="email" id="email"type="text" />
<input name="button" onclick="ajaxFunction(document.getElementById('email').value" type="button" />
</form>
I wanna be able once the button get clicked, the email text input will be passed to the javascript function.
You're almost perfect, just a few things:
You missed a ) in your onclick event. Just add it to the end and it should work.
You don't need all that try..catch stuff, unless you need to support Internet Explorer 6, so you can just get rid of it and leave ajaxRequest = new XMLHttpRequest().