Skip to content Skip to sidebar Skip to footer

Javascript Object Not Posting Correctly To $_post On Php Page Using Vanilla Ajax

I have searched the internet and stackoverflow topics for an answer but I have not found any. I know JQuery works fine with sending the object but when I try to do the same without

Solution 1:

It's because post_data.myData is an object and not a string, that it's being encoded via encodeURIComponent as [Object object].

If you're dead-set on using www/form-data encoding, you will need a function that uses recursion to properly escape all the properties and sub-properties of the complex object.

Far be it from me to suggest using jQuery, but it has a convenience function for just this purpose, $.param(obj).

Otherwise, you could just use JSON:

var jsonString = JSON.encode(complexObject);

Edit: I've since needed to implement this function, so I might as well share it here:

/**
 * Pack up an object of parameters into something that can be added to a GET
 * request.
 *
 * Example:
 * encodeParams({ 'foo': 'bar', 'baz': 'qux' })
 * -> "foo=bar&baz=qux"
 * @param { [key: string]: any } params - key-value store of string->anything
 * @return string URL encoded parameters
 */var encodeParams = function (params) {
    var up = new URLSearchParams;
    var addParam = function (prefix, param) {
        if (param instanceofArray) {
            for (var _i = 0, param_1 = param; _i < param_1.length; _i++) {
                var i = param_1[_i];
                addParam(prefix + "[]", i);
            }
        }
        elseif (param instanceofObject) {
            // add like associative array,// e.g. foo[bar][]=baz&foo[bar][]=quxfor (var i in param) {
                if (param.hasOwnProperty(i)) {
                    addParam(prefix + "[" + i + "]", param[i]);
                }
            }
        }
        else {
            up.append(prefix, (param == null ? '' : param));
        }
    };
    for (var p in params) {
        if (params.hasOwnProperty(p)) {
            addParam(p, params[p]);
        }
    }
    return up.toString();
}; // end encodeParams()

Post a Comment for "Javascript Object Not Posting Correctly To $_post On Php Page Using Vanilla Ajax"