Jump to content

AJAX and PHP


Dan06

Recommended Posts

I'm learning ajax and up to this point, I've made web-pages that have 1 form made up of javascript/html that refers to a php page that only has code to process (i.e. update, insert into db) the form from the html page.

 

I'm now would like to have 3 unique registration pages, coded in javascript/html, and still have only 1 php page that does the inserting and updating, rather than having 3 php pages to do the backend work.

 

I thought of creating functions in the php page and correspondingly have the variable data (in the javascript code) enclosed in the appropriate function, so when I send the data only the intended php is executed. Is that the way to go? Or is there another, better way?

 

Insight and suggestions are much appreciated. Thanks

Link to comment
Share on other sites

The easiest way to do that would be with a conditional statement. Then just pass a variable (in my example, one called "function") that determines which code to run.

if ($_REQUEST['function']=="function1"){
  //do this stuff...
}
elseif ($_REQUEST['function']=="function2"){
  //do other stuff...
}

Link to comment
Share on other sites

Thanks for the response. In the process of adjusting my code, I seemingly altered something that now causes my code to no longer work... I've gone over the code and I can't find what's wrong with it... Below is my code, can someone take a look and let me know what they think/know is wrong with it? Thanks.

 

<script language="javascript">
function callback(ajaxResponse){
alert(ajaxResponse);
}

function sendData(){

var XMLHttpRequestObj = false;

var interval = document.forms['basicRegister'].elements['joinType'].length;
for (i=0; i<interval; i++){
	if(document.forms['basicRegister'].elements['joinType'][i].checked){
		var joinType = document.forms['basicRegister'].elements['joinType'][i].value;
	}
}
var firstName = document.forms['basicRegister'].elements['firstName'].value;
var lastName = document.forms['basicRegister'].elements['lastName'].value; 
var email = document.forms['basicRegister'].elements['email'].value; 
var password = document.forms['basicRegister'].elements['password'].value;

var params = "firstName=" + firstName + "&" + "lastName=" + lastName + "&" + "email=" + email + "&" + "password=" + password + "&" + "joinType=" + joinType;

if (window.XMLHttpRequest){
	XMLHttpRequestObj = new XMLHttpRequest();
} else if (window.ActiveXObject){
	XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
	}

if (XMLHttpRequestObj){
	var url = "registration.php";
	XMLHttpRequestObj.open("POST", url, true);
	XMLHttpRequestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	XMLHttpRequestObj.setRequestHeader("Content-Length", params.length);
	XMLHttpRequestObj.setRequestHeader("Connection", "close");

	XMLHttpRequestObj.onreadystatechange = function(){
		if (XMLHttpRequestObj.readystate == 4 && XMLHttpRequestObj.status == 200){
			callback(XMLHttpRequest.responseText);
		}	
	}
	XMLHttpRequestObj.send(params);
}

} 

Link to comment
Share on other sites

The code is supposed to retrieve data from the form and using the post method send it to the processing page. The code does pull the variables from the form, but seemingly does not send the data. I initially thought the problem was with the processing page. So, I tested it by adding an html form, which uses the post method, to the processing page. The php code successfully inserted the data into the database, from the form in the processing page. Hence, that leads me to believe there was a problem with the ajax component of my code.

 

As additional information, below is the processing page code.

 

<?php

include ("objects.php");

$dbConn = new dbConnection();
$format = new stringFormat(); 

$connected = $dbConn->conn(); // connect to db
$dbConn->select_db(); // select db

for ($i=0; $i<6; $i++) // generate id
{
    $Id .= rand(0,1) ? chr(rand(48,57)) : chr(rand(97,122));
}

$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$joinType = $_POST['joinType'];

$insertQuery = sprintf("INSERT INTO registration (Id, firstName, LastName, joinType, email, password) VALUES(%s, %s, %s, %s, %s, %s)",  
$format->formatValue($Id),
$format->formatValue($firstName),
$format->formatValue($lastName), 
$format->formatValue($joinType),
$format->formatValue($email),
$format->formatValue($password));

$result = mysql_query($insertQuery, $connected);
?> 

 

Note: the objects in the processing code work fine. The formatValue function simply adds ' ' to the variable it receives.

Link to comment
Share on other sites

Your javascript has two incorrect variables in the onreadystatechange function:

 

Should be:

      XMLHttpRequestObj.onreadystatechange = function(){
         if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
            callback(XMLHttpRequestObj.responseText);
         }   
      }

 

You didn't capitalize the S in readyState

You didn't add Obj to callback(XMLHttpRequestObj.responseText);

 

 

