Saurabh Gupta
Saurabh Gupta

Reputation: 450

passing two variable from php to ajax then back to php

I'm new to ajax so I don't know much about ajax syntax. though i am trying here to pass variable from php to ajax and then back to php. I was able able to get it done with one variable when it came to two variables I was confused. I don't even know what to search on google to get an answer my to query. So I will be brief here's my php code. addnewbug.php

<script type="text/javascript" language="javascript" src="./javascripts/jquery.js"></script>
<script type="text/javascript" language="javascript" src="./javascripts/script.js"></script>
</head>
 <div class="margin custom">
<body bgcolor="#2e2e2e">
<div style="text-align: center; padding-top: 0px">
    <h1 style="color:white;font-size: 50px">Bughound</h1>
</div>
<div class="effect8">
    <div class="tableMargin">
        <table width="622" class="table">
            <tr class="program_row">
                <form>
                <td width="150" class="td" style="padding-right: 1.9cm">Program</td>

                    <td width="171" class="td">
                        <select id="program" class="dropdown">
                            <option></option>
                            <?php
                            require "./db.php";
                            $sql = "SELECT DISTINCT program_name FROM program";
                            $result = db($sql);
                            while ($row = $result->fetch_assoc()) {
                                $program_name = $row['program_name'];
                                echo '<option name ="' . $program_name . '">' . $program_name . '</option>';
                            }
                            ?>
                        </select>
                    </td>



                <td width="51" class="td">Release</td>
                <td width="41" >
                <div class="release" id="release">
                    <select class="release_select" id='release1'>
                    </select>
                </div>
                </td>
                <td width="103" class="td">Version</td>
                <td width="78" class="td">
                <div class="version" id="version">
                    <select class="version_select" id='program_number'>
                    </select>
                </div>
                </td>
                </form>
            </tr>
        </table>

This is the original page where I'm trying to make changes in select box using the get passing statement here's the script.js which I am using to get variable and pass it to another php program..

  $(function(){
$("#program").change(function(){
    $(".release_select").remove();
    $(".version_select").remove();
    if($("#program").val() !== "") {
        $.get("addnewbug1.php", {program_name: $("#program").val()})
            .done(function(data){
                $("div.release").after(data);
        });
        $.get("addnewbug_version.php", {program_name: $("#program").val()})
            .done(function(data){
                $("div.version").after(data);
        });
    }
});
$("#program_number").change(function(){
    $(".release_select").remove();
    if($("#program_number").val() !== "") {
        var val2 = $("#program_number").val();
         $.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
            .done(function(data){
                $("div.release").after(data);
        });
    }
});
});

The first function is working fine as it takes values from the program and pass it to addnewbug1.php which takes the program name and generate the new select boxes for release and version of it then which is replaced in div-release and division-version(or number)

this is the file where the first function work perfectly - addnewbug1.php

require "./db.php";
echo "<select class='release_select' id='release1'>";
$programname = $_GET['program_name'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'"';
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
 echo "</select>";
?> 

Now I am having error in the second change function of script.js where I need to pass two variables in '$.get' area. Also the .change fucntion for program_number is not working and it won't delete the select box on changing it.

$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})

and the addnewbug2.php is also the new file which is being used by it is -

 require "./db.php";
 echo "<select class='release_select' id='release1'><option></option>";
 $programname = $_GET['program_name'];
 $programnumber = $_GET['program_number'];
 $sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'" and program_number=' . $programnumber;

 $result1 = db($sql1);
 while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
 }
 echo "</select>";
 ?>

I don't know if you get my question or not. Thank you for replying to this question and please reply if require more info.

this is the addidtional db.php code

  function db($sql){
  //Check for connection variable already set
  if(!isset($conn)){
      //Database Connectivity - ip, username, password, database name
      $conn = new mysqli("i have filled this correctly");
  }

//Check Connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $sql);
mysqli_close($conn);
return($result);
 }

Upvotes: 0

