Achieving successful data retrieval with AJAX

I am working with an AJAX function that looks like this:

reader.onload = function(event){
    var fd = new FormData();
    var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
    console.log("name = " + Name);
    fd.append('fname', Name);
    fd.append('data', event.target.result);
    $.ajax({
        type: 'POST',
        url: 'upload.php',
        data: fd,
        processData: false,
        contentType: false,
        success: function(data){
            //console.log(data);
             $.ajax({
                    type: 'POST',
                    url: 'readFile.php',
                    data: {"fileName":fileName},
                    success: function(data){
                        console.log(data);
                    }
                });
        }
    });
};      
  1. First question: How can I retrieve the data from the second success function to utilize it later in the code?

  2. Second question: The data being retrieved is an audio file. Is there a specific method to obtain audio data, or can we retrieve it in the same way as other data types? In my PHP server-side script for the second AJAX request, I am reading an audio file and need to access its data. I have attempted a basic file open and read contents approach. Will this work for audio files?

Server-side code:

<?php
$fileName=$_POST["fileName"];

$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;

Answer №1

While not recommended, one way to address this issue is by creating a global variable at the beginning of your script and then assigning the data retrieved from an Ajax call to that variable within the success function. However, there is a potential risk in that you cannot guarantee that the Ajax call will be completed and the variable will be populated before you actually need to use it.

var myDataVar = null;

...
success: function(result) {
    myDataVar = result;
}

... // later in the script:
if (myDataVar !== null) {
    executeFunction(myDataVar);
}

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 there a way to use nightwatch.js to scan an entire page for broken images?

Hi there, I'm currently working on creating a test to ensure that all images are loaded on a webpage with just one single test. I assumed this would be a straightforward task that many people have already done before, but unfortunately, I haven' ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Integrating Project Tango with Ionic and/or Angular in a cutting-edge mobile application

I'm currently working on a mobile app project and I could use some advice. The majority of the app can be developed using angular.js (and possibly ionic) JavaScript technology. However, there is one aspect that requires integration with an API, specif ...

Attempting to verify the HTML output, yet it remains unspecified

After developing a basic testing framework, I have set myself the challenge of creating a single-page web application using vanilla JavaScript. I've been facing difficulties in figuring out why my view test is not recognizing the 'list' con ...

Using jQuery to verify the status of every input when the page loads

My jQuery price calculator is missing a feature to check if inputs are selected when the page loads. Currently, it only recognizes that Apple is checked after clicking on Banana. How can I modify it to automatically check all inputs at the start? I attem ...

Is there a way to automatically update a Django admin form in the browser whenever a value changes?

I currently have a Choice Field that requires other fields in the form to change when its value is updated. Is there a way to either refresh the entire form or update specific fields using an ajax call within the admin forms? ...

ReactJS is giving me an error message: "Uncaught TypeError: Unable to access property 'ownerDocument' since it is null."

Trying to create a bar chart using D3 and render it with React's render method. Below is my index.js file: import React from 'react'; import ReactDOM from 'react-dom'; import './Styles/index.css'; import BarChart from &a ...

Creating concise AngularJS Controllers for form functionality

While working on a web project with AngularJS, I've observed that most of my form controllers share similar structures. For instance, the only difference between my login controller (as shown below) and a reset password controller is that instead of $ ...

Using Ajax BeginForm can result in the sending of multiple requests, even when only a single

Currently, I am developing a .NET ASP.MVC application and facing an issue in one of my views where I have implemented Ajax.BeginForm. In my _Layout.cshtml file, I have included two scripts in the following order: <script src="~/Scripts/jquery-3.1.1. ...

Is there a way to obtain an automatically generated ID when using the add() method?

Currently, I am working with node, vue, and firestore in my project. One of the requirements is to have a page where the URL corresponds to the auto-generated ID of each document created using the add() method. In order to achieve this functionality, I i ...

"Enhancing security measures with multiple nonce for Content Security Policy

I am encountering an issue with my single page application, which is developed in .net core MVC 2.2. The application loads html sections on the fly. In the main document, I have added a Content Security Policy (CSP) policy with a dynamically generated hea ...

AngularJS Bootstrap Datepicker populating date from input field

I'm currently utilizing Bootstrap for my web application. I've developed a method that initializes all input fields of type date with a class called form_datetime: function initDatepicker(){ $(".form_datetime").datepicker({ ...

fabricJS: clicking on various buttons with the mouse

I have successfully created multiple canvases on the same page based on the number of PDF pages. However, I am facing an issue where some buttons to add different canvases are not working as expected. What I am attempting to do is add text on mouse down fo ...

What is the best way to set up the login page and logged-in homepage using Node, Express, and Passport with the "/" route?

I am currently in the process of developing an application using Node.js, Express.js, and Passport.js. My goal is to create a seamless user experience on the homepage where if you are not logged in, you will see a login form (with potential for additional ...

Troubleshooting: Angular.js error when Typescript class constructor returns undefined

I'm currently trying to create a simple TypeScript class, however I keep encountering an error stating this is undefined in the constructor. Class: class MyNewClass { items: string; constructor(){ this.items = 'items'; ...

How to link a CSS file from a JavaScript file

I have a form for users with fields for first name, last name, password, and confirm password. I've implemented validation to check if the password and confirm password fields match using JavaScript: $(document).ready(function() { $("#addUser").cl ...

Using HtmlUnit to initiate an Ajax call

I am looking to scrape a webpage that contains a download button. When I click on the button, the current page shows me the download progress in the title and then provides me with a download link that I can click on. From what I can see in the developer c ...

Sending selected checkboxes as part of a request to the server can automate the process of downloading a file

I am looking for a way to send checked checkboxes in a server request (for example, in Django) and then automatically download a file in response. Are there any common solutions, advice, or simple examples? I have heard that Ajax and JS (jQuery) do not off ...

Switching from hover to click on the menu

I am struggling with adjusting the function to trigger on 'click' instead of 'hover'. I have attempted changing 'hover' to 'click' and using 'toggle' but have not seen any positive outcomes. $('#menu ...

A guide on integrating Select2.js with WebForms

I am looking to make the switch from Ext.net to select2 js, but I'm struggling with integrating scripts and controls. So far, I have started a new WebForms App, installed select2 through NuGet, and attempted to replicate a sample from the Project sit ...