Achieving results from a function using AJAX to assign them to a variable

I have a scenario where I am attempting to assign a variable from an AJAX call that triggers a function. The code snippet below successfully logs imgurlthumbvar in the console, but when I try to display it using an alert, it shows up as undefined. After doing some research, I discovered that this issue is likely related to the asynchronous nature of AJAX. Can anyone provide assistance with this? Thank you in advance!

function fetchImage(id){
    $.ajax({
        url:'getphotos.php',
        type:'POST',
        dataType: "JSON",
        data:{id:id},
        success: function(result){
            $.each(result, function(){
                imgurl = this.imgurl;
                imgurlthumb = this.imgurlthumb;
                console.log(imgurlthumb)
                return imgurlthumb 
            })
        }
    });
}

$('#test123').click(function(){
    var test = fetchImage(7)
    alert(test)
})

Answer №1

Give it a shot

function displayImages(id) {
    return $.ajax({
        url: 'fetchphotos.php',
        type: 'POST',
        dataType: "JSON",
        data: {
            id: id
        }
    });
}
// Using AJAX to fetch data


$('#clickme').click(async function(){
    var result = await displayImages(7); // Result from AJAX call
    var imageURL;
    $.each(result, function(){
        imgURL = this.imgurl;
        thumbUrl = this.imgurlthumb;
        console.log(thumbUrl)
        //console.log('test')
        imageURL = thumbUrl 
    })

    alert(imageURL)
});

Await transforms an asynchronous call into something that resembles synchronous behavior without actually blocking the execution (sync calls can cause UI freezing)

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

Tips for creating child divs with a width that spans the entire page

When viewing multiple rows of containers on my page, the elements shift inline on smaller screens. I am looking to have the orange bar positioned behind and slightly below the header, spanning the width of the page. To achieve this, I utilized relative pos ...

Incorporating a Third-Party JavaScript Library with Vue.js

I'm attempting to integrate the library found at : into my Vue.js project. However, I am facing difficulties importing and utilizing the scripts, as well as utilizing the library in general. <script src="bower_components/wysihtml/dist/wysiht ...

What is the best way to eliminate the background color from one span after selecting a different one?

I created a span element that changes its background color when clicked, but I want the background color to switch to the newly clicked span while removing it from the previously clicked one. Can someone help me achieve this? CSS list-sty ...

How can I integrate various datasets using AJAX in jQuery?

Using jquery and ajax, I aim to execute a MySQL query when a user selects a value from a dropdown box. My goal is to pass the values from both dropdown boxes as a post request to the next page where the query will check if the values exist. I have success ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Transform a complex PHP array into JSON format using JavaScript

I have a three-tiered PHP array with both numeric indices and key-value pairs. I would like to convert it to JSON, and reiterate through the object list. How would I do this? The PHP array is called $main_array, and appears as: Array( [0] => Arra ...

Error message in Angular 2: Deletion operation is restricted

I am encountering an issue with the Angular 2 http.delete method. Below is my code snippet: const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}); this.http.delete(ConstVarService.url + 'api/tasks/Usu ...

Stop users from being able to copy text on their smartphones' internet browsers

I am currently working on creating a competitive typing speed challenge using JavaScript. Participants are required to type all the words they see from a div into a textarea. In order to prevent cheating, such as copying the words directly from the div, o ...

Display the initial three image components on the HTML webpage, then simply click on the "load more" button to reveal the subsequent two elements

I've created a div with the id #myList, which contains 8 sub-divs each with an image. My goal is to initially load the first 3 images and then have the ability to load more when clicking on load more. I attempted to follow this jsfiddle example Bel ...

Unresponsive Three.js OrbitControls

*Update: I'm feeling a bit confused because I don't believe my function is causing this issue. It seems that simply double-clicking without moving the mouse triggers this behavior consistently, even in the Three.js example. I'm still unsure ...

Error in Node.js child_process: unable to access the property '_writableState' as it is undefined

I'm currently working on integrating ffmpeg's functionality into a Node.js API by utilizing the child_process library. However, I encounter an error when trying to pass data to ffmpeg's stdin pipe, specifically getting a TypeError: Cannot re ...

Rollup.js with Vue.js displays an HTML comment instead of rendering Vue HTML content

As I delve into the world of Vue.js, I am encountering some challenges with rendering a simple interpolation within my local development application. The Issue Strangely, the Vue instance displays an HTML comment of createElement <body> <sc ...

Utilize the data storage API within Next.js or directly in the user's

Struggling to store this ini file on either the server or client, any help would be greatly appreciated. Additionally, I would like to display the ini info in the browser so that clients can easily copy and paste the information. However, I seem to be fac ...

Modify the state of a separate component in React when an onClick event occurs

I am attempting to pass state through props and I am looking to reverse it when I click an element in another component. Is this achievable? Header Component: class Header extends Component { constructor(props) { super(props); this.state = { ...

Using Firebase to loop through elements is made possible with ng

I'm currently faced with the challenge of using an ng-repeat to iterate through some JSON data that I have imported into Firebase. Below is the snippet of HTML code that I am working with: <div class="col-md-4" ng-repeat="place in places"> &l ...

The $.get route is failing to execute on the server-side, resulting in no data being retrieved. The server is not logging any information about this

I'm facing an issue where the $.get method is no longer working for me. I have simplified my code as much as possible, but it still doesn't work. Here is the code snippet: $("#test").click(function() { console.log("I'm in the on click e ...

The Bootstrap navigation bar drop-down feature is not displaying the menu

After skimming through various threads on stackoverflow regarding the dropdown box in the navigation bar, none of the solutions seem to address my issue. Utilizing bootstrap version 3, I've implemented the provided navbar example from the official si ...

Reload the Node.js webpage

Is there a method to automatically refresh a Node.js page following a socket.io event? var messageDynamic = "Initial status"; app.get("/", function(request, response) { response.setHeader('Content-Type', 'text/plain'); respons ...

The angularjs response data is mysteriously missing from the console display

I am struggling with the code below, as the data is not showing in the console log. I am new to Angular and would appreciate some help on how to display the data in HTML. this.$http.get(properties.client+'/123') .then(response => { ...

jQuery experiences difficulty in sending arrays in the JSON content type

I have a JavaScript script that looks like this: $.ajax({ url: 'myservice', type: 'POST', contentType: 'application/json', data: ["test"], }); However, when I execute the script, it sends a request to myservi ...