0

Form.php

echo("<div id='myDv'>");
echo("<select id='mySelect'>");
   echo("<span id='mySpan'>");

        //here I want dynamically generated option values

   echo("</span>");
echo("</select>");
echo("</div>");

myJquery.js

$.post('Process.php', $(this).serialize(), function(data){

      $('#mySpan').html(data);// I tried, but does'nt work

}).fail(function() {alert( "Some Problem Occured" );});

Process.php

$strSql="SELECT Id, Title FROM mytable";
$result=mysql_query($strSql);
while($rowSet=mysql_fetch_array($result)) {
    echo("<option value=".$rowSet['Id'].">".$rowSet['Title']."</option>");
}

My requirement is to use the Id and Title obtained in Process.php, to create select options that will be displayed in the Form.php.

What changes are required in my code? How can I access the $rowSet of Process.php in myJquery.js, to create the select options, that I want to display in Form.php

Sajjad
  • 123
  • 1
  • 8
  • Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[a Kitten is strangled somewhere in the world](http://2.bp.blogspot.com/-zCT6jizimfI/UjJ5UTb_BeI/AAAAAAAACgg/AS6XCd6aNdg/s1600/luna_getting_strangled.jpg)** it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Nov 16 '16 at 16:29
  • Why don't you just json encode the data from server side then Put it back into select onchange Event of jquery or javascript . – Hassan ALi Nov 16 '16 at 16:34

1 Answers1

0

Server Side Processing

File Name:Process.php

First we fetch Data using same query as you have written above

$data=array();
$strSql="SELECT Id, Title FROM mytable";
$result=mysql_query($strSql);
while($rowSet=mysql_fetch_array($result)) {
   $option=array("id"=>$rowSet["Id"],"Title"=>$rowSet["Title"]);
   $data[]=$option;
}
echo json_encode($json_data);

Client Side Processing I am using jquery and its change event.I am looping json encoded data to extract Id and Title from them.

    <select id="getOptions"></select>
    <script>
    $("#getOptions").change(function(e){
     $.ajax({
        url:"Process.php",
        success:function(data){
        console.log(data);
       for(var i=0;i>=data.length;i++){
        $("#getOptions").append("<option value='"+data[i]["Id"]+"'>"+data[i]["Title"]+"    </option>");
       }
      },
    error:function(err){
     alert(err);
      }
    });
});
    </script>
Hassan ALi
  • 1,313
  • 1
  • 23
  • 51