PROBLEM WITH AJAX JSON

Asked

Viewed 168 times

0

IMG_TROCAR.PHP file 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 only returns 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 this 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 does not appear on the page for the user in the console says that the data is not defined someone has a solution for this

2 answers

0

From what I understand, you do not take anything as a parameter for the php routine, but from it you receive information.

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

echo json_encode($dado);

Where $given is the variable it contains:

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

To complement, if you don’t mind using Jquery, I suggest you modify your code a little to make the call ajax as 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);
});

Thus you have the assurance that the return will be received properly if no other error occurs during the process.

  • i made your example so that in the console says that pack is not defined

0

Your mistake 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 waiting dado that doesn’t exist anywhere... yet $.getJSON() already a short hand for an ajax request that receives a json, there is no need for the JSON.parse(dado). And lastly, don’t create a variable called img which will actually represent a block of html.

Below is an example with its function uploadFoto() amended and renamed to loadContato(), why 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);
  });  
}
  • i made your example more in DOM where the div with class="r_f_p" does not show the username name neither avatar nor console returns anything

  • The path to img_swap is right where javascript is running?

  • I will update the top and put the code of the page img_trocar.php for you to see

  • In fact it matters the path of it on your site

  • as yes makes an example there to see me

  • I edited and added the comment: If the img_trocar.php file is at the root of your site, put "/" at the beginning, otherwise indicate the correct path to your location.

Show 1 more comment

Browser other questions tagged

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