gh0st
gh0st

Reputation: 214

AJAX request not working on remote host

I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:

function send() {
    console.log("preparing");
    var beacon = {
        beaconID: $("#beaconID").val(),
        name:$("#beaconName").val(),
        campaignID:$("#campaignID").val(),
        clientID:$("#clientID").val()
    }
    console.log("payload:");
    console.log(beacon);

    $.ajax({
        type: 'POST',
        url: '../beaconAPI/index.php/createBeacon',
        data: JSON.stringify(beacon),
        contentType: "application/json; charset=utf-8",
        traditional: true,
        success: function (response) {
            console.log("done:");
            console.log(response);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
         }
    });
}

Upvotes: 0

Views: 1074

Answers (1)

epascarello
epascarello

Reputation: 207527

From the comments you posted

10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "

A status code of zero means one of two things:

  1. You are running off file protocol
  2. The page refreshed as Ajax call is made

Since you said this is on production, sounds like it is a case of #2.

So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.

onclick="send(); return false" 
onsubmit="send(); return false"

$("#foo").on("click", function(e) {
    send();
    e.preventDefault();
});

Upvotes: 1

Related Questions