Pass to other php script?

OK, I have a routine that uses ajax (which I barely understand) to get dynamically the name of a show and put in a dropdown box using the dates in a database. Now, once the user gets the year of the show and the name of the venue, then it needs to be submtted to another php script to get the images (those come later). So, how do I accomplish this with javascript/ajax?

the script is here

<?php

    session_start();
    include_once(getRootPath(). 'inc/db_connect_PDO2.php');
    
    $db = get_db_connection();
    
    $result = $db->prepare('SELECT DISTINCT(Show_Year) FROM Show_Pix ORDER BY Show_Year DESC');
    $result->execute();
    
    // returns the relative path from current folder to Web Site Root directory
    function getRootPath() {
      $current_path = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME);
      $current_host = pathinfo($_SERVER['REMOTE_ADDR'], PATHINFO_BASENAME);
      $the_depth = substr_count( $current_path , '/');

      // Set path to root for includes to access from anywhere
      if($current_host == '127.0.0.1') $pathtoroot = str_repeat('../' , $the_depth-1);
      else $pathtoroot = str_repeat ('../' , $the_depth);

      return $pathtoroot;
    }
?>

<html>
<head>
<title>Roshan's Ajax dropdown code</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 <script>
function getXMLHTTP() { //fuction to return the xml http object
        var xmlhttp=false;    
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {        
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }
             
        return xmlhttp;
    }
    
    
    
    function getName(strURL) {        
        
        var req = getXMLHTTP();
        
        if (req) {
            
            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('showName').innerHTML=req.responseText;                        
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }                
            }            
            req.open("GET", strURL, true);
            req.send(null);
        }
                
    }
</script>




</head>

<body>

<form method="post" action="PicCapEdit.php?showYear=<?=$_POST['showYear']?>&showName=<?$_POST['showName']?>" name="form1">
<div width="60%" border="0" cellspacing="0" cellpadding="0">
  <div style="clear:both;">
    <div width="150" style="float:left;">Show Year&nbsp;&nbsp;&nbsp;&nbsp;</div>
    <div  width="150" style="float:left" ><select name="showYear" onChange="getName('findname.php?showName='+this.value)">
        <option value="">Select Show Year</option>
        <? while ($row = $result->fetch(PDO::FETCH_ASSOC)){ ?>
        <option value=<?=$row['Show_Year'] ?>><?=$row['Show_Year'] ?></option>
        <? } ?>

        </select></div>
  </div>
  <div style="clear: both;">
    <div width="150" style="float:left;">Show Name&nbsp;&nbsp;</div>
    <div style="float:left;"><div id="showName" style="float:left;"><select name="showName">
    <option>Select Show Name</option>
        </select></div></div>
  </div>
  <div>
    <div>&nbsp;</div>
    <div>&nbsp;</div>
  </div>
  <div>
    <div>&nbsp;</div>
    <div>&nbsp;</div>
  </div>
</div>
  <input type="Submit" name="Form1_Submit" value="Submit">
</form>
</body>
</html>

Hi,

What exactly do you “barely understand”?
Is it the AJAX part of things (i.e. how a web page can communicate with a server to fetch data)?
If so, I would strongly recommend investing a little time and reading up on the basics.
Here’s a good tutorial: http://learn.jquery.com/ajax/

Have a read of that, then let us know if you run into any problems.

OK, my new attempt. However, since the first scripts (PicEditStart.php) is using ajax to call a second php script (findname.php) to fill in the second dropdown, I am not sure how the PostData function of ajax will work to send to the script PicEditCaption.php file. I tried (as seen in the PicEditStart2.php file) but no data comes back.

When I run the first script, then click submit, the first script is “re-started”, in other words, I don’t see the passed script being used. Maybe I am missing something but…

So, help me out please.

PicEditStart.php (updated)

<?php

    session_start();
    include_once(getRootPath(). 'inc/db_connect_PDO2.php');
    
    $db = get_db_connection();
    
    $result = $db->prepare('SELECT DISTINCT(Show_Year) FROM Show_Pix ORDER BY Show_Year DESC');
    $result->execute();
    
    // returns the relative path from current folder to Web Site Root directory
    function getRootPath() {
      $current_path = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME);
      $current_host = pathinfo($_SERVER['REMOTE_ADDR'], PATHINFO_BASENAME);
      $the_depth = substr_count( $current_path , '/');

      // Set path to root for includes to access from anywhere
      if($current_host == '127.0.0.1') $pathtoroot = str_repeat('../' , $the_depth-1);
      else $pathtoroot = str_repeat ('../' , $the_depth);

      return $pathtoroot;
    }
?>

