Search code examples
javascriptasp.net-mvc-4iframedojoimage-upload

Cannot read property 'value' of undefined" on dojo/request/iframe post


I have an image upload function that uploads form with image like this:

iframe(url, {
    form: dom.byId("myform"),
    handleAs: "json",
    timeout: 5000,
    method: "POST"
}).then(function () {
    console.log("Success");
}, function (Err) {
    console.log(Err);
});

On server side I get the image, but on client side I get TypeError: Cannot read property 'value' of undefined↵ at I [as handleResponse] (http://ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/request/iframe.js:9:114)↵ at r (http://ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js:206:81)". I have no returned value! I do not get what causing the error! Please help!


Solution

  • From the Dojo Reference Guide:

    Important: If your payload is something other than html or xml (e.g. text, JSON) the server response needs to enclose the content in a <textarea> tag. This is because this is the only cross-browser way for this provider to know when the content has been successfully loaded. Therefore the server response should look something like this:

    <html>
      <body>
        <textarea>
          payload
        </textarea>
      </body>
    </html>
    

    All you should need to do to fix this issue is to wrap your JSON response in a <textarea> tag. The reason for this is in iframe.js, starting at line 300:

    if(handleAs === 'xml'){
        ...
    }else{
        // 'json' and 'javascript' and 'text'
        response.text = doc.getElementsByTagName('textarea')[0].value; // text
    }
    

    So here is where you get your error that reads, "Cannot read property 'value' of undefined." Dojo can't find a <textarea> element in your response, so doc.getElementsByTagName('textarea') returns an empty array. The 0th element of an empty array, [], is undefined, and dereferencing it will throw this error.