Error accessing json array with php

0

Good morning, cordial greeting to all. Again, I'm going through this space because I have a big unresolved problem and this time it's php based, since I'm starting in this language.

The problem is that I need to return some values in json format from php for which I use the json_encode method. But unlike the methods I use in Java, php returns the keys of the values in uppercase (I do not know if it suddenly has something to do) but when trying to access them from Javascript I get the error "undefined".

This is the json that returns php: [{"0":"13","NROCLI":"13","1":"CC","IDEPRS":"CC","2":"123","NRIPRS":"123","3":"CLIENTE","NOMPRS":"CLIENTE","4":"NUEVO CLIENTE","APEPRS":"NUEVO CLIENTE","5":"JARDINES","DIRPRS":"JARDINES","6":"123456","TELPRS":"123456","7":"13","CODDEP":"13","8":"001","CODMUN":"001","9":"[email protected]","EMLPRS":"[email protected]"}]

And this is my Javascript code to read them.

function find() {
    var data = {
        ideprs: $('#ideprs').val(),
        nriprs: $('#nriprs').val(),
        nrousr: '',
        action: 'FIND'
    };

    $.ajax({
        url: '../../controller/ClienteManage.php',
        method: 'post',
        data: data,
        success: function (r) {
            if (r.includes('{') || r.includes('}')) {
                r = JSON.parse(r);
                cargarDatos(r);
            } else {
                unlockInputs();
            }

        }
    });
}

function cargarDatos(data) {
    $('#nomprs').val(data.nomprs);
    $('#apeprs').val(data.apeprs);
    $('#telprs').val(data.telprs);
    $('#celprs').val(data.celprs);
    $('#emlprs').val(data.emlprs);
    $('#dirprs').val(data.dirprs);
    setValueSelect('coddep', data.coddep);
    setValueSelect('codmun', data.codmun);
}

I do not really know if I have to see the fact that php returns the keys in uppercase, but it's the only difference I notice with the jsons returned when I use Java as a server-side language.

I thank you in advance for any help since I have been trying to solve this problem for several hours. If you have a piece of code that does the same, I thank you share it to learn from you!

Thank you very much.

    
asked by Jesus Escorcia 17.04.2018 в 23:18
source

2 answers

0

The Json you have is an array. Try to refer to him like this:

$('#nomprs').val(data[0].nomprs);
    
answered by 17.04.2018 в 23:26
0

When you send your function cargarDatos you could make a conosle.log of your data console.log(data) , so you will know how your data is being returned and access them. Js makes a distinction between uppercase and lowercase.

So you could access your data.

function cargarDatos(data) {
    console.log(data)
    $('#nomprs').val(data.NOMPRS);
    $('#apeprs').val(data.APEPRS);
    $('#telprs').val(data.TELPRS);
    .
    .
    .
}

I hope it's of your use.

    
answered by 18.04.2018 в 04:40