<html>
<head>
<title>Dropdown code test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script>
function getXMLHTTP() { //fuction to return the xml http object
        var xmlhttp=false;    
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {        
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }
             
        return xmlhttp;
    }
    
    
    
    function getName(strURL) {        
        
        var req = getXMLHTTP();
        
        if (req) {
            
            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('showName').innerHTML=req.responseText;                        
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }                
            }

            req.open("GET", strURL, true);
            req.send(null);
        }
                
    }
    
    function PostData() {
        // 1. Create XHR instance - Start
        var xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        else {
            throw new Error("Ajax is not supported by this browser");
        }
        // 1. Create XHR instance - End
        
        // 2. Define what to do when XHR feed you the response from the server - Start
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status == 200 && xhr.status < 300) {
                    document.getElementById('showName').innerHTML = xhr.responseText;
                    var showName = document.getElementById("showName").value;
                }
            }
        }
        // 2. Define what to do when XHR feed you the response from the server - Start

        var showName = document.getElementById("showName").value;
        var showYear = document.getElementById("showYear").value;
alert("show name: " + showName);
alert("show year: " + showYear);
        var queryString = "?showYear=" + showYear + "&showName=" + showName;
        // 3. Specify your action, location and Send to the server - Start 
        // xhr.open('POST', 'PicCapEdit.php'?);
        xhr.open("GET", "PicCapEdit.php" + queryString, true);
        // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(null);
        // 3. Specify your action, location and Send to the server - End
    }
</script>




</head>

<body>

<form method="post" name="form1">
<div width="60%" border="0" cellspacing="0" cellpadding="0">
  <div style="clear:both;">
    <div width="150" style="float:left;">Show Year&nbsp;&nbsp;&nbsp;&nbsp;</div>
    <div  width="150" style="float:left" ><select name="showYear" onChange="getName('findname.php?showName='+this.value)">
        <option value="">Select Show Year</option>
        <? while ($row = $result->fetch(PDO::FETCH_ASSOC)){ ?>
        <option value=<?=$row['Show_Year'] ?>><?=$row['Show_Year'] ?></option>
        <? } ?>

        </select></div>
  </div>
  <div style="clear: both;">
    <div width="150" style="float:left;">Show Name&nbsp;&nbsp;</div>
    <div style="float:left;"><div id="showName" style="float:left;"><select name="showName">
    <option>Select Show Name</option>
        </select></div></div>
  </div>
  <div>
    <div>&nbsp;</div>
    <div>&nbsp;</div>
  </div>
  <div>
    <div>&nbsp;</div>
    <div>&nbsp;</div>
  </div>
</div>
  <input type="Submit" name="Form1_Submit" value="Submit" onclick="PostData()">
</form>
</body>
</html>

findname.php script

<? $showName=$_REQUEST['showName'];

    include_once(getRootPath(). 'inc/db_connect_PDO2.php');
    
    $db = get_db_connection();
    
    $result = $db->prepare('SELECT DISTINCT(Show_Name) FROM Show_Pix WHERE Show_Year = :showName');
    $result->bindValue(':showName',$showName);
    $result->execute();


?>
<select name="showName">
<option>Select Show Name</option>

<? while($row = $result->fetch(PDO::FETCH_ASSOC)) { ?>
<option value><?=$row['Show_Name']?></option>
<? } ?>
</select>
<?php
// returns the relative path from current folder to Web Site Root directory
function getRootPath() {
  $current_path = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME);
  $current_host = pathinfo($_SERVER['REMOTE_ADDR'], PATHINFO_BASENAME);
  $the_depth = substr_count( $current_path , '/');

  // Set path to root for includes to access from anywhere
  if($current_host == '127.0.0.1') $pathtoroot = str_repeat('../' , $the_depth-1);
  else $pathtoroot = str_repeat ('../' , $the_depth);

  return $pathtoroot;
}
?>

and finally, PicCapEdit.php (to display the selected items to be passed, hopefully)

<?php
session_start();
/*
    Routine PicCapEdit.php
    used to display the pictures, allow user to click on one, popup an edit box to add/edit the caption for that 
    picture, save/cancel that and continue to show the pictures.  There should be a Return button to close out the
    routine and return to the start screen (TBD at this time).  RHE 20141103
*/

// first get the information passed:
//    should be a show year (numeric)
//    then the name (alpha)

$showYear = $_REQUEST['showYear'];
$showName = $_REQUEST['showName'];

// for testing, just echo out these

echo 'Show year passed and recieved: ' . $showYear . '<br>';
echo 'Show name passed and recieved: ' . $showName . '<br>';

/*  
    end of PicCapEdit.php routine
*/
?>

I think you’re confusing concepts.

You should have one HTML page (this can be HTML rendered via PHP).
The AJAX requests should be submitted from this page, to one (or more) server-side (PHP) scripts, which can then return a response (after fetching data from a database table, for example) to be inserted into your original page.

So, let’s start with that.
What does the HTML (not PHP) of your original page look like?
I imagine that it contains at least one select element.

You can go to this site and see how the page is rendered via the php script. It actually has two select statements (one for the years that is derived from the distinct years in the table) and one derived from the selection of the first to get the distinct venue name from the table. Hope this is clear.

