Steps for retrieving JSON data successfully following an asynchronous AJAX request in JavaScript

When submitting a form using AJAX, I need to pass successful data back to the submission page. The transaction is being sent over the TRON network, and the response is an array containing the transaction ID that needs to be returned to the submission page.

In PHP, the code would look something like this -

$exchange_array = array(
     'success' => '1',
);
  
echo json_encode($exchange_array);

But now I'm struggling with returning data in JavaScript as follows -

$(".form").submit(function(e) {
      var url = "submit.php"; 
      $.ajax({
           type: "POST",
           url: url,
           data: new FormData(this), 
           contentType: false,      
           cache: false,            
           processData:false, 
           success: function (data) {

               // check if successful and return txid

            } 
      }); 
       e.preventDefault();
   });

In submit.php:

const sentTx= async () => {
    const tx = await tronWeb.transactionBuilder.tradeExchangeTokens(exchangeID, tokenName, tokenAmountSold, tokenAmountExpected, ownerAddress)
    const signedtxn =  await tronWeb.trx.multiSign(tx, privateKey, 0);
    const receipt =  tronWeb.trx.sendRawTransaction(signedtxn);
    var txid = signedtxn.txID;
  
    // Return txid to ajax request result
};
sentTx();

How can I successfully return the txid to the AJAX request upon completion?

Answer №1

It appears there may be a misunderstanding regarding the concept of asynchrony in javascript. success method for ajax is no longer intended for returning values. Instead, it is used to run a callback function that performs a task.

For instance, you can create a function that performs an action with data:

var myDataReader = function(data) {
  console.log(data)
}

and then invoke it within the success function like this:

$.ajax
  ...
  success: myDataReader

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 choose a mat option by pressing the tab key? It should function similarly to the enter button in a mat-autocomplete component in Angular

Is it possible to make the tab key select the mat option in a similar way to how the enter button works in mat-autocomplete for Angular 6? Currently, in the example URL provided, pressing enter selects the highlighted option, but I would like the same func ...

Why do some developers choose to use the underscore prefix in React/React-native function names?

Traditionally, in JavaScript, I would prefix "private" function names with an underscore (_) due to the lack of access modifiers. However, I find myself a bit puzzled when working on a class in languages like C++ or Java that has two functions: one for int ...

Problem with JQuery draggable and droppable appending elements

I am looking to create a functionality where a div can be dragged into another droppable div and be contained within it, while still remaining draggable inside the droppable div. However, When I try to drag the div into the droppable area, it seems to be ...

Looping through an array and appending distinct elements to a fresh array

I am currently facing an issue and seeking feedback on how to resolve it. Below is the JSON data: questions: [ { question: 'lala', answer: 'papa', categories: ['Handla'] }, { question: ...

Building a PathString Tree

I encountered a similar issue like the one discussed in this post (Get a tree like structure out of path string). I attempted to implement the suggested solution but I am facing difficulties getting it to work within an Angular context. The concept involv ...

Is it possible to update the text in a select input from a dropdown menu within

In my example modal, I have included two components: a dropdown and an input text field. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Test Modal</button> ...

Error encountered while utilizing MUI Button: Unable to access property 'borderRadius' from an undefined source

import React, { Component } from 'react'; import './App.css'; import Screen from './components/Screen/Screen'; import Button from './components/Button/Button'; import { MuiThemeProvider, createMuiTheme } from 'm ...

Designing a Curved Stepper Component in the Shape of an S

I've been attempting to create a custom stepper component with an S-curve shape using React, but so far I haven't been successful. I even tried utilizing the MUI Stepper component and experimented with pure HTML and CSS, but couldn't achieve ...

When utilizing the useLocation feature of React-Router-DOM to retrieve data passed in React, it can cause manually inputted links to malfunction

When manually inputting a link that is incorrect (e.g., "/characters/test"), it initially works fine, but if the link is correct, it still redirects to error 404. However, clicking the link from the Character component functions properly. This me ...

Issue encountered when attempting to display JSON index on individual result page

This is a JSON response. { "listing": { "id": "1", "name": "Institute Name", "contact": "9876543210", "website": "http://www.domain.in", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Populating a MySQL database with data from an array using PHP

Struggling a bit with this task and hoping for some guidance. The challenge is to transfer shopping cart basket products from MySQL to an "order-details" table at checkout, rather than using sessions in this case. The product array is successfully create ...

Checking the alignment of a label or element in the center of a webpage using javascript

I am new to JavaScript and was attempting to determine if an element is centered aligned by accessing its CSS properties/values. Can someone help me retrieve the CSS property to verify text alignment using JavaScript? ...

Issue with AjaxComplete function failing to work

Currently, I am tackling the Opera workaround for printing IFrames. As we are aware, the only method to print an IFrame is by opening it in a new window and then printing it. However, I am encountering an issue where a series of ajax calls are triggered wh ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

Axios failing to retrieve nested data in get request

Having an issue with getting a 2d array using axios in my code. When I try to console.log it, it returns empty. Any suggestions? Here's the piece of code causing trouble: let orig = [] axios .get(<endpoint url here>) .then ...

What is the best way to send a React prop that is buried deep within a JSON structure?

Currently, I am in the process of creating a product table to showcase items for a store. The headers of this table include: id, title, imagePath, newPrice, oldPrice. To accomplish this, I have developed an ItemTable component within my React application t ...

A JSON object received from an AJAX request is either null or empty

I recently deleted a previous question that I had posted because it was no longer relevant and there was another issue to address. The response provided below is very clear, more so than other responses, and I believe it will be beneficial for anyone else ...

What do you call a function that serves no purpose?

Consider a scenario where you have a function defined as: function FunctionT(){ //do something } When describing this function, would you classify it as empty, undefined, or can either term be used interchangeably? Is there a specific designation for thi ...

Issues with Success Function in $.ajax() Call

Currently, I have an AJAX form set up to submit data to a controller function in the background using AJAX. However, even though the function returns a 200 response and the response is visible in Firebug, the success and error functions are not triggering ...

JavaScript: Creating keys for objects dynamically

const vehicles = [ { 'id': 'truck', 'defaultCategory': 'vehicle' } ] const result = [] Object.keys(vehicles).map((vehicle) => { result.push({ foo: vehicles[vehicle].defaultCategory }) }) c ...