Help to query a single database user’s information with JSON

Asked

Viewed 40 times

1

This is the code that works with the img.php file

function loadContato(){
    var location = $('.result_File');
    var item = "";
    $.getJSON("img.php", function(dado){
        item += '<p>' + dado[0].username + '</p>';
        item += '<img src="avatar/'+dado[0].avatar+'">';
        location.html(item);
        console.log(item);
    });
}

json file information img_trocar.php

[ { "avatar": "angela.jpg", "username": "angela vazquez", "email_user": "[email protected]" } ]

I’m having trouble with a single user information line request

Here does the following shows the photo before sending to the data bank all well without problem

function imagemPreview(input) {
    var imgpreview = $('#mgpreview');
    var iconAVATAR = $('.avatar');
    if (input.files && input.files[0]) {
        var filerd = new FileReader();
        filerd.onload = function (e) {
            imgpreview.attr('src', e.target.result);
        };
        filerd.readAsDataURL(input.files[0]);
    }
    uploadFoto();
}

The problem is here in this function I am trying to obiter the user information in JSON format with the $.getJSON method more as it is a single line do not know how to do the for() shows the infections on the page, HELP PLEASE, for security I will not be able to show the user data here

function uploadFoto(){
    var items = "";
    $.getJSON('img_trocar.php', 'GET')
    .fail(function(){
        $('.result_File').html("ERRO!!");
    })
    .always(function(data){
        for(var i = 0; i < data; i++)
            {   
            items += '<img src="avatar/'+data.avatar+'" alt="avatar">';
            items += '<p>'+data[i].username+'</p>';   
            }
        $('.result_File').html(items);
    });
}
  • Try on the for place length in the data: i < data.length

  • not yet, shows nothing nor error shows I’ll put the JSON file for you to see

1 answer

0

Since it is only a JSON object array of only 1 index, you may not need to for, just call the value by the key picking the first and only index of the array (data[0]):

Example:

var data = [ { "avatar": "angela.jpg", "username": "angela vazquez", "email_user": "[email protected]" } ],
items = '<img src="avatar/'+data[0].avatar+'" alt="avatar">'
+ '<p>'+data[0].username+'</p>';   
console.log(items);

  • Please avoid long discussions in the comments; your talk was moved to the chat

Browser other questions tagged

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