Search code examples
phpjqueryajaxhttpjsonp

How to POST to a URL encoded API that returns text?


I have a unique situation. We are using Ytel's X5 cloud contact center. They have an API that will allow us to add people to our database.

You send the data to the API via GET (strange, I know, but I have no control over the server, as it is owned by Ytel).

So I have URL encoded all of my fields. I know that the resulting string is correct, because If I copy the string and paste it into my browser and hit enter, I get a success message.

The success message is plain text.

What would be the correct way to make a call to this type of API?

I tried using jQuery/Ajax but kept getting "Allow-Control-Access-Origin header is not present, therefore localhost is not allowed...". So then I tried setting the "datatype" to "jsonp".

    jQuery.ajax({
    url: ytelPostingString,
    cache: false,
    type: "POST",
    dataType: "jsonp",
    //What do you want to do when the request succeeds?
    success: function(result) {
        console.log(result);
        console.log("Success");
    },
    //What do you want to do when the request fails?
    error: function(result) {
        console.log("Error:" + result);
        console.log("Failure");
    }

});

And this worked! It successfully put the data into the database, the only downside is, the response from the server is NOT jsonp, it's plain text. So the "error" callback will always be called, even if the api request was successful, because ajax is expecting a jsonp object to be returned.

So now I'm trying to make an API call via PHP, But I still don't know what the "correct" way to do so is?

Is it possible to "open" a webpage in javascript (or PHP) and store the output (aka the "webpage") to a variable, which I can then evaluate?

Another interesting note, file_get_contents fails if I call urlencode(URL) or rawurlencode(URL) BEFORE file_get_contesnts(URL). For some reason urlencode and rawurlencode is encogind the : and the / which causes file_get_contents to fail. any ideas?


Solution

  • TO ANYONE READING THIS IN THE FUTURE:

    I had to POST my values to a php script on my server, and use PHP to make the API call. It was as simple as calling file_get_contents($URL);

    NOTE: In order for file_get_contents(); to work on a URL, you MUST have "allow_fopen_url" set to "yes" in your PHP.ini file.