returning array in php and insert into html

Asked

Viewed 66 times

1

I have a PHP script that is returning as follows

{
  "Resultado": [
    {
      "NOMECURSO": "Administração Diurno Sede Ribeirão Preto"
    },
    {
      "NOMECURSO": "Administração Noturno Sede Ribeirão Preto"
    },
    {
      "NOMECURSO": "Agronomia Diurno Campus Ribeirão Preto"
    },
    {
      "NOMECURSO": "Arquitetura e Urbanismo Diurno Campus Ribeirão Preto"
    }
  ]
}

Now in my JS file I am recovering the date value and trying to put the result within a select in my html. more does not work

$.ajax({
    type: "POST",
    url: 'xxxx.php',
    data: {cpf: $('.cpf').val()},
    datatype: "json",
    returnType:"json",
    beforeSend: function() { $('.passo4').hide();$('.loading').show(); },
    complete: function() {  $('.loading').hide();$('.passo4').show();},
    success: function(data){

       var resultado = data;

var $select = $('#data_prova');
 $select.find('option').remove();
$.each(resultado,function(key, value)
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});     
     }
  });

More does not recover! from that error

inserir a descrição da imagem aqui

I need to put these results within a select.. Can anyone help me!

1 answer

1


There is a basic error in your AJAX: the correct is dataType ('Capital T' and not datatype. This error makes the return not a parsed JSON, but only a JSON string.

Another problem is that the return returns an array within an object Resultado, but as you attributed the data to a variable resultado, you should use resultado.Resultado in the $.each, and take the object’s key names using value.NOMECURSO:

$select.append('<option value=' + key + '>' + value.NOMECURSO + '</option>');

The code would be:

$.ajax({
 type: "POST",
 url: 'xxxx.php',
 data: {cpf: $('.cpf').val()},
 dataType: "json",
 returnType:"json",
 beforeSend: function() { $('.passo4').hide();$('.loading').show(); },
 complete: function() {  $('.loading').hide();$('.passo4').show();},
 success: function(data){

    var resultado = data;

      var $select = $('#data_prova');
       $select.find('option').remove();

      $.each(resultado.Resultado,function(key, value)
      {
          $select.append('<option value=' + key + '>' + value.NOMECURSO + '</option>');
      });     
  }
});

One tip is that instead of using $select.find('option').remove();, you could just use $select.empty(); which already empties select todo.

Another thing is, where did you find this returnType? Nor in the documentation officer jQuery has this option.

  • Thank you very much , was perfect!!!! on the returnType I saw on another topic and I put to test... thanks!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.