Hafsa
Hafsa

Reputation: 105

How to create a select list with javascript and populate it with php sql?

I have a form created with javascript https://jsfiddle.net/wdLtv01x/1/ I need to populate my select list interviewer with PHP and MySQL

<div class="col-md-9">
   <div class="form-group">
       <label class="form-label" for="interviewerName">Interviewer par :</label>
       <select id="interviewerName" name="interviewerName_<?php echo $i;?>" style="width: 100%;">
        <?php foreach ($userList->getListUser() as $user):?>
             <option value="<?php echo $user->name; ?>"><?php  echo $user->name; ?></option>
        <?php endforeach; ?>
       </select>
  </div>

How can I create and populate my select list using javascript ?

Upvotes: 2

Views: 3478

Answers (2)

Hafsa
Hafsa

Reputation: 105

Here is the solution

JQuery Ajax

var elt;
$.ajax({
type: "POST",
url : "./system/ajax/select_userinfos.php",
data: { user: elt},
dataType:'json',
success: function(data) {

   var select = $("#select"), options = '';
   select.empty();      

   for(var i=0;i<data.length; i++)
   {
    options += "<option value='"+data[i].name+"'>"+ data[i].name +' '+ data[i].firstname+"</option>";    
    //console.log(options);          
   }
   select.append(options);
}
});

PHP file

require_once("../classes/UserInfos.php");
require_once '../classes/UserList.php';

$userInfos    = new UserInfos();
$userList     = new UserList();
$result = array();

foreach ($userList->getListUser() as $user){

   $result[] = array(
  'name' => $user->name,
  'firstname' => $user->firstname
);
}
echo json_encode($result);

HTML

 <select id="select"></select>

Upvotes: 0

geraldCelente
geraldCelente

Reputation: 995

Honestly speaking, I don't think composing a database query inside an HTML page is a good idea. Doing that will disclose information of your database you want not to disclose if you have security at heart.

The best approach is to store the values you want to pass to php into variables or in an array and pass that to PHP. You may choose a classic POST or an AJAX approach, as you please. Have a look at the links below for further information:

http://webcheatsheet.com/php/passing_javascript_variables_php.php

pass javascript variable to php mysql select query

http://w3schools.invisionzone.com/index.php?showtopic=48741

On the PHP side, you should do proper sanitation in order to avoid SQL-injection attacks. Please have a look at the following resourses:

How can I prevent SQL injection in PHP?

https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

http://www.codeproject.com/Articles/9378/SQL-Injection-Attacks-and-Some-Tips-on-How-to-Prev

I hope this helps.

Upvotes: 1

Related Questions