I don't know anything about javascript, but I volunteered to help with a community website and I needed a form to gather names for a petition.
At first I used straight php to write a file on my server to hold the names, that was ok, but I had to return a meta-redirect to get back to the page the form was on, -ugly-.
I got it to work as far as writing the file on the server and returning without any page refresh, but it errors out on getting the response into an innerHTML div back on the form-page, just won't do it and I don't know enough about javascript to figure out what's wrong. I have the response part shut down right now to hide the alert, but it would be good to know 'why' it's not working as intended (since this is a learning process for me).
It acts like it can't find the div ID, but I couldn't get a string to show from statusText, so I'm pretty much stuck.
Here's the entire code, form, php and css that make up the form-test, all this gets included in the main page if it tests out. I figured there might be a conflict of some sort (DOM, etc.) outside of the ajax code so I posted the whole thing. I've put some comments in the relavent parts of the HTML, the php and css are OK, just posted them in case anybody wants to try it out 'in situ' to reproduce the error:
Code:
/////////////////ajax-test.php//////////////////
<?php
$name=$_POST['fm-name'];
$town=$_POST['fm-town'];
$fname="ajax-test.dat";
$line =sprintf("%-20s %s\n",$name,$town);
$fp=fopen($fname, "a");
fwrite($fp,$line);
fclose($fp);
//see if ajax handles the response
echo "Thanks";
exit;
?>
///////////////// the form's css //////////////////
form{
margin:0;
padding:0;
}
fieldset{
margin:1em 0;
border:none;
//border-top:1px solid #ccc;
}
legend{
margin:1em 0;
padding:0 .5em;
color:#036;
background:transparent;
font-size:1.3em;
font-weight:bold;
}
label{
float:left;
width:100px;
padding:0 1em;
text-align:right;
}
fieldset div{
margin-bottom:.5em;
padding:0;
display:block;
}
fieldset div input,fieldset div textarea{
width:150px;
border-top:1px solid #555;
border-left:1px solid #555;
border-bottom:1px solid #ccc;
border-right:1px solid #ccc;
padding:1px;color:#333;
}
fieldset div select{
padding:1px;
}
div.fm-multi div{
margin:5px 0;
}
div.fm-multi input{
width:1em;
}
div.fm-multi label{
display:block;
width:200px;
padding-left:5em;
text-align:left;
}
#fm-submit{
clear:both;
padding-top:1em;
text-align:center;
}
#fm-submit input{border:1px solid #333;
padding:2px 1em;
background:#555;
color:#fff;
font-size:100%;
}
input:focus,textarea:focus{
background:#efefef;color:#000;
}
fieldset div.fm-req{
font-weight:bold;
}
fieldset div.fm-req label:before{
content:"* ";
}
//body{
//padding:0;
//margin:20px;
//color:#333;
//background:#fff;
//font:12px arial,verdana,sans-serif;text-align:center;
//}
#fm-container{
margin:0 auto;
padding:1em;
width:300px;
text-align:left;
background-color:#eeeeff;
font: arial,verdana,sans-serif;
//text-align:center;
}
p#fm-intro{
margin:0;
}
.button {
display: inline-block;
outline: none;
cursor: pointer;
text-align: center;
text-decoration: none;
font: 14px/100% Arial, Helvetica, sans-serif;
padding: .5em 2em .55em;
text-shadow: 0 1px 1px rgba(0,0,0,.3);
-webkit-border-radius: .5em;
-moz-border-radius: .5em;
border-radius: .5em;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
box-shadow: 0 1px 2px rgba(0,0,0,.2);
}
.button:hover {
text-decoration: none;
}
.button:active {
position: relative;
top: 1px;
}
.round{
font: 14px/100% Arial, Helvetica, sans-serif;
-webkit-border-radius: .5em;
-moz-border-radius: 1.5em;
border-radius: 1.5em;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
box-shadow: 0 1px 2px rgba(0,0,0,.2);
}
.req{
margin-top:.5em;
font: 10px Arial, Helvetica, sans-serif;
}
//////////////// The form-test HTML////////////////////////
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="cssform.css">
<title>Ajax Test</title>
<!-- From JavascriptKit.com -->
<script type="text/javascript">
function ajaxRequest(){
//activeX versions to check for in IE
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
//Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
if (window.ActiveXObject){
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
// if Mozilla, Safari etc
else if (window.XMLHttpRequest)
return new XMLHttpRequest()
else
return false
}
</script>
</head>
<body>
<!-- from JavascriptKit.com -->
<script type="text/javascript">
function ajaxpost(){
var mypostrequest=new ajaxRequest();
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText
}
else{
//force a write just to see if anything shows (just blinks):
document.getElementById("result").innerHTML="<p><strong>Error</strong></p>";
//normally, this alert comes up, but the server-side does write the file.
//alert("An error has occured making the request")
}
}
}
var namevalue =encodeURIComponent(document.getElementById("fm-name").value)
var townvalue =encodeURIComponent(document.getElementById("fm-town").value)
var parameters="fm-name="+namevalue+"&fm-town="+townvalue
mypostrequest.open("POST", "ajax-test.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
</script>
<!-- this is the form that goes in the main page -->
<div id="fm-container" class="round">
<form id="fm-form" method="POST" action="">
<fieldset>
<div style="
font:arial,verdana,sans-serif;
text-align:center;
color:#ff0000;
text-shadow:0 1px 1px rgba(0,0,0,.3);">
<h2>I Support Restoring PBS!</h2>
</div>
<div class="fm-req">
<label for="fm-name">Your Name:</label>
<input name="fm-name" id="fm-name" type="text" maxlength="20">
</div>
<option value=""></option>
<div class="fm-req">
<label for="fm-town">Town:</label>
<select id="fm-town" name="fm-town">
<option value="" selected="selected">Choose a Town</option>
<option value="Morongo Valley">Morongo Valley</option>
<option value="Yucca Valley">Yucca Valley</option>
<option value="Joshua Tree">Joshua Tree</option>
<option value="Twentynine Palms">Twentynine Palms</option>
<option value="Wonder Valley">Wonder Valley</option>
<option value="MCAGCC">MCAGCC</option>
<option value="Copper Mesa">Copper Mesa</option>
<option value="Desert Heights">Desert Heights</option>
<option value="Flamingo Heights">Flamingo Heights</option>
<option value="Yucca Mesa">Yucca Mesa</option>
<option value="Landers">Landers</option>
<option value="Lucerne Valley">Lucerne Valley</option>
<option value="Homestead Valley">Homestead Valley</option>
<option value="Pioneer Town">Pioneer Town</option>
<option value="Apple Valley">Apple Valley</option>
<option value="Victorville">Victorville</option>
<option value="Hesperia">Hesperia</option>
<option value="Barstow">Barstow</option>
<option value="Daggett">Daggett</option>
<option value="Hinkley">Hinkley</option>
<option value="Newberry Springs">Newberry Springs</option>
<option value="Yermo">Yermo</option>
<option value="Other Area/Town/City">Other Area/Town/City</option>
</select>
</div>
<div style="text-align:center;" >
<h5>*All Fields are required.</h5>
</div>
<div id="fm-submit" class="fm-req">
<input name="Submit" value="Add My Name!" type="submit" class="button" onClick="ajaxpost()">
</div>
</fieldset>
</form>
<!-- The test-div I'm trying to write to, just 'blinks' when I force a test-write -->
<div id="result"></div>
</div>
</body>
</html>
Last edited by morongo47; 09-12-2011 at 07:17 AM..
Also, you can get rid of the || window.location.href.indexOf("http")==-1 part of that "if" statement. That is only there for local machine testing (ie, for testing with an AJAX call on your own local computer rather than with a live website). So, really, the above code should be like so:
Code:
alert("server response code: " + mypostrequest.status);
if (mypostrequest.status==200){
document.getElementById("result").innerHTML=mypostrequest.responseText
}
Give that a run and let me know if/what the alert comes up with.
Your on the wrong track. Your javascript is fine, it's your HTML that needs to be reconsidered. I don't know php, so I changed your external php file to ajax-test.asp
Also, since your only testing the response (you said the php wrote to the server as expected) I omitted any logic, or writes... Just the response posting from the asp page to the ajax caller then written to the HTML element.
I left your code the same, but I changed the HTML and the "Thanx!" posted to the "result" element. You made the submit button a submit button... I just started with AJAX, so no one jump down my throat if I say this wrong, but if your form has a submit button you are telling the HTML document to execute the way it would for any other form. With AJAX, the form submission is in the javascript. So all I did was remove the submit
Code:
<input name="Submit" value="Add My Name!" type="button" class="button" onClick="ajaxpost()">
And it worked just fine for me. Hope that helps!
-Also, based on the way you are using the ajaxRequest() I don't think you need the "new", but it's perfectly valid, and runs just fine both ways.
Last edited by blaze4218; 09-12-2011 at 09:50 PM..
DevNull69 is correct but that is not your
problem as the code works either way,
Here is the problem ...
<input name="Submit" value="Add My Name!" type="submit" class="button" onClick="ajaxpost()">
this will not work, this will ...
<input name="Submit" value="Add My Name!" type="button" class="button" onClick="ajaxpost()">
or you could do this ...
<form id="fm-form" method="POST" action="" onsubmit="ajaxpost();return false">
/* form code */
<input name="Submit" value="Add My Name!" type="submit" class="button" >
The blink is because you are submitting to the html page not the php.
As I mentioned before, new is not neccesary, but it is viable.
Your not creating an object with constructors, but you do seam to be creating an instance of ajaxRequest() (which is what was written on the javascriptkit.com page where you got your script), for which the correct syntax would be to use new. Then, accessing the object XMLHttpRequest() methods i.e. mypostrequest.open() (not sure what that's called).
But in javascript, arrays, functions, and even strings are all treated as objects, and as such there are times when i see people use new when they don't need it, and times when they omit it when they should have used it, and javacript doesn't seem to give a hoot (it just knows ).
I hope I used all those big words correctly (I learned most of them last week, lol), but just in case:
see also
-http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript
-https://developer.mozilla.org/en/JavaScript/Guide/Details_of_the_Object_Model
-http://joost.zeekat.nl/constructors-considered-mildly-confusing.html
Those should provide a more conclusive answer to this droll debate... On the other hand- Thanx DaveyErwin for the addition to my response about forms, I wish you had told me that last week, you would have saved me a headache But I wonder, are forms really neccesary when using AJAX? I mean, I use them way more often than I ever use ajax, but when I use ajax I don't really find a need for a form... Maybe a backwards compatibility thing? If the ajax fails use the form to submit?
But I wonder, are forms really neccesary when using AJAX? I mean, I use them way more often than I ever use ajax, but when I use ajax I don't really find a need for a form... Maybe a backwards compatibility thing? If the ajax fails use the form to submit?
Yeah , if its coded correctly sure thats viable, forms are
not a necessary for "ajax" of course but, I personally
always put form elements inside form tags but that
is not strictly necessary.
Thanks for all you guys pitching in on this! I learned a lot just reading through your explanations, you definitely all have some pretty sharp eyes (not to mention, minds).
If I was a web developer, I probably would have paid more attention to javascript all those many years ago, but like so many, I just know what I use.
Thanks again to all of you for all your help, you guys are great.
Last edited by morongo47; 09-15-2011 at 06:58 AM..