Question

I'm using the jquery form plugin to upload an Image, and everything goes on well. The problem I'm having is when it comes to the json response sent by the php script from the server.

//This is the way i output and encode the jason in my php script
$errors['success'] = false;
$errors['.imgContainer'] = 'Image exceeds maximum size.';
echo json_encode($errors);


//Json response copied from console in FireFox 14.0.1
{"success":false,".imgContainer":"Image exceeds maximum size."}


//Console response for:
console.log(xhr.responseText["success"]);
Undefined
//This should have been true right?

I'm using jquery 1.8.0

//My Jquery
$('.imageForm').live('click', function(e) {
        if (!isValid) {
            e.preventDefault();
        }
        else {
            var bar = $('.bar');
            var percent = $('.percent');
            var response = $('.imgHolder');
            var status = $('#status');

            $('form').ajaxForm({
                contentType : "application/json; charset = utf-8",
                dataType: "json",
                type    : "POST",
                url     : "imgHandle.php",
                cache : false,


                //target: "#status",

                beforeSend: function() {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                    $(".imgContainer :input").attr("disabled", true);
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                complete: function(xhr) {

                    console.log(xhr.responseText["success"]);


                }
            });
        }

    });

Why do I get undefined when I try to access (xhr.responseText["success"])? I was hoping to get true or false and the value of the .imgContainer

Maybe its not interpreting it as json. How can I solve this?

Was it helpful?

Solution

You will have to use success instead of complete. In complete you can only access the raw JSON string and you'd have to parse it before you can access it as an object.

In success the parameter will have the JSON object (not the string) so you could directly access it.

success: function(data) {
   console.log(data.success);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top