answer in`json` received from a file `php`

Asked

Viewed 34 times

0

I have the following answer in jSon received from a file php.

{"1":"OK","2":"n"}

I want it now, in jQuery catch the values of indexes 1 and 2 which are respectively "OK" and "n".

How to do this?

My block is like this:

  $("a#bloqDesbloq").click(function() {

     $.post ("../_requeridos/alteraAdministrador.php", {

         idAdministrador   : $(this).attr('idAdmin'),
         bloq      :         $(this).attr('bloq')

     }, function(retorno){
                     alert(retorno[1]);
          if (retorno[1] == "OK") {
              if (retorno[2] == "s")  $("a#bloqDesbloq img").prop("src",'_img/desbloquear.png')
              if (retorno[2] == "n")  $("a#bloqDesbloq img").prop("src",'_img/bloquear.png')
              location.reload();
          } else {
            alert("Erro no bloqueio");
            location.reload();
          }

       }
      );
        return false;

  });

Making:

alert(retorno[1]);

It only gives double quotes as return

"
  • Use the JSON.parse() or correctly define the parameter dataType.

  • Ok return = JSON.parse(_return);

2 answers

0

You can try something like this:

  $("a#bloqDesbloq").on('click', function() {

    $.ajax({
        method: 'POST',
        url: '../_requeridos/alteraAdministrador.
        dataType: 'json'
    }).then(function(data) {
        console.log(data) // aqui vai estar o retorno da sua requisição!
                          // A partir daqui é só vc trata-lo para exibir da forma que quiser..

    }).catch(function(err) {
        console.log(err);  // Caso aconteça algum erro ele ira exibir no console!
    });

  });

0

You have to define the type of return. The example would be the dataType: json

    $('#bloqDesbloq').on('click', function(){
       var idAdmin = $(this).attr('idAdmin');
       var bloq    = $(this).attr('bloq');
       $.ajax({
         url : '../_requeridos/alteraAdministrador.php',
         type : 'post',
         dataType: 'json',
         data: {
           idAdministrador : idAdmin,
           bloq : bloq
          }
       }).
        done( function( data ){
        if( data.1 == "OK" ){
          if ( data.2  == "s")  
              $("#bloqDesbloq").prop("src",'_img/desbloquear.png')
          if (data.2 == "n") 
               $("#bloqDesbloq").prop("src",'_img/bloquear.png')
       }else{

       }
    })
 })

Another option is to use the

$.post('script.php', data, function(response) {
    // Do something with the request
}, 'json');

Source: https://www.abeautifulsite.net/postjson-for-jquery

  • and how I define return type using $.post instead of $.ajax?

  • Tried with JSON.parse( return )

  • yeah, it worked out!

  • Follow that line tip

Browser other questions tagged

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