Search code examples
phpjqueryajaxfirefox-os

JQuery AJAX call from FirefoxOS falls to the error part but it does work fine


My task is simple that I am sending string to the server using jQuery AJAX inside a FirefoxOS App. The data is received but still it doesn't proceed to the success function and falls to the error function.

Following is the segment from manifest:

"permissions": {
    "systemXHR": {
        "description": "Required to make Ajax Calls over the Network"
    }
},
"type": "privileged"

My Ajax function:

$('#btn_save_server').click(function() {
    contacts = 'a line of text';

    $.ajax({
        type: "POST",
        url: 'http://localhost/save_contacts.php',
        xhrFields: { mozSystem: true },
        data: { contacts: contacts },
        beforeSend: function() {
            console.log( contacts );
        },
        success: function(data) {
            alert('done');
        },
        error: function(request, status, error) {
            alert('error');
            console.log( request );
            console.log( status );
            console.log( error );
        }
    });
});

And my server:

<?php
    $contacts = $_POST['contacts'];
    $contacts = json_encode( $contacts );
    file_put_contents( 'contacts.txt', $contacts );
    echo 'Finished';

Solution

  • I was able to fix the problem by searching the Internet and with some help from the link provided by @JasonWeathersby

    The manifest and the server code is the same. The change required was before calling the $.ajax() method some settings were required:

    $.ajaxPrefilter(function(options) {
        if (options.xhrConstructParam) {
            options.xhr = function() {
                return new window.XMLHttpRequest(options.xhrConstructParam);
            }
        }
    });
    
    //for FirefoxOS (require "mozSystem" param in AJAX calls)
    var xhrConstructParam = null;
    xhrConstructParam = {
        mozSystem: true
    };
    
    //default settings for AJAX methods
    $.ajaxSetup({
        xhrConstructParam: xhrConstructParam
    });
    

    Since the mozSystem has been provided so it is no longer required in $.ajax() method:

    $.ajax({
        type: "POST",
        url: 'http://www.local/mobile-sync/save_contacts.php',
        data: { contacts: contacts },
        beforeSend: function() {
    
        },
        success: function(data) {
            alert('done');
        },
        error: function(request, status, error) {
            alert('error: ' + request.responseText);
        }
    });