How to get json data coming from php with javascript

1

I'm having a question, how do I retrieve values, which are transformed into json, into javascript? I believe it is a more elegant way of communicating both. I'm seeing a lot of gambiarra on the internet.

$json_data = array(
    "dados" =>  $Partner->listaParceiro($id) , 
);
echo json_encode($json_data);

Basically, I just generate a json with php. How can I get this data with javascript / ajax?

$.ajax({
    type: 'GET',
    url: "http://127.0.0.1/ecoLicenseLayout/send-data.php",
    dataType: 'json',
    contentType: 'application/json',
    crossDomain: true,
    cache:false,
    success: function(data)
    {

    },
    error:function(jqXHR, textStatus, errorThrown){
        alert('Erro ao carregar');
        console.log(errorThrown);
    }
});

Above all, the ajax I've been trying to do

Error generated: SyntaxError: Unexpected token < in JSON at position 0 (...)

My page content

I need to get the select from the "listPartner" and send it to another page. Then I thought of generating a json and retrieving this json with javascript

<?php
error_reporting(E_ALL);
require_once("classes/Partner.php");
require_once("classes/Clicks.php");
if(isset($_GET['id']) && $_GET['id']) {
    $id = $_GET['id'];
    $Partner = new Partner();
    $Cliques = new clicks();


    date_default_timezone_set('America/Sao_Paulo');
    $dataRegistro = date("Y-m-d H:i:s");

    $Cliques->setDataRegistro($dataRegistro);
    $Cliques->setIdPartner($id);

    $Partner->updateContCliques($id);
    //$Partner->listaParceiro($id);
    $json_data = array(
        "dados" =>  $Partner->listaParceiro($id) ,   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
    );
    echo json_encode($json_data);


    $Cliques->inserir();


}
else{
    header("Location: reg-partner.php");
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>



    <?php
    require_once("cabecalho.php");
    ?>
</head>
</html>
<body>
<!-- /. WRAPPER  -->
<!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME-->
<!-- JQUERY SCRIPTS -->
<script src="assets/js/jquery-1.10.2.js"></script>
<!-- BOOTSTRAP SCRIPTS -->
<script src="assets/js/bootstrap.min.js"></script>
<!-- METISMENU SCRIPTS -->
<script src="assets/js/jquery.metisMenu.js"></script>
<!-- CUSTOM SCRIPTS -->
<script src="assets/js/custom.js"></script>

<script type="text/javascript">

    $.getJSON('http://127.0.0.1/ecoLicenseLayout/send-data.php?id=2', null, function (data) {
        alert(data.results); // Resultado: "Av. 7 de Setembro, S/N"
    })
/*
    var myUrl = encodeURIComponent("http://ecoprintq.com/index.php/partnerApplication/create");
    var dados = "User_full_name:aaaaaaa&User_institution:sssss"
    $.ajax({
        url: "webproxy.php?url=" + myUrl,
        data: dados,
        crossDomain:true,
        type: "GET",
        timeout: 30000,
        dataType: "text", // "xml", "json"

        success: function(data) {
            window.location.href = "webproxy.php?url=" + myUrl + "&" + dados;
        },
        error: function(jqXHR, textStatus, ex) {
            alert(textStatus + "," + ex + "," + jqXHR.responseText);
        }
    });*/


    var conteudoJSON;
    $.ajax({
        type: 'GET',
        url: "http://127.0.0.1/ecoLicenseLayout/send-data.php",
        dataType: 'json',
        contentType: 'application/json',
        crossDomain: true,
        cache:false,
        success: function(data)
        {
            conteudoJSON = data;
            console.log(coneudoJSON);
        },
        error:function(jqXHR, textStatus, errorThrown){
            alert('Erro ao carregar');
            console.log(errorThrown);
        }
    });
</script>


</body>

================= Editing the post =========================== =

With what you said, it's the json that came ... it's not the json I expected

================2EDIT=========================

Mycurrentcode

<?phperror_reporting(E_ALL);require_once("classes/Partner.php");
require_once("classes/Clicks.php");
if(isset($_GET['id']) && $_GET['id']) {
    $id = $_GET['id'];
    $Partner = new Partner();
    $Cliques = new clicks();


    date_default_timezone_set('America/Sao_Paulo');
    $dataRegistro = date("Y-m-d H:i:s");

    $Cliques->setDataRegistro($dataRegistro);
    $Cliques->setIdPartner($id);

    $Partner->updateContCliques($id);
    //$Partner->listaParceiro($id);
    $json_data = array(
        "dados" =>  $Partner->listaParceiro($id)   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
    );
    echo json_encode($json_data);


    $Cliques->inserir();


}
else{
header("Location: reg-partner.php");
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>


    <?php
    require_once("cabecalho.php");
    ?>
</head>

<body>
<!-- /. WRAPPER  -->
<!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME-->
<!-- JQUERY SCRIPTS -->
<script src="assets/js/jquery-1.10.2.js"></script>
<!-- BOOTSTRAP SCRIPTS -->
<script src="assets/js/bootstrap.min.js"></script>
<!-- METISMENU SCRIPTS -->
<script src="assets/js/jquery.metisMenu.js"></script>
<!-- CUSTOM SCRIPTS -->
<script src="assets/js/custom.js"></script>

<script type="text/javascript">




    var myUrl = window.location;
    .ajax({
        type: 'GET',
        url: myUrl
        data: {id:confirm("Insira o id desejado:")},
        //dataType: 'json',
        //contentType: 'application/json',
        crossDomain: true,
        cache: false,
        success: function (data) {
            console.log(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Erro ao carregar');
            console.log(errorThrown);
        }
    });
</script>


</body>
<?php

}
?>
</html>
    
asked by anonymous 13.12.2016 / 19:31

2 answers

0
var conteudoJSON;
$.ajax({
    type: 'GET',
    url: "http://127.0.0.1/ecoLicenseLayout/send-data.php",
    dataType: 'json',
    contentType: 'application/json',
    crossDomain: true,
    cache:false,
    success: function(data)
    {
        conteudoJSON = data;
        console.log(coneudoJSON);
    },
    error:function(jqXHR, textStatus, errorThrown){
        alert('Erro ao carregar');
        console.log(errorThrown);
    }
});
//Ou trabalhe com seu  JSON da maneira que vc quiser usando esta variável.

Soon after the succcess, if you do not use or specify something with the return date, it will be lost and you will not be able to use it any more.

If you use JSON internally, there is also the possibility of working with this JSON using Data.attribute directly within success.

It may only be a case of interpretation as well, try the following change on your page

else{
    header("Location: reg-partner.php");
//}
?>

// ... keep the same until

</body>
<? 
} ?>

Now understanding what you want, it looks like you're not sending the ID you want to get from JSON, change to the following:

$.ajax({
    type: 'GET',
    url: "http://127.0.0.1/ecoLicenseLayout/send-data.php",
    data: {id:confirm("Insira o id desejado:")},
    .....

If your intention is to pass all the elements of your object, you would need to send an ALL variable and test it on the PHP side through a $ Partner-> list AllPartners () for example

    
13.12.2016 / 19:41
0

Try this:

$.ajax({
    type: 'GET',
    url: "http://127.0.0.1/ecoLicenseLayout/send-data.php",
    dataType: 'json',
    contentType: 'application/json',
    crossDomain: true,
    cache:false,
    success: function(data)
    {
        var obj = jQuery.parseJSON(data);
        console.log(obj.atributoJSON);
    },
    error:function(jqXHR, textStatus, errorThrown){
        alert('Erro ao carregar');
        console.log(errorThrown);
    }
});

obj will be your json object and JSON attribute is an attribute of this object. If you return from PHP a JSON that is Student named, for example, you can access it through obj.nome

    
22.06.2018 / 02:31