473,396 Members | 1,927 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Ajax with PHP reflected variables

The1corrupted
134 100+
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
3 1709
phvfl
173 Expert 100+
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
134 100+
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
phvfl
173 Expert 100+
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

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

Similar topics

5
by: aroraamit81 | last post by:
I am using AJAX, it works very fine.............. But the problem is my back end aspx page does not get refreshed rather it picks old values now when I execute the aspx page explictly then the...
6
by: =?Utf-8?B?U2hhd24gU2VzbmE=?= | last post by:
Greetings! I was researching AJAX to provide a solution to displaying status messages while a long process executed. I found several examples online and was able to use their code to get a quick...
3
by: radix | last post by:
Hello, I have a aspx page with ajax scriptmanger update panel etc. I also have public string variables on the aspx page. Whenever postback happens from Ajax update panel, at server side all...
5
by: quirk | last post by:
I am trying to write a script where a page is populated with some maths questions, user answers them (it's timed but I've left this bit out), gets results on same page and ajax takes their score,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.