By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,607 Members | 1,764 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,607 IT Pros & Developers. It's quick & easy.

Ajax with PHP reflected variables

The1corrupted
100+
P: 134
Alright, I have an issue with AJAX. What I have is I have a prompt box with the option "ok" and "cancel" in javascript. I want to send the answer to that prompt off to the php script. I was just wondering if I had it coded right..

Expand|Select|Wrap|Line Numbers
  1. function ajaxFunction()
  2.   {
  3.   var xmlHttp;
  4.   try
  5.     {
  6.     // Firefox, Opera 8.0+, Safari
  7.     xmlHttp=new XMLHttpRequest();
  8.     }
  9.   catch (e)
  10.     {
  11.     // Internet Explorer
  12.     try
  13.       {
  14.       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  15.       }
  16.     catch (e)
  17.       {
  18.       try
  19.         {
  20.         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  21.         }
  22.       catch (e)
  23.         {
  24.         alert("Your browser does not support AJAX!");
  25.         return false;
  26.         }
  27.       }
  28.       if (answer) {
  29.           xmlHttp.send("POST", "answer", true);
  30.     } else {
  31.         xmlHttp.send("POST", "answer", null);
  32.     }
  33.     }
Nov 24 '07 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 173
Hi,

The request would not be sent as the code is currently incorrect. Once you have created the object that is going to be used for the XMLHttpRequest you need to open the object and then perform the send:

Expand|Select|Wrap|Line Numbers
  1. xmlHttp.open("POST","target.php",true)
  2. xmlHttp.send(data)
  3.  
The arguments for the open method are:
  1. Method - POST, GET, etc.
  2. The target URL - where the request is made to.
  3. Is the request asynchronous? Boolean

The third argument will tend to be asynchronous and, therefore, is usually true. The send method accepts one argument which is the post data for the request, is there is no data to be sent the argument is null.

While the implementation detection that you are using will work you could reduce the amount of code using object detection instead of error handling:
Expand|Select|Wrap|Line Numbers
  1.  
  2.     req=null;
  3.  
  4.     if (window.XMLHttpRequest){
  5.     //Everything but IE
  6.         req = new XMLHttpRequest();
  7.     }
  8.     else if(window.ActiveXObject){
  9.     //IE
  10.         req = new ActiveXObject("Microsoft.XMLHTTP");
  11.     }
  12.  
When the code above has executed you will have the required object to make the request. All that needs doing is checking to make sure that req is not null.

A link to a more verbose example of an AJAX request can be seen on another post at
http://www.thescripts.com/forum/thread699791.html#postmenu_2781916
Nov 24 '07 #2

The1corrupted
100+
P: 134
Quick question, what if the target page is already included in the php script? My target is "server/thispage.post.php" which is included to handle the posted data. I'm still a noob to AJAX, and haven't seen any real working examples of this code...

(simplified code)

thispage.post.php
[PHP]
$soldnumber=$_POST['soldiers'];

$soldtotal=($soldcost*$soldnumber);

echo "
<script language=\"javascript\" type=\"text/javascript\">
";
//If none of them are null but also greater than zero..
if (($soldnumber!=NULL) AND ($soldnumber>0) {
if ($soldtotal<$currmoney) {
$currmoney=($currmoney-$soldtotal);
$totals2=$totals2.$soldnumber." soldiers, ";
mysql_query("UPDATE `military` SET `soldiers`=`soldiers`+'$soldnumber' WHERE `id`='$id'");
mysql_query("UPDATE `users` SET `money`=`money`-'$soldtotal' WHERE `id`='$id'");
} else {
echo "
alert(\"Not enough for soldiers!\");
";
}
echo "
var answer=confirm(\"Comfirm Purchase for ".money_format('%n', $currmoney)."?\")
if (answer){
alert(\"Purchase Confirmed.\")
window.location = \"viewempire.php?id=".$_SESSION['user']."\";
} else {
alert(\"Purchase Canceled.\");
window.location=\"viewempire.php?id=".$_SESSION['user']."\";
}
}
";
}
echo "
</script>
";
[/PHP]
Nov 24 '07 #3

Expert 100+
P: 173
If you are using Javascript to make an asynchronous request (AJAX) then you would need to enure that the target URL is included, this can be included by just echoing it in where required.

I have knocked up a very simple example using a couple of php pages (source and target) and a javascript file.

File 1 (the one to open in your browser):
Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  5. <head>
  6. <title>AJAX Test</title>
  7. <script src="script.js" type="text/javascript"></script>
  8. </head>
  9. <body>
  10. <form id="test" action="page1.php" method="post">
  11. <h1>This is a test page to show an AJAX request.</h1>
  12. <p>The slow button below will send an asynchronous request to a page which uses sleep() to mock a long running process. The value in the textbox
  13. is the number of seconds to sleep for.</p>
  14. <p><label>Duration: <input type="text" name="txtDur" id="txtDur" value="5" /></label></p>
  15. <p><label>Make Asynch: <input type="checkbox" name="chkAsynch" id="chkAsynch" checked="true" /></label></p>
  16. <p><input type="submit" name="btnSub" id="btnSub" value="Slow" /></p>
  17. <p><a id="responsive" href="#">Click to test responsive</a></p>
  18. <div id="res"></div>
  19. </form>
  20. </body>
  21. </html>
  22.  
This is just static HTML, the form would post back to the same page if javascript is not enabled or working correctly.

File 2 (the page the request is made to):
Expand|Select|Wrap|Line Numbers
  1. Start Time:
  2. <?php
  3. // current time
  4. echo date('h:i:s');
  5. ?>
  6. , Finish Time:
  7. <?php
  8. // sleep for 10 seconds
  9. sleep($_POST["duration"]);
  10. // wake up !
  11. echo date('h:i:s');
  12. ?>
  13.  
Javascript
Expand|Select|Wrap|Line Numbers
  1.  
  2. // The request object
  3. var $req;
  4.  
  5. // Function that makes the AJAX request.
  6. function makeRequest($duration){
  7.  
  8.     $req=null;
  9.  
  10.     if (window.XMLHttpRequest){
  11.         //Everything but IE
  12.         $req = new XMLHttpRequest();
  13.     }
  14.     else if(window.ActiveXObject){
  15.         //IE
  16.         $req = new ActiveXObject("Microsoft.XMLHTTP");
  17.     }
  18.     if ($req!=null){
  19.  
  20.        // Build the post data.
  21.        var $post = "duration=" + $duration;
  22.  
  23.        // Set the target.
  24.        var $url="target.php";
  25.  
  26.        // Set whether asynch
  27.        var $isAsynch = document.getElementById("chkAsynch").checked;
  28.  
  29.        // Set function that handles the change of state of the request.
  30.        $req.onreadystatechange=state_Change;
  31.  
  32.        // Open the request.
  33.        $req.open("POST",$url,$isAsynch);
  34.  
  35.        // Set the header details.
  36.        $req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  37.        $req.setRequestHeader("Content-length", $post.length);
  38.  
  39.        // Send the request
  40.        $req.send($post);
  41.     }
  42. }
  43.  
  44. // Handles the changing states of the request.
  45. function state_Change(){
  46.     // if xmlhttp shows "loaded"
  47.    if ($req.readyState==4){
  48.     // if "OK"
  49.         if ($req.status==200){
  50.             var $response;
  51.             $response=$req.responseText;
  52.             showResponse($response);
  53.         }
  54.     }
  55. }
  56.  
  57. // Displays the result.
  58. function showResponse($res){
  59.   var $ph = document.getElementById("res");
  60.  
  61.   // If the results placeholder has any content clear it.
  62.   clearChildren($ph);
  63.  
  64.   var $txtRes = document.createTextNode($res);
  65.   $ph.appendChild($txtRes);
  66. }
  67.  
  68.  
  69.  
  70. // Adds a window.onload event. This is used so that any 
  71. // pre-existing onload functions are not overwritten.
  72. function addLoadEvent(func) {
  73.   var oldonload = window.onload;
  74.   if (typeof window.onload != 'function') {
  75.     window.onload = func;
  76.   } else {
  77.     window.onload = function() {
  78.       if (oldonload) {
  79.         oldonload();
  80.       }
  81.       func();
  82.     }
  83.   }
  84. }
  85.  
  86. function clearChildren($obj){
  87.   if ($obj.childNodes.length > 0){
  88.     for(var i=$obj.childNodes.length - 1;i>=0;i--){
  89.         var $child = $obj.childNodes[i];
  90.         $obj.removeChild($child);
  91.     }
  92.   }
  93. }
  94.  
  95. function wireup(){
  96.  
  97.   // Add function to the submit button.
  98.   var $btn = document.getElementById("btnSub");
  99.   $btn.onclick = function(){
  100.  
  101.     var $res = document.getElementById("res");
  102.     clearChildren($res);
  103.  
  104.     var $running = document.createTextNode("Running...");
  105.     $res.appendChild($running);
  106.  
  107.     var $dur= document.getElementById("txtDur").value;
  108.     makeRequest($dur);
  109.     // Return false to stop form submitting.
  110.     return false;
  111.   }
  112.  
  113.   // Add function to responsive test.
  114.  var $a = document.getElementById("responsive")
  115.  $a.onclick = function(){alert("responsive"); return false;}
  116. }
  117.  
  118. addLoadEvent(wireup);
  119.  
You should be able to compare an asynchronous request, page is totally responsive, and a synchronous request, page is frozen until request completes.
Nov 25 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.