Link to comment
Share on other sites

Thanks xtopolis. Once I made those two corrections, the code inserts the form data into the database. I do have 2 follow-up questions however.

 

1. The alert message that I've setup only occurs every other entry, i.e. the first time I fill and submit the form, the alert occurs; second time through, alert doesn't occur; third time, the alert occurs. Why is that?

 

2. Once the first form is successfully inserted into the database, I'd like to display another form. How can I confirm a successful insert and only then display another, new form?

Link to comment
Share on other sites

Thus far I've coded 1 form and the javascript to send that form's data to the processing page.

 

My goal is to have one page display 3 successive forms (after a form's data is successfully inserted to db, the next form is displayed in previous one's place).

 

Additionally, since my last post I tried the code in firefox and the form data would insert, but the alert message never showed.

 

Below is the code I have thus far. 

 

<html>
<head>
<title>Registration</title>
<script language="javascript">

function callback(ajaxResponse){
var ajaxResponse;
alert(ajaxResponse);
}

function sendData(){

var XMLHttpRequestObj = false;

var interval = document.forms['basicRegister'].elements['joinType'].length;
for (i=0; i<interval; i++){
	if(document.forms['basicRegister'].elements['joinType'][i].checked){
		var joinType = document.forms['basicRegister'].elements['joinType'][i].value;
	}
}
var firstName = document.forms['basicRegister'].elements['firstName'].value;
var lastName = document.forms['basicRegister'].elements['lastName'].value; 
var email = document.forms['basicRegister'].elements['email'].value; 
var password = document.forms['basicRegister'].elements['password'].value;

var params = "firstName=" + firstName + "&" + "lastName=" + lastName + "&" + "email=" + email + "&" + "password=" + password + "&" + "joinType=" + joinType;

if (window.XMLHttpRequest){
	XMLHttpRequestObj = new XMLHttpRequest();
} else if (window.ActiveXObject){
	XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
	}

if (XMLHttpRequestObj){
	var url = "registration.php";
	XMLHttpRequestObj.open("POST", url, true);
	XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
	XMLHttpRequestObj.setRequestHeader("Connection", "close");

	XMLHttpRequestObj.onreadystatechange = function(){
		if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
			callback(XMLHttpRequestObj.responseText);
			delete XMLHttpRequestObj;
		}	
	}
	XMLHttpRequestObj.send(params);
}

} 
</script>
</head>

<body>
<form name="basicRegister" id="basicRegister" method="post" style="padding: 10px; border-bottom: #000066 dotted;">
<table width="200" border="0" cellpadding="10" cellspacing="0">
<tr><td>
<p>First Name: <br/> <input type="text" name="firstName" id="firstName" /> </p>
<p>Last Name: <br/> <input type="text" name="lastName" id="lastName" /> </p>
<p>Joining as: <br/> <input type="radio" name="joinType" value="Individual" style="margin-left: -5px;" />Individual   <input type="radio" name="joinType" value="Business" />Business </p></td>
<td><p>Email Address: <br/> <input type="text" name="email" id="email" /> </p>
<p>Password: <br/> <input type="password" name="password" id="password" /> </p>
<p>Confirm Password: <br/> <input type="password" name="confirmPassword" id="confirmPassword" /> </p></td></tr>
<tr><td colspan="2"><center><input type="submit" name="submit" value="Sign-Up" onclick="sendData()"/></center></td></tr>
</table>
</form>
</body>
</html>

 

 

Link to comment
Share on other sites

Firstly, this form should work and alert the response data.

  Didn't change much, but you should note that I changed the button onclick="sendData()" event, and moved it to the form onsubmit event.. with a return value..

 

It now reads: <form onsubmit="return sendData();" ...>

and sendData() has "return false;" at the end, so that the form doesn't get submit normally, but rather through javascript (means the page never moves, and ajax handles the data).

 

<html>
<head>
<title>Registration</title>
<script type="text/javascript">

function callback(ajaxResponse){
   alert(ajaxResponse);
}

