Jump to content

ajax post method


djp1988

Recommended Posts

I am trying to adapt ajax to insert a comment and display it on submit of a form, the php page which is loaded in, has all the script for insert of comment and listing existing comments, but when I submit, I get a Method Not Allowed message, I have put obj.onsubmit = function(){showCustomer();} return falseto make the refresh of the page not happen as I want the javascript to block that default action, so I "Return false" as seen in a few bookshere's my code:

<!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=ISO-8859-1" /><title>Untitled Document</title><script type="text/javascript" src="xmlhttp.js"></script><script type="text/javascript">window.onload = startFunctions;function startFunctions(){	listeners();	}function listeners(){	var obj = document.getElementById("form1");	obj.onsubmit = function(){showCustomer();} return false;	}function showCustomer(){ 	xmlHttp=GetXmlHttpObject();		if (xmlHttp==null){		  alert ("Your browser does not support AJAX!");		  return;		  } 	var url="ajaxcommentPHP.php";	xmlHttp.onreadystatechange=stateChanged;	xmlHttp.open("POST",url,true);	xmlHttp.send(null);}function stateChanged(){ 	if (xmlHttp.readyState==4){ 	document.getElementById("comments").innerHTML=xmlHttp.responseText;	}}</script></head><body><form id="form1" name="form1" method="post" action="">  <p>	<textarea name="textarea" cols="25" rows="5"></textarea></p>  <p>	<input type="submit" name="Submit" value="Submit" /></p></form><div id="comments"></div></body></html>

Link to comment
Share on other sites

i have modified it a bit with still the same error:

function showCustomer(){ 	xmlHttp=GetXmlHttpObject();		if (xmlHttp==null){		  alert ("Your browser does not support AJAX!");		  return;		  } 	var url="ajaxcommentPHP.php";	xmlHttp.onreadystatechange=stateChanged;	xmlHttp.open("POST",url,true);	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");	http.setRequestHeader("Content-length", params.length);	http.setRequestHeader("Connection", "close");	xmlHttp.send(params);}

Link to comment
Share on other sites

It's actually easier than that. Unless there is a time when you will be submitting the form by the traditional route, don't use a form. Just use the form elements. Use a regular button for your "submit" button, and attach your listener to the button's onclick event.EDIT: I posted this before I saw post #3 above. I'm not sure about that first content header. And what is params? Are you sending something or just making a connection? I would have guessed you'd be sending the content of your textarea. You must do that explicitly.

Link to comment
Share on other sites

1. The only Request Header you really need is this: xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");2. In this statement, xmlHttp.send(parameters);, the variable parameters isundefined. If in fact you are trying to send the content of your text area,you need to get a reference to that content. Something like this:myData = "message=" + document.getElementById("commentBox").value;xmlHttp.send(myData);3. There are some other errors as well, but they should clear up if you followthe first part of my suggestion.NOTE. This post has been edited to remove TWO errors I mention below.

Link to comment
Share on other sites

Please see the changes I have made, I have replaced the event handler to an onclick for a normal button, I have then got rid of the <form> and just use the textarea and one button, I have deleted the return false for the onclick event, But it doesn't do what i want, it loads the page into the div but the post info isn't sent and retreived, my ajax-res.php page is as so:

<?php echo $_POST['textarea'];echo 'ddd';?>

i echo ddd just so i see the page load in, but the post data is empty

Link to comment
Share on other sites

Almost there! I forgot something. We need to change this line:myData = document.getElementById("commentBox").value;to this:myData = "message=" + document.getElementById("commentBox").value;And in your PHP script, change this:echo $_POST['textarea'];to this (notice how the keywords are now the same):echo $_POST['message'];

Link to comment
Share on other sites

Well, I'll be darned. Two mistakes in one thread. This one's ugly. When I told you to change your request header, I'd just been looking at the W3 Spec, and I copied their example. Just now, when I looked at one of my own AJAX scripts, I found the content header you'd been using. I guess it works because we set up the data in the same pattern as form data.So replace it again. :)xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");It really should work because I tested it in your document. Good luck!

Link to comment
Share on other sites

Great yes it is working, so this line: myData = "message=" + document.getElementById("commentBox").value;I am setting the variable 'message' which php can pick up ?

Link to comment
Share on other sites

What if i want to send another variable, i tried with no success this line: myData = "message=" + document.getElementById("commentBox").value + "name=" + document.getElementById("NameBox").value; xmlHttp.send(myData);And also tried: myData = "message=" + document.getElementById("commentBox").value; myName = "name=" + document.getElementById("NameBox").value; xmlHttp.send(myData, myName);

Link to comment
Share on other sites

You came very close, both times. For each new value you want to send, you follow this syntax: key=value. Link multiples together with the & character. Like this:

myData  = "message=" + document.getElementById("commentBox").value;myData += "&";myData +=  "name=" + document.getElementById("NameBox").value;

And of course your script has get the value of the second key as well:

<?php   echo $_POST['message'] . "<br>" . $_POST['name'];?>

Now, we really should be testing for those values before we try to use them, so a more robust script would look something like this:

<?php   if (empty($_POST['message']) || empty($_POST['name']) ) {	  echo "Please complete both fields.";   } else {	  echo $_POST['message'] . "<br>" . $_POST['name'];   }?>

Link to comment
Share on other sites

Wow, what would i do without DD ! (you're initials)I'm enjoying this conenction between js and php, I couldn't get my head around it previously, exciting new domain for me !

Link to comment
Share on other sites

I prefer to make my query strings with Array.join, like so:

var parameters = ['foo=bar', 'name=Chris']; //any (or none) that need to go regardless//...if(condition){	parameters.push('this=that');}//...parameters = parameters.join('&');// Our array is now a string.if(method == 'POST'){	ajax.request(method, url, async);	ajax.send(parameters);}else if(method == 'GET'){	ajax.request(method, url + '?' + parameters, async);	ajax.send(null);}

An advantage of this is that all your ampersands are centralized to one string. This means that, as the new ';' separator is phased in, you can easily change your separator to ';&' or ';' as you see fit.Of course, I don't use all that code in every (nor any, I don't think) AJAX project of mine; I used the if-statements rather than multiple blocks of code separated by English sentences.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...