Maximizing JavaScript efficiency: Returning a value within an if statement in an AJAX call

In my function, I have a condition that checks the idType. If it is 1, an ajax call is made to a php file to retrieve the name associated with the specific idName and return it. Otherwise, another example value is returned.

function obtainName(idName, idType){
   var resultString = ""
   if(idType == 1){
       
       $.ajax({
           type:"GET",
           url:"myFile.php",
           dataType:"JSON",
           data:{idName: idN},
           success: function(data){
              resultString = data.name 
              console.log(resultString)
              return resultString   
           },
           error: function(d){
           
           }
       });

   } else {  
       resultString =  "otherValueName" 
       console.log(resultString)
       return resultString
   }
}

When calling this function with specific id names, get_name is utilized with the corresponding idName and type. The for loop is omitted in this example.

function displayObtainedName(exampleIdName){
    var string= get_name(exampleIdName, 1);
    console.log(string)
    return string
}

Lastly, the name is printed out:

displayObtainedName("Alex");

However, if idType is 1 and triggers an ajax call, the result appears as undefined. In the console, the outcome of the variable "string" in the displayObtainedName function shows as undefined. But the value assigned to the variable "resultString" in get_name is correct.

What can be done to solve this issue?

Answer №1

If you want to achieve your desired outcome, there is a simple method you can follow. Simply set the ajax call to sync mode. By default, jQuery Ajax calls run in Async mode, but by adding "async: false" as another argument, we can make it run in Sync mode. Here is a functional example of the solution: 1. Return the promise from the function and handle the promise to obtain the result. 2. Use async: false for synchronous execution.

  1. HTML 2. Example JSON data (data.son)

         <!DOCTYPE html>
     <html>
    
     <head>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
         <script>
             $(document).ready(function () {
    
                 function get_ContentWay1(idName, idType) {
                     var resultString = ""
                     if (idType == 1) {
                         return $.ajax({
                             type: "GET",
                             url: "data.json",
                             dataType: "JSON",
                             data: { idName: idName },
                             success: function (data) {
                                 resultString = data.employee.name;
                                 console.log(resultString)
                             },
                             error: function (d) {
    
                             }
                         });
                     } else {
                         resultString = "otherValueName"
                         console.log(resultString)
                         return new Promise(function (resolve, reject) {
                             resolve(resultString);
                         });
                     }
                 }
    
    
    
    
                 function get_ContentWay2(idName, idType) {
                     var resultString = ""
                     if (idType == 1) {
                         $.ajax({
                             type: "GET",
                             url: "data.json",
                             async: false,//You need to pass this
                             dataType: "JSON",
                             data: { idName: idName },
                             success: function (data) {
                                 resultString = data.employee.name;
                                 console.log(resultString)
    
                             },
                             error: function (d) {
    
                             }
                         });
                     } else {
                         resultString = "otherValueName"
                         console.log(resultString)
                     }
                     return resultString;
                 }
    
                 $("button.btnWay1").click(function () {
                     var idType = $(this).attr("idType");
                     var idName = $(this).attr("idName");
    
                     // Way 1
                     var contect = get_ContentWay1(idName, idType).then((result) => {
                         if (result != "otherValueName")
                             $("#div1").html(result.employee.name);
                         else
                             $("#div1").html(result);
                     }).catch((err) => {
                         alert("error");
                     });
                 });
    
                 $("button.btnWay2").click(function () {
                     var idType = $(this).attr("idType");
                     var idName = $(this).attr("idName");
    
                     //Way 2
                     var contect = get_ContentWay2(idName, idType);
                     $("#div1").html(contect);
                 });
             });
         </script>
     </head>
    
     <body>
    
         <div id="div1">
             <h2>Let jQuery AJAX Change This Text</h2>
         </div>
    
         <button class="btnWay1" idType="1" idName="abc">Get External Content Way 1</button>
         <button class="btnWay1" idType="2" idName="abc">Don't Get External Content Way 1</button>
    
         <button class="btnWay2" idType="1" idName="abc">Get External Content Way 2</button>
         <button class="btnWay2" idType="2" idName="abc">Don't Get External Content Way 2</button>
    
     </body>
    
     </html>
    

        {  
        "employee": {  
            "name":       "sonoo",   
            "salary":      56000,   
            "married":    true  
        }  
    }  

Answer №2

It appears that there is a mistake in your code:

function get_name(idName, idType){
   var resultString = ""
   if(idType == 1){
       
       $.ajax({
           type:"GET",
           url:"myFile.php",
           dataType:"JSON",
           data:{idName: idN}, // You should be passing idName instead of idN
           success: function(data){
              resultString = data.name 
              console.log(resultString)   
           },
           error: function(d){}
       });

   } else {  
       resultString =  "otherValueName" 
       console.log(resultString)
   }

    return resultString;
}


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

