Helping ordinary people create extraordinary websites!

Go Back   Web Development Forum > Website Programming > Client-Side Scripting
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 01-15-2008, 03:28 PM
Junior Member
 
Join Date: Jan 2008
Posts: 24
Default AJAX and PHP working together

I am trying to add AJAX functionality to a site I am building for someone and would like to use ajax in it but am seemingly lost when it comes to this concept.

Here is what Im trying to do:

I want users to be able to signup for a newsletter. This signup process which check against the db to ensure that the user is not already in the system. If they are it needs to return a message saying email already subscribed. If it isnt then a message saying subscription created. All this I would like done without the page reloading.

Any help would be appreciated.

JL
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 01-16-2008, 11:54 AM
BigAlReturns's Avatar
Moderator Extraordinaire!
 
Join Date: Dec 2007
Location: The Wirral, England
Posts: 298
Send a message via MSN to BigAlReturns
Default

Hi JL, I don't have time this second to give you much code for this, but let me explain the concept of Ajax, which might help you understand the issue a bit better.

Firstly we have a page the user sees - call it news.html. This contains a form with the email field. When it's submitted, javascript functions take over, and instead of going to the form processing page as normal, JS requests the processing page in the background, so the user doesn't see anything. For our example, when submitted, JS will request the page process.php?email=whatevertypedin. Process.php is then parsed by the server as it normally would be, and outputs whatever it outputs. This output is not to your users screen though, it's back to the JS function on the original page. In true Ajax (Asynchronous javascript and XML) the output is XML, but to start with I find it easier to use a variant AJAX, which I christen AJAP, or Asynchronous Javascript And Plain-text. So in our scenario, process.php returns one of a set of values to the JS function in plain text, for example, 1 might represent not in DB, added OK. 2 means already in DB, 3 means not in DB, but error occurred adding, 4 means invalid email address
The JS function then uses this returned value to do something - for example, if 1 is returned, display a success message to the user. I'm sure you can work out suitable things to display for the other return values.

This is the basic process of how Ajax works - there is some specific code you need to use, and when I get a chance later on I'll post it for you, with some explanation of what each part of it does. Hope that helps.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 01-19-2008, 07:09 PM
BigAlReturns's Avatar
Moderator Extraordinaire!
 
Join Date: Dec 2007
Location: The Wirral, England
Posts: 298
Send a message via MSN to BigAlReturns
Default

Sorry it took a while JZ, but I'm back and I have some code for you! It's divided into three parts - the page the user looks at (index.php), the javascript (ajax.js) and the backend script (backend.php).

