What is the process to include an image file in a JSON object using PhoneGap?

Having trouble saving an image in JSON. Managed to access the mobile camera with the provided code:

var pictureSource;   // source of the picture
var destinationType; // sets the format of returned value 

// Wait for PhoneGap to connect with the device
//
document.addEventListener("deviceready", onDeviceReady, false);

// Ready to use PhoneGap!
//
function onDeviceReady() {
    pictureSource = navigator.camera.PictureSourceType;
    destinationType = navigator.camera.DestinationType;
}

function onPhotoFileSuccess(imageData) {
  // Get image handle
  console.log(JSON.stringify(imageData));

  var smallImage = document.getElementById('smallImage');

  smallImage.style.display = 'block';

  smallImage.src = imageData;
  location.href = "#pageone";
}

function capturePhotoWithFile() {
    navigator.camera.getPicture(onPhotoFileSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}

function onFail(message) {
  alert('Failed because: ' + message);
}

Encountering issue where a form with text is supposed to take and save a picture. Here's the code adding and saving the form without the image:

function Add(){
var client = JSON.stringify({
repairNum : $("#repairNum").val(),
fname    : $("#fname").val(),
lname  : $("#lname").val(),
address : $("#address").val(),
});
jewelryRepair.push(client);
localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
alert("The data was saved.");
return true;
}

Questioning how to incorporate the image file into the add() function. Thank you!

Answer №1

If the Add() function is called after onPhotoFileSuccess(), you can implement the following in your Add() function as shown below. The image data will be encoded within a data URL.

function Add(){
        var client = JSON.stringify({
            repairNum : $("#repairNum").val(),
            fname    : $("#fname").val(),
            lname  : $("#lname").val(),
            address : $("#address").val(),
            photoData: $("#smallImage").attr("src")
        });
            jewelryRepair.push(client);
            localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
            alert("The data was saved.");
            return true;
    }

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

Hidden button trigger is malfunctioning

I am attempting to activate a hidden button, but the event does not seem to be triggering. Here is the code snippet: <div class="dyn-inp-group"> <div class="dyn-inps"> <div class="form-group form-group-options col-xs-12 dyn-inp" ...

"Implementing a method to convert a varbinary array returned in JSON to an image and displaying it on an ImageView in an

need assistance in converting a varbinary array returned by a web service to an image and displaying it on an imageview. any help would be greatly appreciated. thank you. ...

At what point does a dynamically loaded CSS file in the head section of a webpage actually

If the answer is already out there somewhere, I would really appreciate a link because I just can't seem to find it. When loading .php pages, I either include 'header.php' directly with <?php include 'header.php'; ?> or on ...

Tips on altering the location path when redirecting to a different page using window.location?

Is it a silly question to ask? I tried looking for the answer on Google but couldn't find it. I'm currently working on a website where users can upload photos or videos, using HTML, CSS, and JavaScript. On the homepage, when a user clicks on a ...

Converting a timestamp from PHP in JSON format to date and time using JavaScript

Within the JSON file, there is a timestamp associated with each user login. An example of this timestamp is: timestamp: "1541404800" What steps should be taken to convert this timestamp into date and time format? ...

The chai expect statement is causing an assertion error that I am currently encountering

Exploring the combination of different data types using a simple addition function. For instance, when adding 1 + 1, we expect to get 2, and when adding 1 + "one", the result should be "1one". Below is the content of my functions.js file: module.exports = ...

How to use a string condition to filter a list of objects in Javascript?

Below is the structure of the object: var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5, "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ]; Given the condition ...

Error message in Angular js: Unable to load file using XMLHttpRequest

Encountering an error while debugging an Angular JS application in the WebStorm IDE. The error message states: "XMLHttpRequest cannot load file:///C:/Users/../list.html. Cross origin requests are only supported for HTTP." Provided Javascript code : var a ...

CKEditor directive in AngularJS does not properly enforce the maxlength attribute in textarea

I am currently working on an AngularJS application with the CKEditor plugin. I have created a directive for CKEditor and everything seems to be functioning properly. However, I am facing an issue where I need to limit the character length to 50. I tried us ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

Utilizing Angular 2's Routerlink with *ngIf and Parameters

Currently, I am facing an issue with a routerlink that includes a parameter: http://localhost:4200/item/1 I am trying to figure out how to implement an *ngIf statement with a parameter.... Here is what I have attempted so far: <div *ngIf="router.url ...

Understanding JSON Arrays using jQuery

I've been attempting to display JSON objects in the console, but unfortunately, I'm facing some issues. The JSON data is obtained from a small API that I crafted using PHP. Here's a snippet of my JSON: { TotalResults: 2, Results: [ ...

implement css styling to grid view upon clicking

I have been attempting to add a background color to a grid view row when clicked on that specific row. <script type="text/javascript"> function ChangeRowColor(objref) { objref.style.backgroundcolor = "red"; } </sc ...

When JSON.stringify is used to convert an object to JSON, it will result in

I'm having difficulty creating a JSON object for transmission over the network. The particular array I'm dealing with looks like this in the Chrome debugger. event: Array[0] $$hashKey: "02Q" bolFromDB: 1 bolIndoor: null ...

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

Searching within an array in MongoDB can be easily accomplished using the

I have encountered a challenge with my mongodb JSON array as I am struggling to locate specific categories, for example: { name:"hoyts"} I have attempted various queries like {categories.name:"hoyts"} but unfortunately, none of them have yielded the desi ...

What are the steps to creating a screen that mimics a mirror in the physical world?

Is there a way for the user to see themselves when they open a URL? I'm not looking for a mirror effect like the one produced by jQuery reflection js. I don't want to rely on using the front camera or any other camera to achieve this. Any sugges ...

When using Next.js, an error may occur when trying to use DOMPurify.sanitize(), displaying a TypeError message saying that dompurify__WEBPACK_IMPORTED_MODULE_6___default

Utilizing DOMPurify.sanitize() within dangerouslySetInnerHTML={{}} to render the innerHtml retrieved from the database. Initially, I'm employing getServersideProps() alongside next-redux-wrapper for this specific page. Installed dompurify using: npm ...

The computed function in Vue.js fails to provide a return value

I'm currently experimenting with a basic to-do list using vue.js. My goal is to calculate the total sum of all price values within an array. I created a small function under computed, but it seems like something isn't working correctly. Here&apos ...