How to get json data from php with javascript

Asked

Viewed 3,281 times

1

I have a question, how to rescue the values, which are transformed into json, into javascript? I think it’s a more elegant way to communicate both. I’ve been seeing a lot of gossip on the internet.

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

Basically, I just send 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 basically the ajax I’ve been trying

Generated error: Syntaxerror: Unexpected token < in JSON at position 0(...)

Content of my page

I need to take the select from the "Third" list and send it to another page. I thought of generating a json and recovering 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 is the json that came... it is not the json that I expected

inserir a descrição da imagem aqui

================ 2 EDITION =========================

My current code

<?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>

<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>
  • If in the success of the function put, console.log(data); something appears on the console?

  • Sorry, I forgot to measure the error, I edited in the post

  • And nothing shows up

  • And you’re sure there’s something being returned from the server (echo json_encode($json_data);) does what’s supposed to?

  • Yes, of course

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.

Right after succcess, if you don’t use or specify something with the return date, it will get lost and you won’t be able to use it anymore.

If you use JSON internally, there is also the possibility to work with this JSON using Data.attribute directly within the Success.

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

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

//... keep the same until

</body>
<? 
} ?>

Now understanding what you want, it seems that you are 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->listAll () for example

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 that object. If you return from PHP a JSON that is Student with name, for example, you can access it through obj.nome

Browser other questions tagged

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