Link to home
Start Free TrialLog in
Avatar of peter-cooper
peter-cooper

asked on

Why is my $_POST not going to results page

Hi
I have a dilemma which I cannot seem to overcome. The scenario is I have 2 select list boxes #boxdest & #boxdest2. The aim is to populate #boxdest2 with items from #boxdest which it does successfully. However, when i send to results page for processing, #boxdest is coming through instead of #boxdest2 which holds the items. Funny thing is that #boxdest appears to be sending the correct data through which is actually in #boxdest2.

I would be grateful if someone could point out where I have gone wrong. Thanks

php code

<?php
	$conn = mysql_connect("localhost","root","");
	mysql_select_db("sample",$conn); 
	$result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}' ORDER BY custref ASC");
?>
								
	<select name="boxdest[]" id="boxdest" size="7" multiple="multiple">

<?php
	$i=0;
	while($row = mysql_fetch_array($result)) {
?>
	<option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
<?php
	$i++;
	}
?>
	</select>
          <span style="display: inline-block; width: 70px; height: 82px; padding-left: 10px; padding-right: 10px; vertical-align: top;margin-top:35px;">
          <input type="button" id="submit2" name="submit2" value=">" />
           <input type="button" id="submit3" name="submit3" value="<" />
	   </span>
	   <select name="boxdest2[]" id="boxdest2" size="7" multiple="multiple"></select>

Open in new window


jquery code

<script type="text/javascript">
	
	$(document).ready(function () {
  // initial list, as fetched from the server
  var initialList = $('#boxdest > option')
    .map(function () { return this.value; }).get();

  /**
   * @param {string} source
   * @param {string} destination
   */
  function exchangeLists(source, destination) {
    // find all selected items on the source list
    var selected = $(source + ' > option:selected');

    // move them to the destination list
    $(destination).append(selected.clone());

    // remove from the source list
    selected.remove();

    // sort the destination list
    var list = $(destination + ' > option').clone().sort(function (a, b) {
      if (initialList.indexOf(a.value) < initialList.indexOf(b.value)) {
        return -1;
      }

      if (initialList.indexOf(a.value) > initialList.indexOf(b.value)) {
        return 1;
      }

      return 0;
    });

    // replace current destination list with the sorted one
    $(destination).empty().append(list);
  }

  $('#submit2').click(function () {
    exchangeLists('#boxdest', '#boxdest2');
  });

  $('#submit3').click(function () {
    exchangeLists('#boxdest2', '#boxdest');
  });
});
</script>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

You may have a bigger problem than just jQuery.  While I look at the client-side HTML and JavaScript, take a moment to read this article!
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
Avatar of peter-cooper
peter-cooper

ASKER

Aware of that Ray. But client reluctant to update. Thanks
This is a working sample
Ray. There are issues with the code. Firstly, when I put in a submit button and send to a test page, it is sending 'suppliedMovies' and not 'accquiredMovies'. Secondly, The original items are not being removed from the list. Thanks
Avatar of Julian Hansen
First follow Ray's advice and fix your DB access

Then, you need to show us more of your code - because we can't see where the <form> for the page is defined.

I took the liberty of updating your code to MySQLi and making a few other changes.
One of the changes is to simplify your jQuery - it is not very efficient and overly complex.

Now, why your data is not coming through. The essence of it is that you are using a select box which needs something to be selected in order for it to be submitted. I am guessing you are wanting everything in the second select to be sent through - therefore all options in the second <select> must be selected on submit.

In my solution below you can see the side effect of moving one item from one box to the next will result in all the items in the right box being selected and therefore submitted. This is a side effect of doing a detach and append - the item on the left is selected so when it is detached - the data state of the item is preserved which means when it arrives on the right it is selected. As more items are added they also have a selected state - when you submit you get all the items.

The problem is as soon as you click one of the items on the right you clear all the other selected items in that box - you therefore have two options
1. Trigger a select all whenever something changes
2. Better - trigger a select all on the right box on submit - as shown below

Here is the updated code
HTML / PHP
<form action="reflect.php" method="post">
<?php
  require("connection.php");
  $result = $conn->query("SELECT * FROM `29016222` ORDER BY custref ASC");
?>
  <select name="boxdest[]" id="boxdest" size="7" multiple="multiple">
<?php
  // NOT SURE WHAT $i IS FOR BUT THIS WILL GET THE
  // TOTAL ROWS RETURNED
  $i=$conn->affected_rows;

  while($row = $result->fetch_object()) :
?>
  <option value="<?php echo $row->custref;?>"><?php echo $row->custref;?></option>
<?php

  // WHEN MIXING SCRIPT AND HTML THE : / endwhile 
  // SYNTAX MAKES IT EASIER TO SEE CODE BLOCKS
  endwhile;
?>
  </select>
  <span style="display: inline-block; width: 70px; height: 82px; padding-left: 10px; padding-right: 10px; vertical-align: top;margin-top:35px;">
    <button class="btn btn-primary switch-item" data-src="boxdest" data-dst="boxdest2">&gt;</button>
    <button class="btn btn-primary switch-item" data-dst="boxdest" data-src="boxdest2">&lt;</button>
  </span>
  <select name="boxdest2[]" id="boxdest2" size="7" multiple="multiple"></select>
  <div><input type="submit" class="btn btn-success" value="Submit" /></div>
