سؤال

I need to populate related selects with data from the database. The HTML page has a select with id 'fontes' and a select with id 'cargos'. The jQuery code right now:

$("#fontes").change(function () {
  $.ajax({
    type: "POST",
    url: "json_cargos_fonte.php",
    data: ({fonte: $("#fontes").val()}),
    dataType: "json",
    success: function(json){
      var options = "";
      $.each(json, function(key, value){
        options += '<option value="' + key + '">' + value + '</option>';
      });
      $("#cargos").html(options);
    }
  });
});

And the content of json_cargos_fonte.php:

<?php
include ("conexao.php");
header('Content-type: text/json');
$fonte = $_POST['fonte'];
$retorno = array();
$queryCargos = "SELECT * FROM `cargos` WHERE `fonte` = '$fonte' ORDER BY `cargo`";
$resultCargos = $mysqli->query($queryCargos) or trigger_error($mysqli->error."<br>[ $queryCargos]");
while ($row = $resultCargos->fetch_object()) {
    $retorno[] = $row->cargo;
}
echo json_encode($retorno);
?>

I already tested putting a manual value instead of '$fonte' and it worked, but passing the value selected in fontes does not work. No option appears, beyond the default option I wrote in the HTML:

<select id="cargos" name="cargos" style="min-width: 250px;">
  <option>Selecione um Cargo</option>
</select>
هل كانت مفيدة؟

المحلول 3

Alerted value of the select inside the jQuery change function and saw it added a '\' to the end of the string. So, e.g., InfoJobs appeared as InfoJobs\

Solution:

var fonte = $("#fontes").val();
var fonteNew = fonte.replace("\\","");

Then, inside $.ajax:

type: "GET",

and

data: {fonte: fonteNew},

In the PHP file, changed from POST to GET.

نصائح أخرى

if you want to obtain selected value with jquery, try this

$("#fontes option:selected").val();

In order for this line to work:

$fonte = $_POST['fonte'];

You'll need to serialize your data in your ajax call:

data: $.serialize({fonte: $("#fontes").val()}),
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top