Code:
index.php
<html>
<head>
<title>Database Emailer</title>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body onLoad="backCompat();">
<form id="emailsignup" method="GET" action="backend.php">
<input id="nojs" type="hidden" value="true" />
<input id="email" type="text" />
<span id="submitspan"><input id="submit" type="submit" /></span>
</form>
<div id="return">
</div>
</body>
</html>
Code:
backend.php
<?php
$nojs=$_GET['nojs'];
$email=$_GET['email'];
IF ($nojs=="true") {
// process email in non ajax way, redirect to confirmation page etc etc - this is for users who dont have JS enabled
} ELSE {
// process ajax style
// do database work and return one of 3 values depending on outcome
    IF ( valid email address ) {
        IF (not already in database) {
            IF (added to DB OK)  {
                $return="1";
            } ELSE {
                $return="3";
            }
       ELSE {
           $return="2";
       }
    } ELSE {
        $return="4";
    }
    echo $return;
}
Code:
ajax.js
function ajaxSubscribe() 
  { 
  var xmlHttp; 
  try 
    { 
    // Firefox, Opera 8.0+, Safari 
    xmlHttp=new XMLHttpRequest(); 
    } 
  catch (e) 
    { 
    // Internet Explorer 
    try 
      { 
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
      } 
    catch (e) 
      { 
      try 
        { 
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
      catch (e) 
        { 
        alert("Your browser does not support AJAX!"); 
        return false; 
        } 
      } 
    }
    // end of standard code 
    xmlHttp.onreadystatechange=function() 
          { 
          if(xmlHttp.readyState==4)  // readystate 4 means finished, others mean other things, but not finished is all that matters! 
          { 
          //request done  
              if(xmlHttp.responseText==1) 
              {
               // everything OK, so return that message to 'return' div
              document.getElementById('return').innerHTML="Email Subscribed";
              }
              else if (xmlHttp.responseText==2)
              {
              // email already in DB, so tell user this
              } // more else ifs here for the other options - you get the picture!
          } 
          else  
         { 
         // request still pending, i.e. backend.php is being parsed 
     document.getElementById('return').innerHTML='Working' 
         } 
 
      }
      // this is how we call the backend.php - inserting GET variables here.
    xmlHttp.open("GET","backend.php?nojs=" + document.getElementById('nojs').value + "&email=" + document.getElementById('email').value,true); 
    xmlHttp.send(null); 
  }

function backCompat() {
document.getElementById('nojs').value="false";
document.getElementById('submitspan').innerHTML='<a href="#" onClick="ajaxSubscribe();">Subscribe</a>';
}
OK I think most of the first two pages is self explanatory. In the ajax.js file, the bits between the bold italicised code is standard - as usual IE is awkward and uses different code, so we just have to work out what the browser is and use the appropriate code. Don't worry about how it works, just know it needs to go at the beginning of any Ajax function.
Hopefully the comments explain the rest of it, but let me just explain the backCompat function:
If we just made the form ajaxified, i.e. reliant on JS, we create accesibility issues for people with JS turned off - not good. So what we do is create a normal form, which can be submitted without JS, and processed like any other form. However, for people with JS on, a function runs on page load which removes the normal submit button, and replaces it with the link to our Ajax function. It also changes the "nojs" hidden field from true to false. This is in place so that we can let our PHP script know whether it's being called by an Ajax function, or if it's being used by a normal user.
It all seems a bit complex, but if you have any questions, don't hesitate to ask.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 09-22-2008, 05:33 AM
Junior Member
 
Join Date: Sep 2008
Posts: 1
Default Please help?

I am new to AJAX but I have managed to get most of what I need done with AJAX on my site; except one thing that is still eluding me.
I am using ajaxto post any new entries to the sites DB to the web page in random places (via DIVs). As I add the data to the database I get the resulting info shown on the screen via the periodicalupdater function just fine but as I add new items to the DB the old displayed data is removed and the new data is then displayed even though it is in a different location on the screen. Is there anyway to keep the old displayed data on the screen using the periodicalupdater function while adding new data using periodicalupdater? Thanks for any help in advance. PS, The data I am displaying contains unique DIV positioning coordinates. Below is the code I am using

note: prototype.js is already loaded

this is the function called

function checkping()
{
var <?php echo $holder;?> = new Ajax.PeriodicalUpdater('newPing','my.php', {method: 'post', frequency: 3.0, decay: 1});
}
</script>

this is the calling script
<script language="javascript" type="text/javascript">
checkping();
</script>

this is what is sent back to the ajaxcall via my.php. note the variables for top and left vary with each record posted.
<?php
echo
"<div style=\"position:absolute;
visibility:visible;
width:160px;
height:48px;
top:",$top_coord,"px;
left:",$left_coord,"px;
background-color:",$bgrcolor,";
border:2px solid #000000;
z-index:1\">
<img src=\"images/flags/",$flagfilename,"\" alt=\"country flag\" width=\"60\" height=\"32\" align=\"left\"><font size=\"-3\">", $usr_name, "
From: ",$country, "
", $pingText, "</font></div>";

?>



-----------------------------------------------------------------------------
outsourcing software development
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 09-24-2008, 03:43 AM
ryanhellyer's Avatar
Super Moderator
 
Join Date: Dec 2007
Posts: 711
Default

hmm, you've lost me there sorry. I don't know much about Ajax. Hopefully an Ajax expert will be along to help shortly.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -5. The time now is 08:51 AM.


Website Design by Ducani Media Group
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.