Forum Moderators: open

Message Too Old, No Replies

AJAX post method

         

music_man

1:26 am on Jul 23, 2006 (gmt 0)

10+ Year Member



Hi

I am just wondering how to get form variables to send using AJAX.

I can get it to work with GET, but I am looking to have it so that I can submit several fields to a php page and have that php page do stuff with those variables.

I have an example with GET that I got from a tutorial and I changed a bit:

<html>
<body>

<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
var un = document.getElementById("username").value;
ajaxRequest.open("GET", "working/functions/pagetest.php?act=add_page&username=" + un, true);
ajaxRequest.send(null);
}

//-->
</script>

<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name="username" id="username" /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>

And the php


<?

if($_GET["act"]=="add_page") {

$un = $_GET["username"];

echo $un;

}

?>

Rambo Tribble

3:47 am on Jul 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I believe all you need to do is change your method to POST in the open() statement as well as the form's method attribute and change your PHP to reflect that you now have $_POST variables being submitted.

[edited by: Rambo_Tribble at 3:49 am (utc) on July 23, 2006]

supermoi

11:44 pm on Jul 23, 2006 (gmt 0)

10+ Year Member



Use post instead of get for the first parameter in open(). Separate the query string (everything after the?) from the address of your script and pass this query string in the send() statement. (send(query string))
Google it for examples.