</form>

Open in new window

jQuery
<script>
$(function() {
  // CAPTURE CLICK ON SWITCH BUTTONS
  $('.switch-item').click(function(e) {
    e.preventDefault();
  
    // GET THE src AND dst FROM CUSTOM
    // DATA ATTRIBUTES
    var src = $(this).data('src');
    var dst = $(this).data('dst');
  
    // FIND THE SELECTED <option> IN THE SOURCE <select>
    // DETACH IT AND ...
    var sel = $('#' + src + ' option:selected').detach();
  
    // APPEND IT TO THE DESTINATION <select>
    // PRESERVING STATE
    $('#' + dst).append(sel);
  });
  
  // ON SUBMIT ...
  $('form').submit(function() {
    
    // SELECT ALL OPTIONS IN THE RIGHT <select> SO
    // THAT THEY PROPAGATE THROUGH TO THE SERVER
    $('#boxdest2 option').prop({selected: true});
  });
});
</script>

Open in new window


Working sample here

EDIT Added comments to jQuery code
EDIT2 The Bootstrap classes (btn btn-primary btn-success) on the buttons can be removed without any affect on how the code runs
Julian. I am having trouble getting this to work. Could it be because I am using php 5.3.13? The problem is that #boxdest is not being populated with any data. Would appreciate your comments. Thanks
There may be better ways to do this, but I'm getting sensible results from this approach.

Lines 12-18 simulates the query and collection of the options
Lines 36-59 tried to preserve your working jQuery code as much as possible
Lines 62-68 changed the id names to something that made it easier for me to think about the problem
Lines 70-79 "submit" button click gathers up the options on the "rite" and puts them into a request to the reflector script.
Please see: https://iconoun.com/demo/temp_peter_cooper.php
<?php // demo/temp_peter_cooper.php
/**
 * https://www.experts-exchange.com/questions/29016222/Why-is-my-POST-not-going-to-results-page.html
 */
error_reporting(E_ALL);

// MAKE SURE THAT PHP WORKS WITH UTF-8
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');


// USE PHP (AND MAYBE MySQL) TO CREATE VARIABLES FOR OUR HTML
$options = <<<EOD
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Tre</option>
<option value="4">For</option>
EOD;


// CREATE OUR WEB PAGE IN HTML5 FORMAT, USING HEREDOC SYNTAX
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){

    var initialList = $('#left > option').map(function(){
        return this.value;
    }).get();

    function moveSelections(source, destination) {
        var selected = $(source + ' > option:selected');
        $(destination).append(selected.clone());
        selected.remove();

        var list = $(destination + ' > option').clone().sort(function (a, b){
            if (initialList.indexOf(a.value) < initialList.indexOf(b.value)){
                return -1;
            }

            if (initialList.indexOf(a.value) > initialList.indexOf(b.value)){
                return 1;
            }
            return 0;
        });

        $(destination).empty().append(list);
    }


    $('#moverite').click(function(){
        moveSelections('#left', '#rite');
    });

    $('#moveleft').click(function(){
        moveSelections('#rite', '#left');
    });

    $('#submitme').click(function(e){
        e.preventDefault();
        var values = $("#rite > option").map(function(){
            return $(this).val();
        }).get();

        $.post("request_reflector.php", {q:values}, function(response){
            $("#output").html(response);
        });
    });

});
</script>

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<form>

<select id="left" multiple="multiple">
$options
</select>

<input type="button" id="moverite" value="Move >>>" />
<input type="button" id="moveleft" value="Move <<<" />

<select id="rite" multiple="multiple">
</select>

<br clear="all" />
<input type="submit" id="submitme" value="Go" />
</form>

<div id="output" />

</body>
</html>
HTML5;


// RENDER THE WEB PAGE
echo $htm;

Open in new window

PHP 5.3 is kind of like MySQL.  It's severely out of date and no longer supported at all, not even for security fixes.  Current PHP versions are always to be found on the home page in the upper right-hand corner under the word "Download."
http://php.net/

Choose one of those: 5.6+ or 7+
BTW, here is the reflector script.  It often comes in handy!
<?php // demo/request_reflector.php
/**
 * Bounce the request vars back
 */
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');

// START A BUFFER TO CAPTURE THE BROWSER OUTPUT
ob_start();

// USE PREFORMATTING TO MAKE THE OUTPUT EASY TO READ
echo '<pre>';

// SHOW THE COOKIE(S)
echo '$_COOKIE: ';
var_dump($_COOKIE);
echo PHP_EOL;

// SHOW THE GET REQUEST
echo '$_GET: ';
var_dump($_GET);
echo PHP_EOL;

// SHOW WHAT WAS RECEIVED IN POST
echo '$_POST: ';
var_dump($_POST);
echo PHP_EOL;

// SHOW WHAT WAS RECEIVED IN FILES
echo '$_FILES: ';
var_dump($_FILES);
echo PHP_EOL;

// CAPTURE THE BUFFER
$request_data = ob_get_clean();

// SAY THANK YOU
$refer = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '(empty referrer)';
echo 'REQUEST REFLECTED FROM ' . $refer . ' AT ' . date('c');
echo PHP_EOL;
echo $request_data;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial