1

I am trying to get 3 sets of checkbox values from 3 checkbox menus. Note one checkbox menu has values generated using PHP/SQL. Also note that I have no <submit> button on purpose. I want those checkbox values as soon as the user checks them - not on a submit event.

Ultimately i want those sets of values to be in their own individual PHP variable each and I want them to be used on the same page. I have read that its best to use AJAX to convert those JS values into variables in PHP. And so I have built the following so far:

<form id="numberOrderForm" action="index.php" method="POST">
    <div class="wrappers" id="multi-select1Wrapper">
        <h2>Area Code</h2>
        <select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
            <?php
                //The query asking from our database
                $areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
                                FROM `AreaCodes` ac";                                                               //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'

                $areaCodeResults = $conn->query($areaCodeSQL);                                                      // put results of SQL query into this variable

                if ($areaCodeResults->num_rows > 0) {                                                               // if num_rows(from $results) is greater than 0, then do this:
                    // output data of each row
                                foreach($areaCodeResults as $areaCodeResult)                                        //for each item in $areCodeResults do this:
                                    {
                                        $areaNameAndCode =  $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName'];  //get AreaCode and AreaName from query result and concat them
                                        $areaName = $areaCodeResult['AreaName'];                                    // get AreaName
                                        $areaCode = $areaCodeResult['AreaCode'];                                    //get AreaCode

                                        ?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>"  ><?php echo $areaNameAndCode; ?></option><?php  //Create this option element populated with query result variables
                                    }
                } 

            ?>
        </select>
    </div>       




    <div class="wrappers" id="multi-select2Wrapper">
        <h2>Number Type</h2>
        <select class="dropDownMenus" id="multi-select2" name="multi_select2[]" multiple="multiple">
            <option class="menuoption2" name="package" value="gold">Gold</option>
            <option class="menuoption2" name="package" value="silver">Silver</option>
            <option class="menuoption2" name="package" value="bronze">Bronze</option>
        </select>
    </div>

    <div class="wrappers" id="multi-select3Wrapper">
        <h2>Order</h2>
        <select class="dropDownMenus" id="multi-select3" name="multi_select3[]">
            <option class="menuoption3" value="sequential">Sequential</option>
            <option class="menuoption3" value="random">Random</option>
        </select>
    </div>  
 </form>

I then have my AJAX requests set up - one per checkbox menu, since ultimately I want 3 PHP variables. Each make an AJAX request and if successful shows a basic alert box containing those checkbox values within. And here they are:

<script>
$(function(){
   $("#multi-select1").change(function(e){
        var areaCode = $("#multi-select1").val();
        $.ajax({
            type: 'post',
            url: '/index.php',
            dataType: 'text',
            data: 'areacode=' +areaCode,
            success: function(d){
                if (d.length) alert(d);
            }
        });         
    }); 


    $("#multi-select2").change(function(e){
        var numberOrder = $("#multi-select2").val();
        $.ajax({
            type: 'post',
            url: '/index.php',
            dataType: 'text',
            data: 'numberorder=' +numberOrder,
            success: function(d){
                if (d.length) alert(d);
            }
        });         
    }); 

     $("#multi-select3").change(function(e){
        var order = $("#multi-select3").val();
        $.ajax({
            type: 'post',
            url: '/index.php',
            dataType: 'text',
            data: 'order=' +order,
            success: function(d){
                if (d.length) alert(d);
            }
        });         
    }); 

}); //end ready  

So far so good. Those alert boxes contain the right values. My console also is ...index.php?areaCode=*value,value* upon making the POST request so that seems in order too. And so I'd imagine I would be able to echo out values that have been POSTED like this:

<div>
    <?php
        if(isset($_POST['areaCode'])){
                $ac = $_POST['areaCode'];

                foreach($ac as $value){
                        echo $value;    
                }
        }
    ?>
</div>

But nothing happens. Can anyone help?

Liam
  • 156
  • 9
  • You can start by showing the data that _is or is not being returned_ in your javascript `function(response){ alert(areaCode); });` wont cut it but `function(response){ alert(response); });` **JUST MIGHT** – RiggsFolly May 18 '16 at 15:19

1 Answers1

1

First, the response varname must be used both in the function() param and in the function itself. See below revisions.

