1

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! :(

3
  • you need to parse (=decode) the string '{"data":"cos","data1":"cos1"}' to a json first: var result = JSON.parse(request.response); Commented Oct 29, 2017 at 13:06
  • Yes ! That's it. Post answer and I will accept it! Commented Oct 29, 2017 at 13:09
  • related: stackoverflow.com/questions/45015/… Commented Oct 29, 2017 at 13:13

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.