function sendData(){
   
   var XMLHttpRequestObj = false;
   
   var interval = document.forms['basicRegister'].elements['joinType'].length;
   for (i=0; i<interval; i++){
      if(document.forms['basicRegister'].elements['joinType'][i].checked){
         var joinType = document.forms['basicRegister'].elements['joinType'][i].value;
      }
   }
   var firstName = document.forms['basicRegister'].elements['firstName'].value;
   var lastName = document.forms['basicRegister'].elements['lastName'].value;
   var email = document.forms['basicRegister'].elements['email'].value;
   var password = document.forms['basicRegister'].elements['password'].value;
   
   var params = "firstName=" + firstName + "&" + "lastName=" + lastName + "&" + "email=" + email + "&" + "password=" + password + "&" + "joinType=" + joinType;
   
   if (window.XMLHttpRequest){
      XMLHttpRequestObj = new XMLHttpRequest();
   } else if (window.ActiveXObject){
      XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");
      }
      
   if (XMLHttpRequestObj){
      var url = "registration.php";
      XMLHttpRequestObj.open("POST", url, true);
      XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      XMLHttpRequestObj.setRequestHeader("Content-length", params.length);
      XMLHttpRequestObj.setRequestHeader("Connection", "close");
   
      XMLHttpRequestObj.onreadystatechange = function(){
         if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){
            callback(XMLHttpRequestObj.responseText);
            delete XMLHttpRequestObj;
         }   
      }
      XMLHttpRequestObj.send(params);
   }

  return false;
}
</script>
</head>

<body>
<form onsubmit="return sendData()" name="basicRegister" id="basicRegister" method="post" style="padding: 10px; border-bottom: #000066 dotted;">
<table width="200" border="0" cellpadding="10" cellspacing="0">
<tr><td>
<p>First Name: <br/> <input type="text" name="firstName" id="firstName" /> </p>
<p>Last Name: <br/> <input type="text" name="lastName" id="lastName" /> </p>
<p>Joining as: <br/> <input type="radio" name="joinType" value="Individual" style="margin-left: -5px;" />Individual   <input type="radio" name="joinType" value="Business" />Business </p></td>
<td><p>Email Address: <br/> <input type="text" name="email" id="email" /> </p>
<p>Password: <br/> <input type="password" name="password" id="password" /> </p>
<p>Confirm Password: <br/> <input type="password" name="confirmPassword" id="confirmPassword" /> </p></td></tr>
<tr><td colspan="2"><center><input type="submit" name="submit" value="Sign-Up"/></center></td></tr>
</table>
</form>
</body>
</html>

 

As for your goals... there are a few ways to do that.  Depending if your forms are static or not, you could either have PHP return a form for javascript to output onto the page, or have javascript show a form it already has hidden when the first form is successfully sent.

 

You can ready PHP to see if it was a success or not.. just read the output..

if(xmlhttpobj.responseText == "Success") { do something } else { show errors }

 

something like that.  It's really up to you how you want to do it, and depends on if your forms are dynamic or static.  If you are feeling confident with javascript, learn object oriented javascript and make form objects perhaps..

 

Or simply, have the forms already made and hidden/disabled with css/javascript, and just show them as needed.

Link to comment
Share on other sites

Thanks xtopolis, the form does insert the data and the alert does show the response data every time. I probably will use php for the remaining forms, as one of them is dynamic.

 

But there are two aspects I was hoping to clarify.

1. When I made the change to use the onsubmit event, once the form's data is inserted and the alert displays, the filled out form data remains. When the onclick event was used, once the data was inserted, the form would be cleared. With onsubmit, is the form supposed to remain filled? If so, how can I clear it?

 

2. What do you mean, "... have PHP return a form for javascript to output" Specifically I'm concerned with the word return. Right now the way I was planning on doing it, was in the php side verify the form data was inserted and then echo/print the form which would be sent back to the javascript in the responseText. For example:

 

 if ($result == "1"){
echo ("<form>...</form>");
}

 

 function callback(ajaxResponse){
var ajaxResponse;
document.getElementById("Form").innerHTML = ajaxResponse;
}

 

As an alternative could I return a form stored in variable from the php side to the javascript/ajax side, i.e.

 $form2 = "<form>...</form>"; 
return $form2; 

 

Link to comment
Share on other sites

1) That is the intended result of my method.  The form doesn't submit, because it's no longer behaving like a form...  As for clearing it, I was under the impression you planned to display another form in it's place, therefore it would be completely replaced anyway.

 

2)reponseText holds the output from the PHP page that it accesses.  You can have the PHP page output text/html if you wanted which you could have javascript put into the page that submitted the form

 

You can have javascript replace it with whatever you want.  Say if there is an error, display and error message and the same form again.. it's really up to you.

Link to comment
Share on other sites

Thanks for the clarification on the two points. I wanted to make sure that the form was supposed to retain the values. I was also a bit confused about what you meant my "return", I thought you meant the proper way to use/interact with responseText was with a return() statement rather than outputing text or html via echo, print etc. on the php page.

 

Once again, thanks.

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.