views:

75

answers:

4

Hi. 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

A: 

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...

Nev Stokes
$var is defined in another PHP tag within the same PHP file
A: 

Hi, 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 :)

mistrfu
Nev Stokes and mistrfu: $var is defined in another php tag within the same file
Hi, I edited the code and supplied some suggestions, hope it helps.
mistrfu
A: 

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 }
});
seengee
What i want to do is to send a variabel using POST and AJAX..I want to recieve that variabel on the serverside and use it for an SQL qury. The result for this query is used to populate a <select> element..the <p> tag that was in my code was really just for testing..the problem is still that I dont recieve the POST variabel..as I said before...i checked the HTML header..the data is there, and when i look at the html i Firebug after the post the value of the posted variabel is shown in the html code.
if you are echoing within `/ondemand/Radio.php` and you can see the variable, and you can see it being sent within Firebug then the variable IS being sent in the POST. If you want to return that variable to your page as a select menu then Ajax.Updater is ideal - output your select menu in `/ondemand/Radio.php` and set Ajax.Updater to update an ID in your page and it will populate with the menu.
seengee
I know what you meen...but, i need to use the variabel i am posting in a SQL query..if (DBconnection($con)) { if ($stmt = $con->prepare($QUERY_SELECT_PODCASTS_FOR_PROGRAM)) { $stmt->bind_param("i", $program); //$stmt->bind_param("i", $program); $program = $_POST["programID"]; $stmt->execute(); $stmt->bind_result($title, $refnr, $filepath);I am sorry that I have been so spesific about <select> boxes...it doesn't need to be a select box..I just want the value of the posted varabel so I can use it in the query...but yes, after that i want to use the query to update the page
i tried var_dump after posting..the result is null before and after POST with AJAX..note..var_dump is printed in a <p> tag using echo
please add your full code to your original question so it can be read more easily.
seengee
A: 

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.

Chad