Click to See Complete Forum and Search --> : Ajax responseText problem...


daredevil14
02-28-2008, 05:06 PM
i am not getting the .responseText of the php file with ajax though the data are inserted successfuly into the db... here's the code...

<script type="text/javascript">
<!--

function GetXmlHttpObject()
{
var xmlHttp = null;
try
{
xmlHttp = new XmlHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

var xmlHttp;

function process()
{
var xmlHttp = GetXmlHttpObject();
if ( xmlHttp == null )
{
alert("Your Browser Does Not Support HTTP Requests");
}
var name = document.getElementById("name").value;
if ( name.length == 0 )
{
alert("Missing Name!!");
document.getElementById("name").focus();
return;
}
var comment = document.getElementById("comment").value;
if ( comment.length == 0 )
{
alert("Missing Comment!!");
document.getElementById("comment").focus();
return;
}
var url = "insert_body.php";
var qs = "name=" + escape(name) + "&comment=" + escape(comment);
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange = statechanged;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlHttp.send(qs);
}

function statechanged()
{
if ( xmlHttp.readyState == 4 || xmlHttp.readyState == "complete" )
{
document.getElementById("res").innerHTML = xmlHttp.responseText;
}
}

//-->
</script>

<form>
Name : <input type="text" name="name" id="name" /><p></p>
Comment : <br /><textarea rows="5" cols="15" name="comment" id="comment"></textarea>
<p><input type="button" onclick="process()" name="insert" id="insert" value="Insert" /></p>
</form>

<div id="res"></div>

and now insert_body.php :

<?php

$conn = mysql_connect("localhost","root","");
if (!$conn)
{
die("Could Not Connect To The Database Server : " . mysql_error());
}

mysql_select_db("ajax", $conn);

$name = htmlentities(mysql_real_escape_string($_POST["name"]));
$comment = htmlentities(mysql_real_escape_string($_POST["comment"]));

$sql = "INSERT INTO gb (name,comment) VALUES ('$name','$comment')";

if ( mysql_query($sql, $conn) )
{
echo "Posted!!";
}
else
{
echo "Error : ". mysql_error();
}

mysql_close($conn);

?>

why am i getting a javascript error, i mean why .responseText is not working ?

Kudose
02-28-2008, 08:47 PM
.-

daredevil14
02-29-2008, 03:13 AM
what .- ???

sophistikat
02-29-2008, 03:27 PM
Hi daredevil14,
I have been trying to do something every similar to yours and while debugging, I had found another post of yours (adding xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8")) but from this thread, I read that yours is writing to the database... mine won't!! Can you see something in my code?

The JavaScript
<script type="text/javascript">
<!--
function addUser()
{
<!-- debugger; -->
var email = document.getElementById("myemail").value;
var pass = document.getElementById("mypassword").value;
var alias = document.getElementById("myalias").value;

if (email.length == 0) { alert("Form field 'Electronic Mail' is blank"); return; }
if (pass.length == 0) { alert("Form field 'Login Passowrd' is blank"); return; }
if (alias.length == 0) { alert("Form field 'Alias' is blank"); return; }

var xmlHttp;
try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } };

xmlHttp.onreadystatechange=function()
{
switch (xmlHttp.readyState)
{
<!-- The request is not initialized -->
case 0:
alert("request error");
break;
<!-- The request has been set up -->
case 1:
alert("request is set");
break;
<!-- The request has been sent -->
case 2:
alert("request was sent");
break;
<!-- The request is in process -->
case 3:
alert("request is in progress");
break;
case 4:
alert("xmlHttp.responseText: " + xmlHttp.responseText);
switch (xmlHttp.responseText)
{
case true:
<!-- username/password was incorrect -->
alert("username/password was incorrect");
break;
case false:
<!-- username/password was correct -->
alert("username/password was correct");
break;
}
break;
}
}

var query = "myemail=" + escape(email) + "&mypassword=" + escape(pass) + "&myalias=" + escape(alias);
xmlHttp.open("POST","addUser.php",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
alert("send: " + query);
xmlHttp.send(query);
}
-->
</script>

The Form

<div id="page">
<div id="addList"></div>
<div id="addUser">
<h1>Add User</h1><br />
<form>
<p><span class="formLeft">Electronic Mail</span><input id="myemail" type="text"></p>
<p><span class="formLeft">Login Password</span><input id="mypassword" type="text"></p>
<p><span class="formLeft">Alias</span><input id="myalias" type="text"></p>
<p><br/><span class="formLeft">&nbsp;</span><input type="submit" value="Add Me!" onclick="addUser()"></p>
</form>
</div>
</div>
I am running this locally so my PHP looks like<?php

# dBNames
$db_name="MylesAlexander";
$db_table="db_users";

# connection to db
$link = mysql_connect("localhost", "root", "root");
mysql_select_db($db_name, $link);


# GET/SET users post login info
$email=htmlentities(mysql_real_escape_string($_POST['myemail']);
$password=htmlentities(mysql_real_escape_string($_POST['mypassword']);
$alias=htmlentities(mysql_real_escape_string($_POST['myalias']);


# Get Tables Data
$query = "INSERT INTO '$db_table' (users_ID,users_login,users_pass,users_alias,users_registered) VALUES (NULL, '$email', '$password', '$alias', NOW())";
if (mysql_query($query, $link))
{
echo "Success";
}
else
{
echo "Error";
}

mysql_close($link);
?>The alert let me know that the fields value are been sent properly but once the page reloads, there was nothing added to the database and and xmlHttp.responseText is blank?

Thanks for any help.

edit: updated PHP code; still same results

daredevil14
02-29-2008, 04:39 PM
try this...

instead of this :

<input type="submit" value="Add Me!" onclick="addUser()">

try :

<input type="button" value="Add Me!" onclick="addUser()" />

sophistikat
02-29-2008, 05:05 PM
that actually fixed the refresh issue i was having (did not mention) but still not writing to the database. i am using FireBug to inspect the code and its posting the correct variables and values but in the Response tab, it stays on Loading...

I don't have to setup anything permissions for PHP to write to MySQL do it?

daredevil14
02-29-2008, 05:36 PM
ok do you see these :

$email=htmlentities(mysql_real_escape_string($_POST['myemail']);
$password=htmlentities(mysql_real_escape_string($_POST['mypassword']);
$alias=htmlentities(mysql_real_escape_string($_POST['myalias']);

you forgot to close each htmlentities() second bracket...

change it to this :

$email=htmlentities(mysql_real_escape_string($_POST['myemail']));
$password=htmlentities(mysql_real_escape_string($_POST['mypassword']));
$alias=htmlentities(mysql_real_escape_string($_POST['myalias']));

now i guess it'll work, but the responseText will stay empty; that's actually my problem...

rulian
02-29-2008, 05:49 PM
your responseText returns only string information, it does not return objects or boolean values. Therefore although responseText can be "true" (the string) it cant be if (responseText == true) because true is a boolean (meaning predetermined value embedded in js)

Take this a step at a time, first confirm your request is sending.
in your php file simply echo out "hello world" and see if your
code:
alert("xmlHttp.responseText: " + xmlHttp.responseText);
echos out "hello world"

if it does your request is going through
at that point you just have to check your php.
To start off you PHP does not return the values that your javascript is expecting, your javascript is expecting true or false and yoru php returns success or error .

A INSERT statement will return true or false, and error codes depending on arguments you have set up in your tables like unique id's

so it doesnt return rows, i dont know how you are expecting to have "incorrect username/password" if it doesnt compare to something. You can have "username in use" errors.

and yes your connection to mysql should have read/write permissions in order to proccess an insert

daredevil14
02-29-2008, 05:59 PM
ok finally it worked with me... i am getting the xmlHttp.responseText result from the php script... by doing this :

// ...
xmlHttp.onreadystatechange = function statechanged()
{
if ( xmlHttp.readyState == 4 || xmlHttp.readyState == "complete" )
{
document.getElementById("res").innerHTML = xmlHttp.responseText;
}
}
// ...

instead of this :

// ...
xmlHttp.onreadystatechange = statechanged;
// ...
function statechanged()
{
if ( xmlHttp.readyState == 4 || xmlHttp.readyState == "complete" )
{
document.getElementById("res").innerHTML = xmlHttp.responseText;
}
// ...
}

sophistikat
02-29-2008, 10:52 PM
Its good news all around, I got mine working as well. I used FireBug to help me debug the all my previous errors.

JavaScript
<script type="text/javascript">
<!--
function addUser()
{
/* debugger; */
var email = document.getElementById("myemail").value;
var pass = document.getElementById("mypassword").value;
var alias = document.getElementById("myalias").value;

if (email.length == 0) { alert("Form field 'Electronic Mail' is blank"); return; }
if (pass.length == 0) { alert("Form field 'Login Passowrd' is blank"); return; }
if (alias.length == 0) { alert("Form field 'Alias' is blank"); return; }

var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
};

xmlHttp.onreadystatechange=function()
{
switch (xmlHttp.readyState)
{
case 0:
<!-- The request is not initialized -->
break;

case 1:
<!-- The request has been set up -->
break;

case 2:
<!-- The request has been sent -->
document.getElementById("addme").visible = false;
break;

case 3:
<!-- The request is in process -->
break;
case 4:
switch (xmlHttp.responseText)
{
case "Success":
getList();
break;
case "Error":
showError();
break;
}
break;
}
}

// write post query
var query = "myemail=" + escape(email) + "&mypassword=" + escape(pass) + "&myalias=" + escape(alias);

// execute query
xmlHttp.open("POST","addUser.php",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlHttp.send(query);
}
</script>
HTML
<div id="page">
<div id="addList"></div>
<div id="addUser">
<h1>Add User</h1>
<span id="addSuccessMessage" class="red" />
<span id="addErrorMessage" class="red" />
<span id="addExistMessage" class="red" />
<span id="addDataMessage" class="red" />
<br />
<form method="post">
<p><span class="formLeft">Electronic Mail</span><input id="myemail" name="myemail" type="text" /></p>
<p><span class="formLeft">Login Password</span><input id="mypassword" name="mypassword" type="text" /></p>
<p><span class="formLeft">Alias</span><input id="myalias" name="myalias" type="text" /></p>
<p><br/><span class="formLeft">&nbsp;</span><input id="addme" type="button" value="Add Me!" onclick="addUser()" /></p>
</form>
</div>
</div>

<!-- auto-fill form -->
<script language="javascript">
document.getElementById("myemail").value = "marlon@actionscriptblog.net";
document.getElementById("mypassword").value = "1234";
document.getElementById("myalias").value = "Dad";
</script>

PHP
<?php
# connection to db
$sqlConnect = mysql_connect("localhost", "root", "root");
mysql_select_db("MylesAlexander", $sqlConnect);

# check for data
if (!empty($_POST["myemail"]) && !empty($_POST["mypassword"]) && !empty($_POST["myalias"]))
{

# GET/SET data
$email = $_POST["myemail"];
$password = $_POST["mypassword"];
$alias = $_POST["myalias"];

//TODO: check if user already exists

# Get Tables Data
$query = "INSERT INTO db_users VALUES (NULL, '{$email}', '{$password}', '{$alias}', NOW())";
if (mysql_query($query, $sqlConnect))
{
echo "Success";
return;
}
else
{
echo "Error: " + mysql_error($sqlConnect);
}
}
else
{
echo "Error: Missing Data";
}

# close connection to db
mysql_close($sqlConnect);
?>