Jump to content

ajax loaded form - help!


jackappleby

Recommended Posts

using an ajax script, i am loading a php file with a form in it into a DIV.

 

it works great until i click submit on the form. once submitted, the php returns (with errors / success messeges) in another window - not a new window, just on its own page. basically, the submit button returns the ajax-loaded php file not back into the DIV, but loads the php file on its own into my browser window (so no css or anything). does anybody know, once submit has been clicked, how i keep the output (error and success messeges) from the form in the same window and same DIV as it was originally loaded from?

 

i don't know about javascript / ajax, and have limited knowledge of php.

 

for reference (don't know if it is really worth including this), here is the ajax script:

 

// here we define global variable
var ajaxdestination="";

function getdata(what,where) { // get data from source (what)
try {
   xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
  		new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { /* do nothing */ }

document.getElementById(where).innerHTML ="<div class=\"loading\"><img src='images/loading.gif'></div>";
// we are defining the destination DIV id, must be stored in global variable (ajaxdestination)
ajaxdestination=where;
xmlhttp.onreadystatechange = triggered; // when request finished, call the function to put result to destination DIV
xmlhttp.open("GET", what);
xmlhttp.send(null);
  return false;
}

function triggered() { // put data returned by requested URL to selected DIV
  if (xmlhttp.readyState == 4) if (xmlhttp.status == 200) 
    document.getElementById(ajaxdestination).innerHTML =xmlhttp.responseText;
}

 

and here is my php file that is loaded via ajax:

 

<?php
include("../account/include/session.php");
?>

<div class="top_box_content_header_left">
Update Your Email Address 
<?
$data = mysql_query("SELECT * FROM users")
or die(mysql_error()); 
$info = mysql_fetch_array( $data ); 
echo "( currently ".$info['email'] .")"; 
?>
</div>

<form action="account/process.php" method="POST">

<label>New Email Address</label>
<input type="text" name="email" maxlength="50"><? echo $form->error("email"); ?>

<input type="hidden" name="subedit" value="1">
<input type="submit" value="Update" id="submitbutton">

<?
if(isset($_SESSION['useredit'])){
   unset($_SESSION['useredit']);
   
echo '<div id="success">Your account has been successfully updated.</div>';

}
?>

</form>

</div> 

 

Thank you

Link to comment
Share on other sites

So you want the form to be processed on the same page?

 


<script language="javascript">
function blah(form) {
    a = <pretend this is an ajax object>;
    a.open("GET", "blah.php?bleh="+form.bleh.value);
    a.onreadystatechange = callback;
    a.send(null);
}
</script>

<form action="blah" method="blah" onsubmit="blah(this); return false;">
<!-- the return false; prevents the form from submitting -->
<input name="bleh" type="text" />
</form>

 

 

That's a way to do it in it's simplest form.

Link to comment
Share on other sites

yes, i want the form processed on the same page and for it to stay in the div it was loded into.

 

sorry corbin, but i don't know what to do with the code you suggested. i don't know what replaces 'blah' or 'pretend this is an ajax object' or anything - is it possible for you to fill in these bits for me? i've no knowledge of javascript, only to the extent of being able to copy and paste it.

 

thanks

Link to comment
Share on other sites

You should know Javascript before delving into AJAX x.x.

 

 

I'm too lazy to write something custom, so I'm modding my post from here: http://www.phpfreaks.com/forums/index.php/topic,206137.msg938757.html#msg938757.

 

Anyway:

 

<!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" xml:lang="en" lang="en" dir="ltr">
<head>
<title>AJAX Example</title>
<script language="javascript">

	//now for the non-jQuery method.  (Standard?  I don't know what to call it lol)

	function GetAjax() { //this is a little function I use sometimes when
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) { }

		try {
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) { }

		if (typeof XMLHttpRequest != 'undefined') {
			return new XMLHttpRequest();
		}

		throw new Exception('No AJAX support');
	}

	function Login(form) {
		//obj is the same thing as an object returned by something like document.getElementById()
		try {
			var aobj = new GetAjax();
			aobj.open("POST", "login.php", true);
			var p = "username=" + encodeURI(form.username.value) + "&password=" + encodeURI(form.password.value); //the post params.
			//set some headers just in case
			aobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			aobj.setRequestHeader("Content-length", p.length);
			aobj.onreadystatechange = HandleSendResponse;
			aobj.send(p);
		}
		catch (E) {
			alert('Bah!');
			//worst error handling ever.  EVER!
		}
	}

	function HandleSendResponse() {
		//hopefully you get this concept because i't's hard to explain....  HandleSendRequest() will be executed
		//inside of the XMLHttpRequest class, so, this responds to 'this' instance of that class
		if(this.readyState == 4) {
			//it's done!
			if(this.status == 200) {
				//everything is (assuming the data was passed/processed correctly) good
				if(this.responseText == "1")
                                            document.getElementById("form_holder").innerHTML = "Thank you for logging in.";
                                        else
                                            document.getElementById("form_error").innerHTML ="'Incorrect username or password.";
			}
			else {
				//something went wrong x.x
			}
		}
	}

</script>
</head>

<body>

<div id="form_holder">
    <strong>Please login:</strong>
    <div id="form_error" style="color: red;"></div>
    <form action="login.php" method="POST" onsubmit="return Login(this);">
        Username: <input type="text" name="username" value="" /><br />
        Password: <input type="password" name="password" value="" />
    </form>
</div>

</body>

 

Then login.php:

 

<?php
if(isset($_POST['username']) && $_POST['username'] == 'someone' && isset($_POST['password']) && $_POST['password'] == 'something')
    echo "1";
else
    echo "0";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.