Take json array in ajax

Asked

Viewed 55 times

-2

Good afternoon, I have a problem to display the result in the json, I do an Insert of an array in the database with for, it inserts perfect in the database, but I’m not able to display the successful response in the json. My ajax is like this:

var recuperarResultado = function(){

    $('.btnCadastrarMensa').on('click', function(e){
    event.preventDefault();

         var form = $('#formMen').serialize();

         $.ajax({
           type: 'post',
           url:'admin/mensal',
           data: form,
           dataType: "JSON",
               success: function(res){

                       var div_concluido = '<div class="row margin-top-40">'+
                                            '<div class="col-md-12 text-center">'+
                                               '<h2>' + res.msg + '</h2>'+
                                                '</div>'+  
                                          '</div>';          
                               $('.mensalidade_concluido').removeClass('d-none');
                               $('.mensalidade_concluido').html(div_concluido);           

            },error: function(res){

                  console.log(res);                       
             }
         });
    });
}

My seat insertion function is like this:

//Cadastrar Mensa dos Clientes
  public function mensal(){

     if ($this->form_validation->run()) {
        $retorno = '';

        //puxo a lista dos dados do cliente
        $cliente = $this->mensa_model->listarClientes();

     //coloco ele em um array
         $cliente = array_map(function($item){

            return $item->{'id'};

            },$cliente);

            echo"<pre>";
            print_r($cliente);

        //insiro os dados um por um com o for   
        $contador = count($cliente);
        for($i=0; $i < $contador; $i++){

            $mensa['id_cliente'] = $cliente[$i];
            $mensa['dt_mensal'] = $this->input->post('datas');
            $mensa['status'] = "1";
            $query = $this->mensa_model->doInsertMensa($mensa);
        }


     //E aqui exibo a mensagem de sucesso

          $retorno = [
            'erro' => 0,
            'msg' => 'Sucesso'
        ];



    }  else {

          $retorno = [
              'erro' => 10,
              'msg' => 'Erro ao inserir dados'
          ];
      }       

      echo json_encode($retorno);    
   }

In the console result in Replay it shows that it was successfully inserted:

responseText: "<pre>Array↵(↵    [0] => 1↵    [1] => 3↵    [2] => 4↵    [3] => 6↵    [4] => 7↵    [5] => 8↵    [6] => 9↵)↵{"erro":0,"msg":"Sucesso"}

That is to say, I inserted everything in the bank, but I can’t display the successful response, it goes straight to the error showing the error message.. If you can help me, thank you.

  • puts the code of the php method that returns the answer

  • @Ricardo Punctual already updated and added the method, but everything is perfect, only the answer in ajax that does not display

  • At least in the code snippet you posted, the quotes are missing from string out in the field url and is missing a comma after the field dataType.

  • @Gustavo Sampaio, yes I already arranged, and continues with the same problem, it does not display the successful response, only on the console

  • In fact, what’s happening is that you’re mixing JSON with HTML. And you ask AJAX to convert the response of the request to JSON, and the answer brought a mixed content. Therefore, it creates an error, since <pre>... is not something that should be present in a JSON file. Therefore, try to place the HTML content inside the JSON object, rather than using the echo and the print_r.

  • @Gustavo Sampaio Resolvi already. I was using the code snippet: echo"<pre>"; print_r($client); to see the result in Sponse, I took worked perfect.. Thanks for your help

Show 1 more comment

1 answer

-1


Hello,

2 problems!

1) You are not returning pure JSON!

echo"<pre>";
print_r($cliente);

2) Javascript needs to transform JSON into an object!

success: function(retorno){

   var res = JSON.parse(retorno); // CONVERTE JSON EM OBJETO

   // res.erro e res.msg ficarão acessíveis

I hope I’ve helped!

  • was exactly that. Thank you very much my friend for the help.

  • TIP: use and abuse the Console... console.log('AJAX return: ' + return) so you can identify possible failures ;)

  • mto obligato, I’m still a little beginner, but I’m getting the way kkk, Valew by the tips brother

Browser other questions tagged

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