将字符串化的JSON返回给PHP

I'm using a JQuery script manipulate an image. So far, all the functions are working as intended, except for returning the data to PHP. I've tried several examples that I've found on Stackoverflow, yet I've been unable to return the data without any errors.

Note: JavaScript is not my primary language, my previous attempts at using Ajax have failed.

    $.ajax({
        type: "POST",
        url: "/foo/bar.php",
        datatype: "json",
        data: { 
            submit: JSON.stringify(format(), null, 2) 
        },
        cache: false,
        success: function() {
            console.log("Order Submitted");
        }
    });

This is the error that is generated:

designer.js:276 Uncaught TypeError: Cannot read property 'slice' of undefined
at format (designer.js:276)
at designer.js:340

Slice is a function inside Format. At the end of the Format function, it returns a variable out. I've attempted to replace the data with data: { test: out }, but this proved to be unsuccessful as well.

In PHP, I call the result as follows; $stringData = $_POST['submit']; Which returns the following: Array ( [submit] => Submit )

When console.log(out) is called without the ajax code in place, it returns the values correctly. As soon as the ajax code is added, parts of the script stop operating as intended.

function format() {
var all = rects.slice().sort(function(d, f){ return d[0] - f[0]});
var lst = null;
var out = [];

for (var i = 0; i < all.length; i++) {
        var cur = all[i];
        var pen = cur[0];

        if (lst != pen) {
                var locs = [];

                out.push(locs);
                lst = pen;
            }
            var ecl = cur[1].pos;
            var pos =
            {
                pos: [
                    round(ecl[0] / size.x),
                    round(ecl[1] / size.y),
                    round(ecl[2] / size.x),
                    round(ecl[3] / size.y)
                    ]
            };

        if(typeof cur[1].colour !== 'undefined'){
                pos.colour = cur[1].colour;
            }

        if(typeof cur[1].filter !== 'undefined'){
                pos.filter = cur[1].filter;
            }
    locs.push(pos);
}
console.log(JSON.stringify(out, null, 2));
return out;

}

Generally, the error Cannot read property 'slice' of undefined implies you're calling .slice() on something that doesn't exist.

The first line of your format function does make a rects.slice() - however you do not show where this rects variable comes from (it seems to be global).

Given this is the only call to slice in the code you show, what is probably happening is that the global variable rects is indeed undefined.

Adding console.log(rects) as the first line of the format function will help you debug it.