0

I'm trying to reach an API from inside my tag manager. The language to use for the so-called building blocks in this tag-manager is JavaScript. The POST API I am trying to use is fully functioning and works like this:

input:

{"features": "xyz"}

output:

[0.45]

I set up an ajax statement, but it does not seem to work.

I have tried all different kinds of input and content types. The code looks like this:

 $.ajax({
url: apiurl,
type: "POST",
data: {"features": "xyz"},
contentType: "application/json; charset=utf-8",
success: function (data) {
    console.log(data)
},
error: function(){
     console.log("Error");       }
});

What I am doing wrong here? I keep getting error messages.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
T.Beil
  • 37
  • 7
  • 2
    Define "does not seem to work". What *does* it do? Are there any errors on the browser's development console? When you use the browser's debugging tools, does the code execute at all? Is the AJAX request made? What is the server's response? Note that the single word "Error" doesn't make for a very useful error message. You need to provide more information about the error. – David Apr 26 '19 at 13:10
  • 1
    to add to @David 's comment can we also see more code. what is `apiurl` and what event are you using to trigger the ajax call – Michael Cacciano Apr 26 '19 at 13:12
  • 1
    You must "stringify" the json object e.g. data: JSON.stringify({"features": "xyz"}), – Muhammad Faisal Apr 26 '19 at 13:13
  • 2
    No, a plain object is fine for data, see https://api.jquery.com/jQuery.post/#jQuery-post-url-data-success-dataType @MuhammadFaisal – 0xnoob Apr 26 '19 at 13:16
  • 2
    What error do you get? the error function of [$.ajax](https://api.jquery.com/jQuery.ajax/) takes three parameters: `(jqXHR, textStatus, errorThrown)`, print them out. – 0xnoob Apr 26 '19 at 13:20
  • 1
    @0xnoob — It's fine if the server is epecting form url encoded data. It isn't if the server is expecting JSON (which the example input in the question implies is the case).. – Quentin Apr 26 '19 at 13:21
  • Probably a duplicate of https://stackoverflow.com/questions/3168401/json-formatting-sending-json-via-jquery-ajax-post-to-java-wicket-server – Quentin Apr 26 '19 at 13:22

0 Answers0