Views: 927

Answers (4)

moh89
moh89

Reputation: 132

I have same problem as you had in this page: PHP ajax database : how to pass two variables and get data of them in different options? ,i have 2 diffrent php file,one is handling select files,the other handle the database sql,firstly i pass a value which user choosed from first select which updates the second select,and choosing second select should update third select(which is remain empty) i dont know what is my problem(i guess i send value of first ajax to the other php file,and when i get it back to use it for second ajax call,the first value will gone.

Upvotes: 0

Saurabh Gupta
Saurabh Gupta

Reputation: 450

Thank you for replying, i solved my problem using AngularJS, which i started reading after posting this question. My main moto behind this question was to populate a (2nd)select box and (3rd)select box using value from other (1st) select box and when the values in newly populate (2nd) select box was done. Then change values (3rd)select box using the (2nd) select box. Vice versa for last point. Apply unique filter to select boxes and without moving to next page. So here's the code simplified form of Addnewbug.php-

              <!DOCTYPE html>
          <html >
          <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
          <script src= "https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.js"></script>
          <body>

          <div ng-app="myApp" ng-controller="customersCtrl">

          <select ng-model="selectProgram">
          <option></option>
          <option ng-repeat="x in programes | unique: 'prognumber'" name=""{{x.progname}}"">{{ x.progname }}</option>
          </select>
          <select ng-model="selectNumber">
          <option></option>
          <option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['progrelease']:selectRelease | unique: 'prognumber'" name=""{{x.prognumber}}"">{{ x.prognumber }}</option>
          </select>
          <select ng-model="selectRelease">
          <option></option>
          <option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['prognumber']:selectNumber | unique: 'progrelease'" name=""{{x.progrelease}}"">{{ x.progrelease }}</option>
          </select> 
          </div>

          <script>
          var app = angular.module('myApp', ['angular.filter']);
          app.controller('customersCtrl', function($scope, $http) {
             $http.get("db/program_db.php")
             .success(function (response) {$scope.programes = response.records;});
          });
          </script>

          </body>
          </html>

offcourse i used some other stackexchange questions to get it right. And for the table which is being imported in this code i used this program_db-

    <?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    if(!isset($conn)){
            //Database Connectivity - ip, username, password, database name
        $conn = new mysqli("*connection parameters*");
     }
    if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
    }
    $result = mysqli_query($conn, "SELECT program_name, program_number,program_release FROM program");
    $outp = "";
    while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
        if ($outp != "") {$outp .= ",";}
        $outp .= '{"progname":"'  . $rs["program_name"] . '",';
        $outp .= '"prognumber":"'   . $rs["program_number"]        . '",';
        $outp .= '"progrelease":"'. $rs["program_release"]     . '"}';
    }
    $outp ='{"records":['.$outp.']}';
    $conn->close();

    echo($outp);
    ?> 

Upvotes: 0

Vipul sharma
Vipul sharma

Reputation: 1255

json_encode() is perfect for transport php variable with ajax

something like

//your ajax call receiver page -: your_link_for_ajax.php

    $output =     json_encode(array('type'=>'success','address'=>$address,'table_record'=>$table_record));
    die($output);

you can read it like

this code on your html page

    $.post('your_link_for_ajax', post_data, function(response){  

                    //load json data from server and output message     
                    if(response.type == 'error')
                    {
                        output = '<div class="alert alert-danger">'+response.text+'</div>';
                    }else{
                        output = '<div class=" alert alert-success">'+response.address+'</div>';
                        $('#stateIdContact').html(response.table_record);

                    }

                }, 'json');

Upvotes: 1

joy d
joy d

Reputation: 418

If I get that correctly, your initial problem is to pass more than one variable in AJAX call.

You can construct the URL like this :

var val2 = $("#program_number").val();
var val1 = $("#program").val();
$.get("addnewbug2.php?program_number="+val2+"&program_name="+val1)

Upvotes: 1

Related Questions