Does this help?

Ok, so on that page you have two selects.
When you select “Show Year” it seems to populate “Show name” according to the year selected.
What should happen after that?

What I am hoping will happen is the the user clicks the Submit button and then the selections are passed to the script PicEditCap.php (code in post #4 above) and be displayed. In the javascript area (ajax?) I have the function PostData that should build the “query” and append that to a call to the script.

I am only just trying to test my ability to learn how to pass those values from the main script to the final one for display. Make sense?

E

A bit more, but let’s back up a little.

So, the user selects a year in the “Show Year” select and the “Show name” select is populated.
The user then selects a name in the second select and presses submit.
The values from both selects are then be passed to a second PHP script (PicEditCap.php) via AJAX.
This script should then do what?
It doesn’t actually get rendered, so it cannot “display” anything. If you want to render a new page at this point, you should just submit the form, as is.
The second script (PicEditCap.php) can do things like manipulate the data, or fetch values from a database, but it will need to return a value to your original page (the one with the two selects), which your original page can then display (for example).

OK, first, thanks for staying with me on this. Still understanding how and when to use the ajax.

Second, right now I was just trying to use the PicEditCap.php file to echo out that the values got passed to it, but, as one can see, that did not work as I was hoping

Last, I think I am maybe not doing a great job of explaining, which I tend to do.
So, the PicEditCap.php script should eventually select (fetch) all the pictures based on the year and name that would hopefully be passed to it. Remember, that the name is populated via once again another php script.

Now, that being said, I am not sure how to get the values into this script (PicEditCap.php - yet again another script, the 3rd in this chain so to speak) so I can use the mysql select statement to get those pictures from the database.

Thanks once again for sticking with me on this.

Ajax is used when your page needs to retrieve information from the server and you want to do it without having to reload the web page.

OK, understood. So, that would work nicely for what I want for the main page. BUT, now that the user has selected what they want, how does the script pass that on to another page for use in retrieving data from the database? That is what I don’t get.

There are two ways for web pages to pass information to the server - they can use GET or they can use POST.

GET is used when you are sending a request to retrieve data without changing it. POST should be used when youwant to change something on the server.

These are used either when you send a request to load a new web page or using Ajax to request information without reloading the page. The two request types are the same whether Ajax is used or not.

When you simply link to another page the request uses GET and the values to be passed come after the ? in the address you are requesting. To send a POST request without using Ajax you need to create a form and submit that to the server using method=“POST”

OK, can you look at my post #4, PicEditStart.php and see if I am at least in the ballpark for using ajax/javascript to call on another script to use the second script to get the information that should be passed to it for querying my database for information?

Thanks

Use a form.

Here’s a simple demo.

On the first page, the second select element is populated via AJAX.
This is done by attaching an event handler to the first select element and sending an AJAX request to ajax.php any time the first select’s value changes.

I have wrapped both selects and the submit button in a <form> tag.

<form action="submit.php" method="post">
  ...
</form>

Now, when the user is done making their choices and they click submit, the form values are submitted to a second PHP script (submit.php). This is a normal form submission. The page refreshes (the url changes) and no AJAX is involved.

In submit.php you are then free to do what you want with the values that you receive.

Here’s the code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>AJAX test</title>
  </head>
  <body>
    <form action="submit.php" method="post">
      <p>
        <label for="show_year">Show Year:
          <select id="show_year" name="show_year">
            <option value="">Select year</option>
            <option value=2014>2014</option>
            <option value=2013>2013</option>
            <option value=2012>2012</option>
            <option value=2011>2011</option>
            <option value=2010>2010</option>
          </select>
        </label>
      </p>
      <p>
        <label for="show_name">Show Name:
          <select id="show_name" name="show_name"></select>
        <label>
      </p>
      <button>Submit</button>
    </form>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      $("#show_year").on("change", function(){
        $.ajax({
          type: "POST",
          url: "ajax.php",
          cache: false,
          data: { "show_year": $("#show_year").val() },
          success: function (response){
            console.log(response);
            $("#show_name").html(response);
          }
        });
      });
    </script>
  </body>
</html>

ajax.php

<?php
$show_year = $_POST["show_year"];

// You now have the value submitted via AJAX stored in the $show_year variable.
// You would normally use it to do some database stuff
// Then echo the result
// In this case, I'll just return a few option tags
//
echo "
<option value='name_one'>Name one</option>
<option value='name_two'>Name two</option>
<option value='name_three'>Name three</option>
<option value='name_four'>Name four</option>
";

submit.php

<?php
print_r($_POST);

Does that help?

OK, I am starting to see some daylight through the fog. I see that the ajax you used in the example (via jquery) is only updating the current page. I see what I thought was the correct method to send data to the next page is now not correct - you still have to use the form tag and open that page from the POSTed data. I am going to see how I can now use this in my scripts.

Thanks

1 Like

Now you’re getting it!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.