开发者

$_POST is empty when using AJAX (Prototype)

I am fairly new to PHP and I am experiencing a problem that I can't find an answer to anywhere!! It really bugs me... I want to post data to a PHP script using AJAX. I am using the JS framework Prototype to do AJAX communication.

Here is the JS code:

new Ajax.Request("/ondemand/Radio.php", {
          method: 'POST',
          parameters: {programID: id}, 
          onSuccess: function(transport) {
              开发者_运维百科  window.alert("Success, " + id);


          },
          onFailure: function() {
              window.alert("Communication problem");
          },
          onComplete: function() {
              window.alert("Complete");
          }
});

All JS is in the element...The function is called when choosing an option from a box

PHP code:

<?php 
       //Selects all programs that have a podcast
       $QUERY_SELECT_ALL_PROGRAMS   = "SELECT DISTINCT d.defnr, d.name 
                       FROM definition d, podcast p 
                   WHERE p.program = d.defnr";
       //Select podcasts that belongs to a given program
       $QUERY_SELECT_PODCASTS_FOR_PROGRAM   = "SELECT p.title, p.refnr, p.filename
                           FROM podcast p
                       WHERE program =  ?";
       //Selects all podcasts
       $QUERY_SELECT_ALL_PODCASTS = "SELECT p.refnr, p.title, p.filename, p.filename 
                            FROM podcast";

        $BROADCAST_PATH = "";

        $programID = $_POST["programID"];


/* Returns true if DB connection to server and database is OK
 * Takes mysqli as parameter
 * Connect to the database using the MySQLi API in PHP 5.x
 * This is the prefered way*/
 function DBconnection($connection) {
   $result = false;
   //Refering to $con declared eralier
   //global $connection;
   //Check DB connection
 if ($connection->connect_error) { 
           die('Connect Error: '.$connection- >connect_error); }
else {
    //Refering to $DB_NAME declared earlier
    //Select DB
      global $DB_NAME;
       $DB_selected = $connection->select_db($DB_NAME);
      if (!$DB_selected) { die ('Can\'t use : ' . $connection->connect_error); }
       else { $result = true; }
  }
  return $result;
   }

   ?>


<?php
  echo "<form>";
  echo "<select>";
  //The MySQL connection object, must be created before connection
  $con = new mysqli($MYSQL_SERVER, $MYSQL_USER_NAME, $MYSQL_PASSWORD, $DB_NAME);
if (DBconnection($con)) {
    if ($stmt = $con->prepare($QUERY_SELECT_PODCASTS_FOR_PROGRAM)) {
        $stmt->bind_param("i", $program);
        //$stmt->bind_param("i", $program);
        //$program = $_POST["programs"];
        $program = $_POST["programID"];
        $stmt->execute();
        $stmt->bind_result($title, $refnr, $filepath);
    }
    if (is_null($_POST["programs"])) {
        echo "<option>Choose a program first...</option>";
        //echo "<option>".$file."</option>";
    }
    else {
        if (is_numeric($_POST["programs"])) {
            while($stmt->fetch()) {
                print_r($title);
                //$filepath holds the value of only the name of the broadcast without the entire path
                //40 is the starposition of the name
                $filename = substr($filepath, 40);
                echo "<option value=\"".$refnr."\" id=\"".$refnr."\" onclick=\"play('".$filename."')\">".utf8_encode($title).utf8_encode($filename)."</option>";
            }
        }
    }
     $con->close();
}
echo "</select>";
echo "</form>"; 
  ?>

Here is my problem...The value of $_POST is allways "Array ()". When using a regular form that posts, everything is OK, I get the value, but when using AJAX (not only Prototype), I dont.

What i want to do simply put is: Post data with AJAX -> use recieved data in sql query -> make a HTML lement based on the result from the sql wuery..

This is kind of difficult when I don't get the POST'ed variabel

I also took a lokk at what was being sent, and POSTDATA was correct. Please, I really need someones help on this...been looking for days now for an answer..

Read this post to get a better understanding.. Same problem


I don't know if you've pasted your code in your question wrong but $var = $_POST["programID"]; doesn't appear to be in a PHP block so $var won't be assigned a value from the POST array...


I might be missing something here but what are you actually trying to do? Ajax.Request doesn't return anything by default. It is possible to use responseText to update your page but your code is making no reference to this. Looking at your code, you will not see anything updated in your page (if thats what you're expecting) but you should be getting a JavaScript alert from your onSuccess callback. If not, please confirm what callback (or if not what error) you are getting.

If you're looking to update a value in your page using AJAX then you need to look at Ajax.Updater. To be clear, if you wanted to update the ID of "p" with the output from your Ajax call you would do:

new Ajax.Updater('p', '/ondemand/Radio.php', {
  parameters: { programID: id }
});


don't know how to comment so I have to post this as a Answer. If this code is copied from your php script:

$var = $_POST["programID"];
<p id="p">
<?php 
    echo "Program ID er " . utf8_encode($var);
?>
</p>

Aren't you missing <?php and ?> around $var = $_POST["programID"];

Edited 20101028:

