Troubleshoot Cordova Camera Plugin: Ajax Call Not Executing

In my first Cordova Application, I am eager to implement Face API by Microsoft Cognitive Services. Although I have successfully utilized MS Cognitive Services in C# & XAML code, I now aim to integrate it with JavaScript for my Cordova application. Code:

var app = {
initialize: function () {
    this.bindEvents();
},
onDeviceReady: function () {
    document.getElementById("take-picture-button").addEventListener("click", function () {
        appState.takingPicture = true;
        navigator.camera.getPicture(cameraSuccessCallback, cameraFailureCallback,
            {
                sourceType: Camera.PictureSourceType.CAMERA,
                destinationType: Camera.DestinationType.FILE_URI,
                //destinationType: Camera.DestinationType.DATA_URL,
                targetWidth: 500,
                targetHeight: 500

            }
        );
    });   }   function cameraSuccessCallback(imageUri) {

appState.takingPicture = false;
appState.imageUri = imageUri;
document.getElementById("get-picture-result").src = imageUri;

// Code for Face Detection
var params = {
    "returnFaceId": "true",
    "returnFaceLandmarks": "true",
    "returnFaceAttributes": "{string}",
};
var body = { "url" : ""+imageUri };
$.ajax({
    url: "CorrectURL/detect?" + $.param(params),
    beforeSend: function (xhrObj) {
        xhrObj.setRequestHeader("Content-Type", "application/json");
        xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "KEY-Value");
    },
    type: "POST",
    data: JSON.stringify(body),
})
    .done(function (data) {
        alert("success");
    })
    .fail(function () {
        alert("error");
    });

// End of Face Detection Code }

I am facing an issue where the Ajax call is not being executed as expected. Upon checking on Azure Portal, I noticed that there are no calls registered. Seeking assistance from anyone who can provide guidance on resolving this problem.

Thank You

Answer №1

It appears that in your program, you are looking to transfer the image file to the backend for processing, but currently, only the image path stored in imgUri is being sent.

Below is a snippet of code from my own project that may be helpful to you:

//Code snippet for capturing a photo using the camera

takePhoto: function () {
                var profile = this;
                var options = {
                    quality: 90,
                    destinationType: Camera.DestinationType.FILE_URI,
                    sourceType: Camera.PictureSourceType.CAMERA,
                    allowEdit: true,
                    correctOrientation: true
                };
                $cordovaCamera.getPicture(options).then(function (imageData) {
                    var image = document.getElementById('post-img');
                    image.src = imageData;
                    profile.post.image = imageData;
                }, function (err) {
                    // handle error
                });
            }

//This section demonstrates the use of $cordovaFileTransfer Plugin

$cordovaFileTransfer.upload(config.api_url + "/user/add-post-image", filePath, options).then(function (result) {
                    var response = JSON.parse(result.response);
                    if (response.status === 0) {
                        cb("");
                    } else {
                        cb(response.data.img_path);
                    }
                }, function (err) {
                    console.log(err);
                }, function (progress) {
                    console.log(progress);
                });

The key concept here is that you need to send the actual file, not just the file path. The $cordovaFileTransfer plugin () can facilitate uploading files to the server.

If you still have any doubts or encounter issues, feel free to leave a comment and I will strive to enhance my answer for a better solution tailored to your needs.

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

The issue of basic authentication failing to function on Internet Explorer and Chrome, yet operating successfully on Firefox

Here is how my authentication code looks: public class BasicAuthenticationMessageHandler : DelegatingHandler { private const string BasicAuthResponseHeader = "WWW-Authenticate"; private const string BasicAuthResponseHeaderValue = "Basi ...

Guide on how to navigate to the bottom of a div element using Selenium Webdriver

My current project involves a unique challenge where there is a specific div element on the webpage that acts as a popup dialog when a link is clicked (similar to Facebook reaction dialog boxes). To automate tests for this scenario, I am using Selenium We ...

Using Discord.js to filter messages that start with a specific phrase and finding a solution for handling DiscordAPIError when using bulk

This is the code I am currently using. Shout out to @André Dion for the assistance. if (message.channel.type == 'text') { message.channel.fetchMessages().then(messages => { const botMessages = messages.filter(msg => msg.auth ...

The materialLoader in Three.js is experiencing difficulty loading an embedded texture image

When I export a material from three.js using the material.toJSON() method, I receive the following result: { "metadata":{"version":4.5,"type":"Material","generator":"Material.toJSON"}, "uuid":"8E6F9A32-1952-4E12-A099-632637DBD732", "type":"MeshStandardMat ...

Prevent textArea from reducing empty spaces

I am facing an issue with my TextEdit application set to Plain Text mode. When I copy and paste text from TextEdit into a textarea within an HTML form, the multiple spaces get shrunk. How can I prevent the textarea from altering the spacing in the text? T ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

Creating Shapes in Leaflet: A Step-by-Step Guide to Drawing Like a Painter

I am attempting to utilize the plugin https://github.com/tcoupin/leaflet-paintpolygon for image annotation in a multipoint circle shape. Unfortunately, the plugin is not functioning correctly as a result of a bug present in the libraries it relies on. Ar ...

Looking for assistance in stopping the parent onclick event from triggering when clicking on a child div

Is there a way to prevent the parent onclick event from triggering when clicking on a child div? Here's the scenario: <div onclick='parentClick()'> <div onclick='childClick()'> <div onlick='subchildClic ...

What is the exclusion filter in AngularJS?

I am currently working on implementing a search box with angular in my project: <input type="text" typeahead="item.name for item in list | filter: $viewValue:comparator | orderBy: '+name'"/> As part of this functionality, I am looking to ...

Delete specific rows within a grid view exclusively on the user's browser

I need to implement a feature where users can remove individual rows from a gridview on the screen without affecting the database. The gridview is populated based on the index selected from a dropdown list. Each row in the gridview should have a remove bu ...

Sending all form input data to Ajax for GET request

Today, my goal is to iterate through each textbox with an ID of setting_value, set its name and value to a key-value array, and then send that data in an Ajax request. The problem I'm facing is that it only seems to be inspecting the first instance o ...

Monitor the collection for changes before adding an item to the collection

When using ui-select multiple, I am facing an issue where I need to check the collection before ng-model="collection" is updated in order to ensure that the new value is not already present in it. Simply watching the collection does not solve this problem ...

Ways to dynamically display commas and periods based on certain conditions?

I have three items that will be displayed conditionally. I need to include commas between them, with a period at the end if it's the last item. {this.state.a&&i++} {this.state.b&&i++} {this.state.c&&i++} {this.state.a && (i==1 ...

The disabling of the `vue/multi-word-component-names` rule in EsLint cannot be overridden

Issue: [eslint] [redacted]/components/Settings.vue 1:1 error Component name "Settings" should always be multi-word vue/multi-word-component-names There is no file named Settings.vue! ❯ tree -I 'node_modules|public|assets' . ...

Tips for seamlessly transitioning the background of Google Maps into view as you scroll down the page

I have a unique background with a Google Map. It loads perfectly in the right place when I open the page, but as I scroll down, it disappears from view. Is there a way to keep the Google map constantly in the background, even when scrolling? This is my cu ...

Symfony2 AJAX form field updateIs Symfony2 form field update with

Here is a form I have: <form action="{{ path('book_create') }}" method="post" {{ form_enctype(form) }}> {{ form_start(form) }} {{ form_row(form.bookFoto) }} {{ form_row(form.bookTitle) }} {{ form_row(form.categories) }} < ...

When the width is reduced to a certain point, the display will change to inline-block, preserving the layout structure

My goal is to maintain a two-column layout for my container boxes, even when the browser width is minimized to 600px in my fiddle. The issue arises with the CSS rule display: inline-block causing the boxes to stack into a single column. Important point: I ...

Modifying the form select class when any option is chosen, with the exception of one

I have a feature that changes the class of a select input when a user selects any option. It works well, but I want the class to change back if the user selects the first option again. The first option is a placeholder without a value because I only want ...

Verify whether the image was uploaded from the camera or gallery within a mobile browser

Currently, I have the following code snippet: <input id="video-selector" type="file" name="files[]" accept="video/*,image/*" capture="camera" > I am looking for a way to determine whether an image was captured using the camera or selected from the ...

Tips for navigating between HTML pages using the onclick event in JavaScript

I'm facing an issue with a button that has an onclick event calling the function move(). The objective is to navigate to a different HTML file I created. Despite attempting to use window.location.href, it hasn't been successful. In the source fil ...