0

I'm indirectly using a jQuery ajax call to send data to my server. In my data is a reference to a function (getName) which get called bij jQuery and the return value is sended through ajax (sendDataPOST).

So this works, except the data that's being send is a querystring (id=500&name=test) and I want to send JSON.

So I added a JSON.stringify over the data so it gets converted to JSON, but as a result the getName function isn't called anymore and the variable is ignored. ({id:500})

var data = {
     id: 500,
     name: getName
};

function getName(){
   return "test";
}

function sendDataPOST(){
    $.ajax({
      url: "/test.html",
      data: data
   });
}

function sendDataJSON(){
    $.ajax({
      url: "/test.html",
      data: JSON.stringify(data)
   });
}

Is there a way to let jQuery execute the function before I convert it to JSON ? And does somebody has a name or a reference too the jQuery docs about the method I'm using ?

And by using the ajax call indirectly, I mean the use off Kendo where I'm limited to the changes I can make to the ajax configuration.

Jeroen
  • 185
  • 1
  • 1
  • 8
  • You've got a lot of problems here, but you might find this article interesting in terms of calling functions when a property is accessed: [how to use javascript Object.defineProperty](//stackoverflow.com/q/18524652) – Heretic Monkey Mar 13 '18 at 14:56
  • I mean, you could always do `data.name()` in your `sendDataJSON` method before making the ajax call. – Taplar Mar 13 '18 at 14:56

1 Answers1

0

In order to change the type of data you're sending you should set contentType parameter to application/json; charset=UTF-8 as it defaults to application/x-www-form-urlencoded; charset=UTF-8 :

    function sendDataPOST(){
        $.ajax({
          url: "/test.html",
          data: data,
          contentType: "application/json; charset=UTF-8"
       });
    }

See the reference and check out the explanation.

Arthur Z.
  • 183
  • 1
  • 5