Okay, I had a look at your newly posted code and can't find anything obvious yet, I made some changes to it:

 <?php

 $message = "<div id=\"php_debug\";
  style=\"border:1px solid red;
          background-color: black;
          color: white;\"
  >";// this is the debug message we will build and later print out where we need it

 //Selects all programs that have a podcast
 $QUERY_SELECT_ALL_PROGRAMS   = "SELECT DISTINCT d.defnr, d.name 
   FROM definition d, podcast p 
   WHERE p.program = d.defnr";
 //Select podcasts that belongs to a given program
 $QUERY_SELECT_PODCASTS_FOR_PROGRAM   = "SELECT p.title, p.refnr, p.filename
   FROM podcast p
   WHERE program =  ?";
 //Selects all podcasts
 $QUERY_SELECT_ALL_PODCASTS = "SELECT p.refnr, p.title, p.filename, p.filename 
   FROM podcast";

 $BROADCAST_PATH = "";
 $message .= "\$_POST["programID"] = ".$_POST["programID"]."<hr />";

 $programID = $_POST["programID"];
 $message .= "\$programID = ".$programID."<hr />";

 /* Returns true if DB connection to server and database is OK
 * Takes mysqli as parameter
 * Connect to the database using the MySQLi API in PHP 5.x
 * This is the prefered way*/
 function DBconnection($connection) {
   $message .= "I am in DBconnection($connection)<hr />";
   $result = false;
   //Refering to $con declared eralier
   //global $connection;
   //Check DB connection

   if ($connection->connect_error) { 
           die('Connect Error: '.$connection- >connect_error); }
   else{
     //Refering to $DB_NAME declared earlier
     //Select DB
     global $DB_NAME;
     $DB_selected = $connection->select_db($DB_NAME);
     if (!$DB_selected) { die ('Can\'t use : ' . $connection->connect_error); }
     else{ $result = true; }
   }
   return $result;
 }

 // Start generating form
 echo "<form>";
 echo "<select>";
 //The MySQL connection object, must be created before connection
 $con = new mysqli($MYSQL_SERVER, $MYSQL_USER_NAME, $MYSQL_PASSWORD, $DB_NAME);
 if (DBconnection($con)) {
   if ($stmt = $con->prepare($QUERY_SELECT_PODCASTS_FOR_PROGRAM)) {
   $message .= "\$program = ".$program."(\$program has never been seen before in this script)<hr />";
     //$stmt->bind_param("i", $program); This line was here originally, $program is null, has never been initialized before, $programID is the var where you store $_POST data, so I changed it to below
     $stmt->bind_param("i", $programID);
     $program = $_POST["programID"];//I left this here, becaause I dont know what you use $program for
     $message .= "\$program = ".$program."(\$program has been filled with \$_POST["programID"])<hr />";

     $stmt->execute();
     $stmt->bind_result($title, $refnr, $filepath);
   }
   $message .= "\$_POST["programs"] = ".$_POST["programs"]."(\$_POST["programs"] has never been sen before)<hr />";
   if(is_null($_POST["programs"])) {
   $message .= "\$_POST["programs"] was empty so I generated \"Choose program first...\" option"<hr />";
     echo "<option>Choose a program first...</option>";
     //echo "<option>".$file."</option>";
   }elseif(is_numeric($_POST["programs"])){
   $message .= "\$_POST["programs"] was numeric so I will start a loop here:<br /> START OF LOOP <br />";
     while($stmt->fetch()) {
       print_r($title);
       //$filepath holds the value of only the name of the broadcast without the entire path
       //40 is the starposition of the name
       $filename = substr($filepath, 40);
       $message .= "\$title = ".$title." and \$filename = ".$filename."<br />";
       echo "<option value=\"".$refnr."\" id=\"".$refnr."\" onclick=\"play('".$filename."')\">".utf8_encode($title).utf8_encode($filename)."</option>";
     }
   $message .= "END OF LOOP<hr />";
   }
   $con->close();
 }
 echo "</select>";
 echo "</form>";
 $message .= "</ div>";
 echo($message);//print out the debug message we were building through out the script 
 ?>

Could you use above posted code and let us know what does it print out?

Also I would suggest you to handle all the post data at the beginning of the script doing something like this:

$var1 = $_POST["var1"];
$var2 = $_POST["var2"];
$var3 = $_POST["var3"];
$var4 = $_POST["var4"];
$var5 = $_POST["var5"];

Because that way you save yourself a lot of confusion, later and only work with simple to read variable names. For example what is $_POST["programs"]? is it same as $_POST["programID"] ?

Altogether there is a lot of confucion, at least for me with variable names:

$program
$programID
$programs
$_POST["program"]
$_POST["programs"]
$_POST["programID"]

Which ones are used? Which ones are correct?

I tend to tackle this problem by starting the name of variable with its purpose:

$id_program -> ID of a single program or row in db $txt_program -> description of program, or program txt $num_programs -> number of programs, how many programs there are(how many ids) $arr_programs -> array of programs, for example array of all program ids

Hope it helped a bit, let me know. Good luck :)


Perhaps it's bugging out and sending the request as a GET? Try:

print_r($_REQUEST);

The $_REQUEST var will contain both $_POST and $_GET vars.

I'd also find it hard to believe but is it possible that instead of method: 'POST' you should be using method: 'post' -- most Prototype examples use lowercase.


If you directly post data and the result is what you're expecting, then it's the generated HTML that's the source of your problem. This line:

 echo "<option value=\"".$refnr."\" id=\"".$refnr."\" onclick=\"play('".$filename."')\">".utf8_encode($title).utf8_encode($filename)."</option>";

is the cause of your problem. "Array()" is kind of the "toString()" version of what PHP does when arrays are concatenated to a string. $refnr is obviously an array here and Prototype simply picks up that value.

A hint: use printf('<option value="%d">%s</option>', ...) to save your eyes the sore of the leaning slash syndrome ;-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