<script>
    $(function(){
        $("#multi-select1").change(function(e){
            var areaCode = $("#multi-select1").val()
                $.post("index.php?areaCode="+areaCode, function(dude){
                  alert(dude);
                });        
           });           


        $("#multi-select2").change(function(e){
            var numberType = $("#multi-select2").val()
                $.post("index.php?numberType="+numberType, function(obama){
                  alert(obama);
                });        
           });           


        $("#multi-select3").change(function(e){
            var order = $("#multi-select3").val()
                $.post("index.php?order="+order, function(response){
                  alert(response);
                });        
            });           
    });
</script>

Secondly, you might find it easier to use the full $.ajax() format rather than the shorthand form $.post(). They are the same method, but the full form is easier to use until you get the hang of things. Note that $.post(), $.get() and $.load() are all shorthand forms of $.ajax()

var varvalue = "some text";
var area = $('#area').val();
$.ajax({
    type: 'post',
     url: 'another_php_file.php',
    data: 'request=' +area_code_lookup+ '&area=' +area+ '&varname=' +varvalue,
    success: function(d){
        if (d.length) alert(d);
    }
});

another_php_file.php

<?php
    $request = $_POST['request'];
    $recd = $_POST['varname'];

    if ($request == 'area_code_lookup'){
        $area = $_POST['area'];
        //$area_loc = do a MySQL Lookup
        $out = '<div class="row">';
        $out .= 'Location: ' .$area_loc;
        $out .= '</div><!-- .row -->';
        echo $out;
    }else if ($request = 'something_else'){
        echo 'PHP side received: ' .$recd;
    }else if ($request = 'something_else'){
        echo 'Do a MySQL lookup, build HTML, and echo it back';
    }
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • @Liam You might also find the examples referenced in [this post](http://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery/17974843#17974843) to be helpful. Note that a common newbie error is to try to send AJAX to the same PHP file that is sending the AJAX - see [this post](http://stackoverflow.com/questions/17529509/values-not-updated-after-an-ajax-response/17530014#17530014) – cssyphus May 18 '16 at 16:47
  • Ah thank you for your help, but can i ask? If I have sent that data to 'another_php_file.php' - do i then need to use AJAX send that data back to 'index.php' (my original page) so it can be shown there. Also that data that I do send to 'another_php_file.php' - is that a string or some other type of data? I ultimately need to send that data to the back end for a query to be made using that data, my back end team need a string or that data within a PHP variable for their work. Having it on show on the same page is merely a test to make sure that data is in the right format for them to work with – Liam May 23 '16 at 08:19
  • Whatever the PHP side echos back (using the `echo` command) -- and I mean *anything*: HTML, text string, `echo json_encode($phpArray);` -- will be received on the other side as the variable named `success: function(here)`. It's really that easy. Try experimenting. Try `alert(here)` *(if here was the name defined in the success function param)* – cssyphus May 23 '16 at 13:47
  • Ok that makes sense so far and I have edited above, but are you saying its not possible to use AJAX to make a JS variable into a PHP variable without a `another_php_file.php`? I get the web pages code in that `alert` box now. However in Firebug within the console and its info about the request I can see within the 'Param' tab I see those values checked in my checkbox. Also I tried to change it to `index.php` and use this on the same page since it is my aim ultimately: `
    ` It didn't work though.
    – Liam May 23 '16 at 15:05
  • bah - not 'Param' tab - 'Post' tab! sorry :/ – Liam May 23 '16 at 15:14
  • Sadly, you cannot post AJAX to the same PHP file - [see this answer](http://stackoverflow.com/questions/17529509/values-not-updated-after-an-ajax-response/17530014#17530014). It was on my wishlist also, but a no go. However, you can have a single AJAX file that handles all of your AJAX calls -- just add another variable that identifies the AJAX call (e.g. `data: request=send_contact_email&name=bob&email=etc`) – cssyphus May 23 '16 at 15:48
  • The way that you update the current page based on data received back from PHP via AJAX is to parse the `here` variable *(I will call it "bob" in my next example)* and manually code what you want done. It's a bit of work, but once done it works like a hot darn. ***Or,*** while still on the PHP side you can build the HTML you want displayed and echo that entire HTML string. Back on the original page you then paste it into a div, again using the defined variable name: `success: function(bob){ $('#areaState').html(bob); }` – cssyphus May 23 '16 at 16:29