0

I have a javascript function with jQuery that calls an API. A part of the call sets the object type, and sets it to the object id. The right function is set, but I do not know how to set the key correctly. The API get "object_type" and not "itemDetails" for the parameter in data.

Is there a way to set the value of a key in the data array to itemDetails as its called from the function?

function details_api(object_id, object_type){
    $.ajax({
        url: '/api.php',
        type: 'POST',
        data: {
            function: object_type,
            data: {
                object_type: object_id
            }
        },
        error: function() {
          alert('An error occurred connecting to server. Please check your network');
        },
        dataType: 'json',
        success: function(json) {
            if (json.status) {
                console.log(json.data);
             }else{
                alert(json.message);
            }
        }
    });

}
details_api('1', 'itemDetails');
user1955162
  • 797
  • 2
  • 6
  • 21
  • You mean `data` should be something akin to `var data = {}; data[object_type] = object_id`? I don't think you can do this inline. There's no problem with defining it before the `$.ajax`, scope will handle it, even if it's slightly inelegant. – user01 Jul 09 '16 at 02:47
  • So in my code, the post sends function: itemDetails. Then it sends object_type: 1. I want it to send itemDetails: 1. – user1955162 Jul 09 '16 at 02:51
  • is `object_type === 'itemDetails'` in this instance? – user01 Jul 09 '16 at 02:52
  • No...do it exactly as @user01 shows and pass that object to the data option like `data:data,` – charlietfl Jul 09 '16 at 02:53
  • I did it his way. Thats the correct answer – user1955162 Jul 09 '16 at 05:00

0 Answers0