PROBLEM WITH AJAX JSON

0

File IMG_TROCAR.PHP code

<?php
    include_once('config/config.php');
    $ligacao = new PDO("mysql:dbname=$baseDado;host=$host", $user, $pass);

    $id = $_POST['id_user'];

    $mudarAvatar = $_FILES['img_avatar'];

    if($mudarAvatar['name'] == ""){
        //header('Location:perfil.php?ref=configuracao');
       echo '<p>avatar esta fazio</p>';
        exit;
    }else if($mudarAvatar['name']){
        //faz a troca de foto do avatar no banco de dado
        $atualizarAvatar = $ligacao->prepare("UPDATE users SET avatar = ? WHERE id_user = ?");
        $atualizarAvatar->bindParam(1, $mudarAvatar['name'], PDO::PARAM_STR);
        $atualizarAvatar->bindParam(2, $id, PDO::PARAM_INT);
        $atualizarAvatar->execute();

        $location = "avatar/";

        move_uploaded_file($mudarAvatar['tmp_name'], $location.$mudarAvatar['name']);

        //header('Location:perfil.php?ref=configuracao');
    }

        //busca a informação do usuario
        $sql = "SELECT avatar, username, email_user FROM users WHERE id_user = :id";
        $consulta = $ligacao->prepare($sql);
        $consulta->bindParam(':id', $id, PDO::PARAM_INT);
        $consulta->execute();
        $result[] = $consulta->fetch(PDO::FETCH_ASSOC);

        echo json_encode($result, JSON_PRETTY_PRINT);

       $ligacao = null;

?>

I have a JSON file img_trocar.php that returns only a single line of a contact

[
    {
        "avatar": "IMG_20180208_171358_956.jpg",
        "username": "rafaelshembek",
        "email_user": "[email protected]"
    }
]

So far so good. Now the problem is here in that code,

function uploadFoto(){
    var img = '';
    var location = $('.r_f_p');//local onde vai aparece as informações do usuario
    $.getJSON('img_trocar.php')
    var obj = JSON.parse(dado)
    .always(function(dado){
        img += '<p>' + dado[0].username + '</p>';
        img += '<img src="avatar/'+dado[0].avatar+'">';

    });
    location.html(img);
}

The problem is that the information on the page does not appear for the user in the console, it says that the data is not defined, someone has a solution for this.

    
asked by anonymous 04.03.2018 / 13:34

2 answers

0

As I understand it, you do not nothing as a parameter to the php routine, but it receives information from it.

The first suggestion, therefore, is to ensure that the "data" is returned by the php routine itself converted into the JSON format. This can be done with the code below:

echo json_encode($dado);

Where $ given is the variable that contains:

[{"avatar": "IMG_20180208_171358_956.jpg", "username": "rafaelshembek", "email_user": "[email protected]"}]

To complement, if you do not mind using JQuery, I suggest that you modify your code a bit to make the ajax call as in the example below:

var img = '';
var location = $('.r_f_p');//local onde vai aparece as informações do usuario
var url = "img_trocar.php";

$.ajax({
    context : this,
    type    : "POST", 
    url     :url, 
    data    : pack, 
    dataType: "json", 
    encode  : true,
})
.done(function(dado){
    img += '<p>' + dado[0].username + '</p>';
    img += '<img src="avatar/'+dado[0].avatar+'">';
})
.fail(function(dado){   
    e_OnError(data);
});

So you have the guarantee that the return will be received properly if no other errors occur during the process.

    
04.03.2018 / 14:30
0

Your error is here

$.getJSON('img_trocar.php')
var obj = JSON.parse(dado)

You make a request to receive json, but do nothing with it, then you call parse expecting dado that does not exist anywhere ... Still $.getJSON() already a short hand for an ajax request that gets json, there is no need for JSON.parse(dado) . And finally, do not create a variable called img which will actually represent a html block.

Here's an example with its uploadFoto() function changed and renamed to loadContato() , because that's what the method does.

function loadContato() {
  var location = $('.r_f_p');
  //Se o arquivo img_trocar.php está na raiz do seu site, coloque a "/" 
  //no início, caso contrário, indique o caminho correto para a sua localização. 
  $.getJSON('/img_trocar.php', function(dado){
      var html = '';           
      html += '<p>' + dado[0].username + '</p>';
      html += '<img src="avatar/' + dado[0].avatar + '">';
      location.html(html);
  });  
}
    
04.03.2018 / 14:44