Utilizing Javascript to store API data in a variable for future reference

I have a requirement for my code to first go through a specific process and then extract the URL from the API for future use.

const apiKey = "_____________"
const file = document.getElementById("file")
const img = document.getElementById("img")
const url = document.getElementById("image_url")
file.addEventListener("change", ev => {
    const formdata = new FormData()
    formdata.append("file", ev.target.files[0])
    formdata.append("upload_preset", apiKey)
    fetch("https://api.cloudinary.com/v1_1/dj6n2zg0o/image/upload", {
        method: "post",
        body: formdata
    }).then(data => data.json()).then(data => {
        // Updates Image on HTML page
        img.src = data.url
        // Renders URL onto HTML
        url.innerText = data.url
        // Need to get image_url variable to newFormHandler function
        return data.url
    })
});

Once the image has been processed by the API, I then need to pass the URL to this form handler:

const newFormHandler = async (event) => {
    event.preventDefault();
 
    const name = document.querySelector('#name').value.trim();
    const initial_price = document.querySelector('#initial_price').value.trim();
    const description = document.querySelector('#description').value.trim();
    if (name && initial_price && description) {
        const response = await fetch(`/api/products`, {
            method: 'POST',
            body: JSON.stringify({ name, initial_price, description }),
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (response.ok) {
            document.location.replace('/');
        } else {
            alert('Failed to create project');
        }
    }
};

document
  .querySelector('.new-product-form')
  .addEventListener('submit', newFormHandler);

Any suggestions or guidance on this process would be highly valuable

Answer №1

After some troubleshooting, I finally found the solution. It turns out that I needed to create a global variable to store the data and use it in the form handler.

let storedData

file.addEventListener("change", ev => {
    const formdata = new FormData()
    formdata.append("file", ev.target.files[0])
    formdata.append("upload_preset", apiKey)
    fetch("https://api.cloudinary.com/v1_1/dj6n2zg0o/image/upload", {
        method: "post",
        body: formdata
    }).then(data => data.json()).then(data => {
        img.src = data.url
        url.innerText = data.url
        // Need to get image_url variable to newFormHandler function
        storedData = data
        console.log(storedData)
        return data.url
    })
});

I made modifications to the section below:

const newFormHandler = async (event) => {
    event.preventDefault();

    // Need url from storedData variable
    const {url} = storedData
    // const image_url = storedData.url
    // From Mini Project
    const name = document.querySelector('#name').value.trim();
    const initial_price = document.querySelector('#initial_price').value.trim();
    const description = document.querySelector('#description').value.trim();

    // Added image_url: url
    if (name && initial_price && description) {
        // Mini Project - const response = await fetch(`/api/projects`,
        const response = await fetch(`/api/products`, {
            method: 'POST',
            // Need to be key value pairs
            body: JSON.stringify({ name, initial_price, description, image_url: url }),
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (response.ok) {
            document.location.replace('/');
        } else {
            alert('Failed to create project');
        }
    }
};

document
  .querySelector('.new-product-form')
  .addEventListener('submit', newFormHandler);

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

Not all elements are removed by an array

$channels = array('imaqtpies','imsoff','zzero71tv', 'kaptenen', 'onlySinged', 'nightblue3') ; $nr = 0; $callAPI = implode(",",$channels); $online = 'online.png'; $offline = ' ...

Switch up div content - advertisements at the top or bottom

An issue has arisen where the ads on a website are currently being displayed at the bottom of the source code, but they should actually be visible at the top. Here is the ad placeholder code: <div id="300_250_placeholder"></div> And here is ...

What is the role of the app.use method in ExpressJS in handling URL redirects that end with a "/"?

This script automatically redirects URLs that end with a "/" to the same URL without it. For example, if a user visits http://localhost:3000/about/, they will be directed to http://localhost:3000/about. This ensures that image URLs and other HTML file refe ...

Combining Multiple Pie Charts with a Line Chart in Highcharts

Can anyone provide guidance on creating a chart similar to the one shown in the Highcharts library? https://i.sstatic.net/BoX4i.jpg ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

What is the method for determining profit as a percentage?

I need some help with a basic question. I have two variables, 'a' and 'b'. Variable A represents the money I receive from a customer, while variable B represents the money I will pay to a carrier. For example, if I receive $1000 from a ...

Upgrade the jQuery code from version 1.4.2 min to version 1.10.2 min

Hey there, I'm looking for assistance with updating the code below to use jQuery 1.10.2. The backslashes are present because I am using it with PHP and need to escape special characters. I'm not very familiar with JavaScript and unsure of the ch ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

Unable to store the user's input information in the database

I've been attempting to incorporate an "add" button feature that saves/adds/inserts data into my table. I have inputted some text in the form of tags (input type), but unfortunately, it doesn't seem to be functioning properly. Despite conducting ...

What is the best way to convert a table into a data array using jQuery?

I need help with a form and table integration. <form id="form_step" action="form_stepb.php" method="post"> Within the table, there are various rows containing dropdowns and input fields: <table class="data_table ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

Modify the color scheme of an HTML webpage

Looking to enhance my HTML page with a new feature. The page is responsive and currently using Bootstrap CSS and JS. My goal is to allow users to change the color of the page dynamically by selecting a background or text color. Check out this example link ...

Dealing with React Native: Navigating App Store Rejections and Embracing IPv6

In my react-native client for a website, the login page offers two options: manually enter the login code or scan it using a barcode scanner. I have extensively tested the app on real devices and emulators, and it's functioning correctly. However, all ...

Updating state based on input from a different component

I am attempting to modify the state of the page index in index.js from the Pagination component, Here is my index.js code: import useSWR from 'swr'; import { useState } from 'react'; const Index = ({ data }) => { const ini ...

Develop an efficient file uploading API in PHP that is constantly updating and adapting

I have been working on developing a file upload API in PHP. Currently, I have created a simple PHP script that enables the uploading of files from an HTML page to a server. However, the code I have written has a fixed name for the file upload control, whic ...

Having difficulty using replaceWith to replace text in jQuery

My favorite script successfully adds data to SQL and replaces HTML tags. I have included a text like Add Favorite and used replaceWith to display Remove Favorite. However, the output is not as expected, as shown in the image below. https://i.sstatic.net/x ...

Utilizing AJAX for seamless communication between JavaScript and PHP within a modal dialogue box

I'm struggling with learning how to effectively use ajax. In the project I'm currently working on, I have a chart where I can select different people. Once I click on a person's button, their information gets updated in the database. However ...

Prevent premature termination of slow HTTP requests in Node.js/Express server

Having an issue with long duration http requests in my React/Nodejs application. Whenever a request takes more than 4 minutes to respond, it gets aborted before reaching the client. Could there be a timeout setting for requests or something else I am overl ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...