0

I have a Google Chrome extension (browser action) that sends popup form inputs to my Meteor website/app database. (Based on Log in to a meteor app from a Google chrome extension.)

The XHR code on popup.js:

$(document).ready(function() {
  $('#form').on('click','#submitForm',function () {
    var xhr = new XMLHttpRequest();
    var data =  {
                  "field1": $('#input1').val(),
                  "field2":$('#input2').val(),
                };
    xhr.open("POST", "http://MYAPPNAME.meteor.com/extension/post", true);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xhr.send(JSON.stringify(data));
  });
});

The code works very sporadically. Typically on the fourth attempt (i.e., four submissions of the form).

What could be causing this inconsistency? Is it simply a facet of the slow free hosting on meteor.com? I will likely but switching to a custom domain (on a paid server), but ideally want to ensure the functionality before payment.

EDIT

I've added event listeners for the XHR errors (from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest), as per Xan's suggestion.

xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);

Each time now, the "abort" (transferCanceled) alert appears. However, the data is still sent correctly occasionally (even with the error alert).

Is this of any note? Are there better ways to be alerted of errors?

Community
  • 1
  • 1
  • I'm always rather sceptic when it comes to sending JSON instead of "normal" URL parameters like `field1=value1&field2=value2`. Did you try that? – devnull69 Dec 03 '14 at 07:16
  • 1
    Add a listener to errors on the XHR, and if possible examine the server logs. It's very hard to diagnose without that information. – Xan Dec 03 '14 at 09:02
  • @Xan Added listeners. See edit above. Can't access server logs, but will try localhost instead. – AvidSnacker Dec 03 '14 at 23:36

1 Answers1

1

I guess that the request is aborted because the form is submitted. Try to cancel the default action (form submission) in the click handler:

$('#form').on('click', '#submitForm', function(event) {
    event.preventDefault();
    ....
});

And you might want to use the form's submit event instead. This allows users to hit Enter to submit a form instead of clicking a button:

$('#form').on('submit', function(event) {
    event.preventDefault();
    ....
});
Rob W
  • 341,306
  • 83
  • 791
  • 678