Recover JSON in PHP

Asked

Viewed 983 times

-2

I saw many forums but still not solved for me

HTML

<div class="form-group col-xs-12 col-sm-5 col-md-6 col-lg-6">
  <label for="banco">Banco</label>
  <select id="banco" type="number" class="form-control" required="" >
    <option value="">Selecione</option>
    <option value='{"sigla" : "bradesco", "banco": "Bradesco"}'>Bradesco</option>
    <option value='{"sigla" : "bb", "bank": "Brasil"}'>Brasil</option>
    <option value='{"sigla" : "cef", "bank": "Caixa Economica Federal"}'>Caixa Econ&ocirc;mica Federal</option>
    <option value='{"sigla" : "itau", "bank": "Itau"}'>Ita&uacute;</option>
    <option value='{"sigla" : "santander_banespa", "bank": "Santander"}'>Santander</option>
  </select>
</div>

Javascript

I have in Javascript that makes the following sending:

function salvar(){
jQuery('#form').submit(function () {
    var banco       = document.getElementById('banco').value;
     $.ajax({
     type    : 'post',
     dataType: 'json',
     url     : 'function/conta.php',
     beforeSend : carregando,
     data: {                
           'banco'      : JSON.stringify(banco),         
           },
           success: function (data) {
           //alert(data.retorno);
           if (data.retorno == 1) {
           sucesso('Opera&ccedil;&atilde;o realizada com sucesso!');
           }
           else {
           errosend('N&atilde;o foi poss&iacute;vel realizar opera&ccedil;&atilde;o. Verifique se todos os campos est&atilde;o preenchidos ');
          }
        }
      });
    return false; 
 });
}

PHP

In PHP it returns:

if(isset($_POST['banco'])){
    $banco = $_POST['banco'];
}

$bank1 = json_decode($banco);

foreach ($bank1 as $item => $value) {
        echo $value->{'bank'};
    }

But the message it gives is:

Warning: Invalid argument supplied for foreach() in

Each case is a case, because in another file I use this block foreach works for

  • Do a test to see what type of data returns. Put before the foreach var_dump($bank); ... put here what is displaying to you.

  • Are you sure JS is generating JSON with simple quotes? I made a test here and returned with double quotes and thus worked perfectly in the PHP.

  • It generated it here {'sigla' : 'bb', 'bank': 'Brasil'}' (length=34)

  • I tried it in PHP and with single quotes it doesn’t work. When I put double quotes it works as it should. The jQuery/Javascript function is correctly generating JSON ?

  • I edited it to see if it is better understood the question

  • He spoke in php and not jquery. Eu não posso responder, mais essa é uma boa formas, veja uma api de cotação como exemplo: <?php &#xA;$json_str = file_get_contents("https://economia.awesomeapi.com.br/json/all/USD-BRL,EUR-BRL"); &#xA;$jsonObj = json_decode($json_str);&#xA;$usd = $jsonObj->USD;&#xA;$eur = $jsonObj->EUR; ? > then you just recover with echo {{ $Eur->Ask }}, this shows the current quotation, now just adapt your need.

Show 1 more comment

1 answer

1


There are several ways to do what you need, but I’ll use your concept.

In the Javascript try to send the contents of option selected as he is:

function salvar(){
jQuery('#form').submit(function () {
    var banco       = document.getElementById('banco').value;
     $.ajax({
                type    : 'post',
                dataType: 'json',
                url     : 'function/conta.php',
                beforeSend : carregando,
                data: {

                    'banco'      : banco,

                },
                success: function (data) {
                    //alert(data.retorno);
                    if (data.retorno == 1) {
                        sucesso('Opera&ccedil;&atilde;o realizada com sucesso!');
                    }
                     else {
                        errosend('N&atilde;o foi poss&iacute;vel realizar opera&ccedil;&atilde;o. Verifique se todos os campos est&atilde;o preenchidos ');
                    }
                }
              });
        return false; 
});
}

In PHP decode with json_encode

if(isset($_POST['banco'])){
    $banco = $_POST['banco'];
}

$bank1 = json_decode($banco);

echo $bank1->sigla.'<br />';
echo $bank1->bank;

The mistake I understand is that option is sending a unique object and not an array of objects, so it does not need to be caught (and will not even give) by foreach that just loops with arrays. With this, you can take the object directly.

NOTE: I noticed that in your options has a json value called bank instead of bank.. Be careful with this, because it may give future errors in the checks.

  • gave this here Notice: Trying to get property of non-object in but if your der var_dump the data shows

  • Give a var_dump($bank1); before the foreach and put what returns

  • return it here object(stdClass)[1]&#xA; public 'sigla' => string 'bb' (length=2)&#xA; public 'bank' => string 'Brasil' (length=6)&#xA;

  • @adventistaam edited the answer, from a look there

  • Bingo!!! That’s exactly what it was! It worked! Thank you very much!

  • So I didn’t need to use JSON.stringify

  • @adventist ;)

  • 1

    @adventistaam not, because in the option you are already sending a json in string form. In PHP just decode it.

  • Thanks a lot! I have to learn a lot

  • @adventistaam we are always in the learning stage rsrs. Anything, just post here on Stack Overflow that any of us will help you.

  • Blz. You can leave

Show 6 more comments

Browser other questions tagged

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