Performing a javascript ajax call to interact with the Microsoft Emotion API

I'm currently experimenting with the Microsoft Emotion API using a simple Python web server that has CORS enabled. Below is the Python file I use to start the server:

python-server.py

#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

class CORSRequestHandler (SimpleHTTPRequestHandler):
    def end_headers (self):
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

if __name__ == '__main__':
    BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)

In my index.html file, I have included the following code for sending the HTTP request:

index.html

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        $.ajax({
            url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",JSON.stringify({"my-key"}));
            },
            type: "POST",
            // Request body
            data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>

After approximately 30 seconds, I encounter a connection refused response. The code for the HTTP request was copied from the associated emotion API page. I am uncertain if this issue is due to requiring a real server or if there's an error in the code itself. Any insights would be appreciated. Thanks.

Answer №1

For the JSON to be transmitted, it should be in string format. Therefore, modify your body specification to:

data: "{\"url\": \"http://...\"}"

Answer №2

Feel free to utilize the following code snippet (remember to replace your-key with your actual key). Simply save it as a .html file and open it in your browser - it should work without requiring any server connection. If successful, you can then try running it on your Python server.

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
    $(function() {
        $.ajax({
            url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","your-key");
            },
            type: "POST",
            // Request body
            data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>

Answer №3

<!DOCTYPE html>
<html>

<head>
  <title>Facial Recognition API Implementation</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>

<body>

  <script type="text/javascript>
    $(function() {
      $.ajax({
          url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
          beforeSend: function(xhrObj) {
            // Setting the request headers
            xhrObj.setRequestHeader("Content-Type", "application/json");
            xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",
              "");
          },
          type: "POST",
          // Request body
          data: JSON.stringify({
            "url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
          }),
        })
        .done(function(data) {
          console.log(data);
        })
        .fail(function(e) {
          console.log(e);
        });
    });
  </script>
</body>

</html>

https://i.sstatic.net/bmPzS.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for an AngularJS directive to compile a fresh element that has a second directive assigned to it?

UPDATE: All directives listed below will now require ng-model bindings to be applied in the elements they generate, targeting the controller assigned to the page. The code has been modified to reflect this. I am exploring the creation of dynamic HTML usin ...

Retrieve values from PHP using AJAX to dynamically update input field values

I have set up a unique Custom Post Type in Wordpress named Location/Tour and another one called Itinerary. Within my CPT Itinerary, I have integrated some ACF custom fields, including a repeater field containing various subfields (such as Relationship fiel ...

What is the method for retrieving the Java List containing custom class objects defined within the <s:iterator> tag in a JSP file from within my JavaScript function?

Within my jsp file, I am retrieving a List of objects from my java action class (struts2) and displaying them. Now, I need to access these list objects within my javascript method. How can I achieve this? The code in mycode.jsp: <script type="text/jav ...

What could be the reason for attempting to insert metadata into a Google Drive document resulting in it being saved as plain text

I'm working on updating the metadata of a file that was previously uploaded to Google Drive. The metadata includes the title and description. However, I've noticed that when I submit the file, the name remains unchanged. The metadata seems to be ...

guiding user immediately to blog post upon successful login

I recently created a blog with a customized URL like instead of the traditional . Now, my dilemma is that I want to share this URL and have it redirect users to the login page if they are not logged in. Once they log in, I would like them to be redirect ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

What is the technique for choosing the parent's ID with jQuery?

When a user clicks on any team, I need to retrieve the parent's parent ID. For example, if someone clicks on a Premier League Team, I want to store the ID 2 in a variable called league_id. Here are my attempts so far: Using Closest Method $('u ...

using absolute URLs for image source in JavaScript

How can I output the absolute URLs of images in a browser window (e.g., 'www.mysite.com/hello/mypic.jpg')? Below is a snippet of my code: $('img').each(function() { var pageInfo = {}; var img_src = $(this).attr('s ...

Troubleshooting a problem with the skybox texture in Three.js

I am currently experimenting with creating a basic Skybox using Three.js, but I've encountered an issue where the texture I'm applying to the cube is only visible on the outside and not on the inside. Below is the code for my skybox: const path ...

Exploring the use of jQuery or other JavaScript libraries for creating dynamic web applications

After completing a mid-level web application recently, I utilized Telerik controls along with native JavaScript functions in collaboration with other developers on the project. We encountered numerous cross-browser issues using this approach, although we ...

Exploring user inputs and displaying variables using JavaScript and HTML 4.01

I was testing some code and I'm facing an issue that I can't figure out: <HTML> <head> <title> Page 1 </title> <script> function myFunction() { var x=document.getElementById("myEmail") document.write(x) } </scr ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

a problem with the display toggling feature in VueJS regarding the "Show more" / "Show less"

Hey everyone, I am currently working on a filter feature using VueJS and Laravel. I'm facing some challenges with the (Show more) / (Show Less) button functionality. The issues are: Issue 1: Normally when you limit a list of items, it should show a "S ...

Attempting to understand how to retrieve specific items from my MongoDB Database that are associated with a particular user based on their ID

I've been attempting to retrieve specific items (Portfolio pics) that have been submitted by a user from my Mongo Database. However, when I checked the extracted items using Console logs, it seems to display all portfolio pieces for every user instead ...

why is the sum coming out as an undefined number?

My challenge involves creating a table that should display the total price, however, it keeps showing NaN. The code snippet below outlines how the total price is calculated: import React from 'react'; const Total = (props) => { const {ite ...

What is the process for adding a custom header when making an ajax call in a datatable?

Currently, I am utilizing datatables and need to include a custom header for specific server-side requirements. Can anyone provide guidance on how to send a custom header when navigating to the next or previous pages using jQuery datatables? Additional ...

Implementing Mock AJAX Calls Using NSURLProtocol

I am using a UIWebview to make AJAX calls to external services. When the device is offline, I need to intercept these requests and return local JSON data instead. To achieve this, I have implemented a NSURLProtocol to catch the AJAX requests. However, I a ...

Vue Router - Checking if Paramater Exists in an Array

Looking for a solution: /browse/:type/:id? Is there a way to check if the value of :type is included in a predefined array of valid options? ...

Guidelines for accessing .csv files using Python

Having trouble opening the file called inflammation-01.csv. Check out the full activity here. The error message keeps saying it cannot locate the specified file. import numpy fname = 'inflammation-01.csv' numpy.loadtxt(fname, delimiter=',& ...

Retain the user's input in the text box even after the form has been submitted

Currently, I am tackling the challenge of creating a register form with an error handler to manage any mistakes made by users during registration. Once the form is submitted, potential errors are displayed to the user. To enhance user experience, I am ex ...