Search code examples
javascriptphparraysajaxxmlhttprequest

Access response JSON array from XMLHttpRequest


I have a problem. I'm sending file via AJAX (XMLHttpRequest). Anyways. PHP function is returning a response array encoded to JSON. I can catch array in JavaScript but i can't access to specified key in array.

Here is the console log of this array:

{"data":"cos","data1":"cos1"}

I have my JavaScript file:

$('input[name=zdjecie]').on("change",function() {
    var inputfile = document.querySelector('#file');
    var file = inputfile.files[0];

    $('button[type=submit]').addClass('disabled');

    var formData = new FormData();
    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function(e){
        var pro = Math.round(e.loaded/e.total * 100);
        if(pro == 100) {
            $('#upload_progress').css({'width':pro+'%', background:'#00A65A'});        
            $('button[type=submit]').removeClass('disabled');                
        }
        else {
            $('#upload_progress').css({'width':pro+'%', background:'#3C8DBC'});   
        }
    }, false);        

    formData.append('file', file);
    request.open('post', '/admin/ajax/upload-admin-photo');
    request.send(formData);
    request.onloadend = function() {
        var result = request.response;                
        console.log(result.data);
    };
});

Now PHP function that is executing after POST request:

/**
 * @Route("/admin/ajax/upload-admin-photo")
 */
public function ajaxUploadAdminPhotoAction(Request $request)
{ 
    $data = $_FILES;

    $response = array("data" => 'cos', 'data1' => 'cos1');
    return new Response(json_encode($response)); 
}

Console log of variable result: {"data":"cos","data1":"cos1"}

Console log of variable result.data: undefined

I really need some help. I was trying everything! :(


Solution

  • You need to parse (=decode) the string '{"data":"cos","data1":"cos1"}' to a json first:

    var result = JSON.parse(request.response);
    // now you can access it's params:
    console.log(result.data);
    

    see the manual for more information.