Steve Walsh Steve Walsh - 11 months ago 48
Ajax Question

jQuery ajax post works on console but not from the page

I can't find the answer from any searching I've done.

I have a simple button using an anchor tag in HTML:

<a id="beginUpload" href='/upload' class='button-style'>Upload</a>

The data is generated from an input element on the HTML with id 'file'.

My jQuery method is as follows:

$("#beginUpload").click(function () {
var data = {
mimeType : document.getElementById('file').files[0].type,
fileSize : document.getElementById('file').files[0].size
type: 'POST',
url: '/post_asset/',
data: data,
dataType: 'json',
success: function (result) {
error: function (error) {

When I run the contents of the click function (after first inputing a file) - it returns my expected response which is something like this:

Object {success: true, upload_url: "http://my_url", id: 12, mime_type: "audio/mp3", size: "52981888"}

However, when I run this code using the button, I get an error with an empty errorResponse text as follows:

Object {readyState: 0, responseText: "", status: 0, statusText: "error"}

Any idea what I am doing wrong?

Answer Source

Try to prevent the default behavior of your link a (redirect to /upload) using e.preventDefault() :

$("#beginUpload").click(function (e) {

    //...Your code here

Hope this helps.