What is the best way to transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...

Managing data in React and JavaScript: Clearing fields upon successful sign up and redirecting to login page after receiving a 200 status code

Here is the code for my SignUp react function. After receiving a response of 200 upon clicking the Sign up button, I want to clear the text in all three fields and redirect the user back to the login page. I'm new to web development so any assistance ...

jQuery fade in problem or alternate solutions

When I send a post request to a file and input the response into id='balance', I would like it to have a flickering effect or fadeIn animation to alert the user that it is being updated in real time. I attempted to use the fadeIn() method but it ...

Getting Info from Eventbrite API Request Parameters

Looking to fetch a list of popular events specifically in San Francisco using an ajax request to the Eventbrite API. Check out the code snippet below. let city = 'San Francisco'; let query = "token=" + token + "&venue.city=" + city + "&p ...

Executing multiple jQuery.ajax() requests in sequence

Hi there! I could use some assistance with jQuery Ajax calls. I'm working in JavaScript and need to send ajax requests to the controller, which then retrieves a value from the model. I have to check this returned value and potentially make more ajax c ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...

Protecting multiple form submissions with a CSRF token

Two forms are present on a single page, each declared as follows: form_for @student, {remote:true, format: 'json'} do |f| and form_for @teacher, {remote:true, format: 'json'} do |f| Upon clicking the submit button for the teacher fo ...

The internal cjs loader in node threw an error at line 1078

I'm encountering an error on Windows 10 when running the npm command: node:internal/modules/cjs/loader:1063 throw err; ^ Error: Cannot find module 'D:\mobile-version portfolio\ at Module._resolveFilename (node:internal/modules/cjs/load ...

When the state of the grandparent component is updated, the React list element vanishes in the grandchild component. Caution: It is important for each child in a list to have a unique

In my development project, I've crafted a functional component that is part of the sidebar. This component consists of 3 unique elements. ProductFilters - serves as the primary list component, fetching potential data filters from the server and offer ...

Having trouble retrieving data from Laravel's JSON response object

This is one of the weirdest bugs I've come across in my coding experience. When a user submits a reply through AJAX in my controller, I'm returning a JSON response to retrieve the ID of that reply. $reply = Status::create([ 'body' ...

Can you explain how to utilize prop values for setting attributes in styled-components v4 with TypeScript?

Overview Situation: const Link = styled.a` border: solid 1px black; border-radius: 5px; padding: 5px; margin: 10px 5px; `; type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>; const LinkAsButton = styled(Link).attrs<ButtonP ...

Inconsistencies with AJAX performance

Hey there, I'm a newbie and absolutely loving this site! Currently diving into the world of JavaScript and have been through numerous tutorials. However, I seem to be struggling with getting Ajax to work. Recently stumbled upon this code snippet on ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

An invalid primitive was encountered in the JSON data

I am trying to pass the number of seats to TryJSIN.aspx in my function test(), but I keep encountering errors. When I use type 'GET', I get the following error: "Invalid JSON primitive: 1-9." The value 1-9 represents the number of seats. Howe ...

Determine if an object has been submitted in a MEAN / AngularJS application

I am working with an AngularJS frontend and using Express, Node, and MongoDB on the backend. My current setup is as follows: // my data to push to the server $scope.things = [{title:"title", other properties}, {title:"title", other properties}, {titl ...

"Encountering a 404 error with the angular2-in-memory-web-api

Currently, I am in the process of developing a 5 minute application using Angular 2 with reference to this particular guide: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html. While working on the HTTP section, I encountered a 404 error due to the a ...

Headers can't be set after they have been sent. This issue arises when calling create(data,cb) function

I am a beginner in Node.js and I am attempting to create a model in MongoDB. However, when I make a call to localhost:3000/a, I notice that the request is being sent twice in the console and I am encountering an error stating "Can't set headers after ...

What is the best way to incorporate a background image in a Bootstrap tooltip?

I'm having trouble displaying an element with a background-image property within a Bootstrap tooltip. The image is not showing up as expected. <div class="big-panel"> <a href="#" data-bs-toggle="tooltip" data ...

Obtaining Data from CRM 2011 with the Power of jQuery and JavaScript

Currently, I am facing an issue while attempting to retrieve data from CRM 2011 using jQuery. Despite my efforts, I am unable to successfully fetch the desired data. Below is the code that I have been working on: function GetConfigurations() { var oDataP ...

I encountered an issue with my PHP script when trying to interpret a JSON file

I encountered an error stating "requested JSON parsing failed". I have written a PHP script to retrieve data from the server side, but I realized that PHP is not installed. Do you think this is required for the script to run properly? Could this be the r ...