How to return data from a Jason, within PHP, via Jquery?

Asked

Viewed 47 times

-3

I’m having trouble returning information via Ajax. It has to show the results in a alert(). The problem is that I am trying to return this data from a PHP file that creates a array() and then use the json_encode(), but when returning this data, it returns as an object.

header('Cache-Control: no-cache, must-revalidate'); 

header('Content-Type: application/json; charset=utf-8');
    
$placa = array(

    'marca' => "Chevrolet",
    'modelo' => "Agile LTZ 1.4",
    
);

echo json_encode($placa);

Arquivo Js

$(document).ready(function(){

$("#form-placa").submit(function(e){
    e.preventDefault();
});

$("#placa").blur(function() {
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url : 'funcoes/placa.php',
        data: $('#form-placa').serialize(),
        
        beforeSend: function(){
            //$("#include").css('display', 'none');
            //loading.css('display', 'block');
        },
        
        success: function(dados){
        
            var carro = JSON.parse(dados); 
            
            alert(carro.marca);

            
        },
        error: function(error)
        {
            alert(error);
        }
    });
});
});
  • In the Browser Developer Tools, in the Network tab, what is your response to your PHP? (You can test using an HTTP client, such as Postman software)

1 answer

0

Are you doing the json.parse() of something that is already json. You can use jsonRESPONSE.dados no javascript which will be json. You can open the developer tools and breakpoint the ajax response and see if the answer already comes as json (how you are doing the json_encode() in the controller it already comes as json.)

Browser other questions tagged

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