-2

I've seen this technique many time on other questions to make an AJAX POST:

var postData = $('#my-form').serializeObject();
$.post(url, postData, function(){});

But what I want to do is this.

var data = {name1: 'value1', name2: 'value2'};
$.post(url, data, function(){});

And this is producing the error:

TypeError: undefined is not a function (near '...$.ajax...')

What technique allows me to post non-DOM objects as HTTP form data?

William Entriken
  • 37,208
  • 23
  • 149
  • 195
  • You made a typo. You named your variable `data` on line 1 and `post` on line 2 – Quentin Apr 22 '19 at 23:02
  • If the typo isn't the problem, then you need to provide a [mcve]. `url` is undefined … but not defining it will throw a reference error when you try to read from it. If it and the second argument are properly defined, then it should work fine. – Quentin Apr 22 '19 at 23:02
  • You may want to use something like `var fd = new FormData; fd.append('name1', 'value1'); fd.append('name2', 'value2');` then look at [this](https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery), if you want to use jQuery. I would just use XHR2. – StackSlave Apr 22 '19 at 23:05
  • @StackSlave — Using `FormData` makes things significantly more complicated. If you're using jQuery you need to pass it extra options so it doesn't break it. You also need to make sure the backend you are sending data to can support multipart form data. Typos aside, the code in the question is fine. – Quentin Apr 22 '19 at 23:11
  • Noob mistake, jQuery Slim claims another victim – William Entriken Apr 23 '19 at 13:48

1 Answers1

1

You want to create a JSon object and send it through Ajax

let myData = {
    first: 'A',
    second: 'B',
    third: {
            third_1: '3A'
            third_2: '3B'
            },
};

$.ajax({
    type: "POST",
    dataType: "text",
    data: myData, //<-- your object
    url: "/path/to/myPHPfile.php",

    success: function (serverResult) {
        // Do something with serverResult
    },
    error: function (e) {
        console.log("Error", e);
    }
});
Marco Sanchez
  • 788
  • 7
  • 22