Assign a variable to the result of ajax that remains unchanged until it is specifically invoked

I am currently working on the final part of my radio script, specifically focusing on the "last song" section. My goal is to retrieve a URL from an external PHP script, play the song, and once the song ends, I want to set a global variable equal to the current URL by calling a function. This global variable should remain unchanged until the function is called again and updated with the next song.

Despite several attempts, I keep encountering errors such as 'undefined' or 'Uncaught TypeError: Cannot set property 'innerHTML' of null'. The code snippet below exemplifies this issue:

var data = $.ajax({
url: '../scripts/radio.php',
data: {
attr1: 'value1'
},
success: function(data) {
console.log(data);
}
});

function playFirst(){

var lastSong = data;
document.getElementById("songName").innerHTML = data;
fileChosen = true;
setupAudioNodes();

var request = new XMLHttpRequest();

request.addEventListener("progress", updateProgress);
request.addEventListener("load", transferComplete);
request.addEventListener("error", transferFailed);
request.addEventListener("abort", transferCanceled);

request.open('GET', data, true);
request.responseType = 'arraybuffer';

// When loaded decode the data
request.onload = function() {

$("#title").html("Infinite");
$("#album").html("Infinite");
$("#artist").html("");
onWindowResize();
$("#title, #artist, #album").css("visibility", "visible");

// decode the data
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
sourceNode.buffer = buffer;
sourceNode.start(0);
$("#freq, body").addClass("animateHue");
//on error
}, function(e) {
console.log(e);
});
};
request.send();
};

Answer №1

Upon receiving data in the success callback, it is important to store it for future use. If the returned data is not stored, it will remain as undefined when the function playFirst() is invoked.

An effective way to handle this is by saving the returned data in a global variable. Here is an example:

let data;
$.ajax({
    url: '../scripts/radio.php',
    data: {
        attr1: 'value1'
    },
    success: function(returnData) {
        data = returnData;
        console.log(data);
    }
});

Alternatively, you can directly call the playFirst() function within the success callback, passing the received data as an argument:

$.ajax({
    url: '../scripts/radio.php',
    data: {
        attr1: 'value1'
    },
    success: function(data) {
        playFirst(data);
    }
});

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 trigger a function after a tooltip or popover is generated using Twitter Bootstrap?

Is there a way to manipulate a tooltip or popover with twitter bootstrap after it has been created? It seems like there isn't a built-in method for this. $('#selector').popover({ placement: 'bottom' }); For instance, what if I ...

Issues with the plugin for resizing text to fit the parent div's scale

I've spent the last hour attempting to get this script to function properly, but no luck yet. Check out the correct jsfiddle example here: http://jsfiddle.net/zachleat/WzN6d/ My website where the malfunctioning code resides can be found here: I&apo ...

Error with Webdriver/FXDriver utils.js leading to Firefox unresponsive script issue

While running browser tests with Watir webdriver and FXDriver, everything seems to be functioning well except for one test that loads a lightbox containing a large amount of HTML. When this lightbox opens, Firefox displays a popup indicating that Utils.js ...

I am having trouble retrieving the photo URL link when using the Facebook Graph API

I've been working with the Facebook Graph API and encountering an issue. I am trying to retrieve a photo URL using the post_id, however, it is not returning the desired link. I need this URL for future operations. Is there anyone who can assist me in ...

connection and navigation hiccup

In my current project, I am utilizing Redux and React. Within App.js, I've implemented some Routes and also make use of the connect function from react-redux. In order to avoid any potential update blocking issues, I typically wrap my component in the ...

angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so: constructor(private _http: HttpClient) {} getUsers(location){ return this._http.get(`https://someurl?location=${location}`) .pipe( map((response: any) => response), ...

What causes a browser to redirect when trying to update the value of the alt field in a Wordpress media image?

Attempting to create a bookmarklet for the Wordpress image gallery manager that triggers the sidebar when an image is clicked. The sidebar contains fields for alt text (input), legend, and description (both textarea). <a href="javascript:var t=document ...

Ways to transfer a PHP variable to Ajax

Is there a way to display the title variable in an AJAX request using PHP and jQuery? PHP <?php $title = "Test-1"; ?> Ajax $(".btn").click(function () { if ($(".main-input-box").val().length > 0) { $(".btn").load("results ...

Problematic Angular 6 Lazy Loading Situation

Below is the code snippet I am using for lazy loading: const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'manager', lo ...

Ways to execute a function when a button is clicked with a shared variable?

When creating buttons in HTML to control video speed, I encountered a strange issue. After successfully implementing the buttons for one video, they only worked on a second video and had no impact on the first one. Deleting the second video seemed to resol ...

The object function router(req, res, next) is encountering an error as it does not contain the required method for handling the request

I am trying to add a new row to my MySQL database, but I encountered an error message. Here is the scenario: I have set up Passport and hjs in my project. I am passing form data from app.js to a JavaScript file where I aim to insert the data. Object funct ...

Using AJAX or a CRON JOB to trigger the execution of a PHP script that includes a sleep function

I've created a PHP script that pulls X records from a database and processes them one by one every 10 seconds. This script needs to be compatible with both a Cron Job and an AJAX call via browser. The cron job aspect is functioning correctly - I hav ...

What seems to be the issue with the data initialization function not functioning properly within this Vue component?

In my Vue 3 component, the script code is as follows: <script> /* eslint-disable */ export default { name: "BarExample", data: dataInitialisation, methods: { updateChart, } }; function dataInitialisation() { return { c ...

Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snipp ...

How can I refresh the container with a new version of the file using PDFObject?

I'm having trouble with a button that generates a PDF and then reloads the PDF in the browser by replacing the container it's in, but with a different link. Despite my efforts, the new PDF does not show up and the old one remains even after refre ...

The regex path matching issue in next.config.js is being caused by the pattern not being able to start with "?"

In my upcoming project, I attempted to utilize regex path matching in the next.config.js file as explained in the documentation. The goal was to match all routes except for one specific route by adding the regex ^(?!.*books). which successfully excludes an ...

Delete ObjectId from Array using Node and Mongoose

Currently, I am working on a website that features a comments section for campsites. This platform is similar to Yelp but focuses on reviewing campsites. Each campsite in the MongoDB collection has a field called "comments" which stores the IDs of all comm ...

Is the AngularJS application failing to transmit data accurately to Node.js?

I've been grappling with this issue for a few days now and I can't seem to pinpoint the problem. As someone relatively new to the MEAN stack, I might be overlooking something obvious. I followed the boilerplate code from mean.io for both the back ...

The storage of HTML5 data is not being saved locally

<html> <head> <title></title> <style type="text/css"> body { font-family: tahoma; } h2 { font-weight: bold; border-bottom: 2px solid gray; margin-bottom: 10px; } #dat ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...