user6757446 user6757446 - 1 month ago 8
Javascript Question

Adding input options generated from backend

I have a little problem with this code included beneath. This is function of library called Sweet Alert 2. I'd like to have "inputOptions" loaded from php

Code I have right now:

function pick(){
swal({
title: 'Choose country',
input: 'select',
inputOptions: {
'SRB': 'Serbia',
'UKR': 'Ukraine',
'HRV': 'Croatia'
},
inputClass: 'form-control select',
confirmButtonColor: '#78339b',
inputPlaceholder: 'choose country',
showCancelButton: true,
}).then(function(result) {
swal({
type: 'success',
html: 'You selected: ' + result
})
});
}


I'd like to have part with input Options like this:

<?php
$ct = mysql_query("SELECT * FROM db WHERE typ = 1",$link);
while($row = mysql_fetch_array($ct)){
echo $row['id'] : $row['country'];
}
?>


I know this won't work but you know what I mean. Can someone actually help me? I would genuinely appreciate any tips on how to do this

Answer

you can get your options by sending request via $.post in jQuery to your php file :

function pick(){
$.post("option.php", {options: options}, function(result){
        if(result){
swal({
  title: 'Choose country',
  input: 'select',
  inputOptions: result,
  .
  .
  .

 });
}
....

for php file should be like this:

// you can get the data you need by senting option to your page $_POST['options']    
$ct = mysql_query("SELECT * FROM db WHERE typ = 1",$link);           
    while($row = mysql_fetch_array($ct)){
        $data[$row['id']] = $row['country'];
    }
    echo json_encode($data);
Comments