Having difficulty defining variables with the user input in an AJAX request

I have created an HTML input for users to enter a zip code, and I have a JavaScript variable set to capture that input. When I console.log this variable, I can see that it is successfully set as a string. However, when I try to make an AJAX call with the zip code input, it doesn't seem to work. Even though I console.log the variable at different stages and confirm that it has been updated, there seems to be some hoisting issue where the value in the AJAX call always reverts back to the initial setting. The AJAX call only works when 'userInputZip' is initially set to a valid zip code. Any assistance would be greatly appreciated.

$(document).ready(function(){
});//end of document.ready

var inputDate = '2015-12-04T20:00:00';
var inputZipCode = '60618';
var userInputZip;

function runAjax(){
console.log(userInputZip);
$.ajax(getJambaseData);
}

// var dataArr = [];

var getJambaseData = {
  type: 'get',
  url:
  'http://api.jambase.com/events?zipCode='+userInputZip+'&api_key=[inserted my key here]',

  // 'http://api.jambase.com/events?zipCode='+userInputZip+'&api_key=[inserted my key here]',
  success: function (data){
    for (i=0; i< 10; i++){
      if(data.Events[i].Date == inputDate){
      var shortDate = data.Events[i].Date.substring(0,10);
      var shortTime = data.Events[i].Date.substring(11,19);
      // dataArr.push(data.Events[i].Date, data.Events[i].Artists[0].Name);
      $("#divID").append('</p>' + 'date::: '+ shortDate + ' time:::' + shortTime + ' show::: ' + data.Events[i].Artists[0].Name + ' time::: ' + data.Events[i].Date + ' address::: ' + data.Events[i].Venue.Address + ' city::: ' + data.Events[i].Venue.City + '</p>');
    }
  }
  },
  error: function(){
    console.log('failed');
  },

}

function findShows(){
  var userZip = document.getElementById("userInput");
  userInputZip = userZip.value;
  document.getElementById("divID").innerHTML = userInputZip;
  runAjax();
}
////////////////////

Answer №1

You made mention of

however, there seems to be a hoisting issue or something similar where the value of 'userInputZip' in the ajax call always sticks to its initial setting

When the script is first executed, you declare getJambaseData as a variable. You assign the url value to

url:
  'http://api.jambase.com/events?zipCode='+userInputZip+'&api_key=[inserted my key here]'
. What were you expecting to happen?

It's like setting var x = 10; and expecting it to magically change when a function is called.

The solution is to move the entire initialization of var getJambaseData = {...} into the runAjax function, which should resolve the issue. Alternatively, you could omit the variable initialization part and directly include the content inside {...} (along with curly braces) within the $.ajax call instead of using a variable. If you refer to the jQuery documentation, you'll notice that this is the common syntax used in most examples.


Although not directly related to your query, I have some friendly advice to share:

  • Avoid using a variable before defining it (following a top-to-bottom approach), as it can prevent headaches down the line.
  • Another suggestion is to minimize the use of global variables. Instead, retrieve the userInputZip within the findShows function and pass it as an argument to runAjax. Over-reliance on global state in application development can lead to challenges sooner rather than later.

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

exploring numerous boxes in an engaging and educational tutorial

Explaining this in the title was a bit tricky, but what I want to create is an interactive tutorial. In this tutorial, the user will click on an area or product they want to clean or use for cleaning. After clicking, another box with relevant information w ...

Troubleshooting a Tiny Bottom Sheet Problem in react-native

On my page, I have a bottom sheet that takes up 3/4 of the space. Then, within that bottom sheet, I open another bottom sheet that only occupies 1/4 of the space (without closing the first one). ...

Improving the performance of a function that generates all possible combinations of elements within an array

After coming across this function online, I decided to optimize it. For instance, if we have an input of [1, 2, 3], the corresponding output would be [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] Below is the code snippet: const combinations = arr = ...

"Enhance Your Online Shopping Experience with Woocommerce Ajax Filters and

I have a structure that looks like this: Company Google Apple Microsoft Material Wood Metal Plastic Essentially, Brand & Material are attributes in the Woocommerce system, while the rest are variables. I am currently working on implementing AJAX fi ...

Encountering timeout issues with Next.JS fetch and Axios requests on Vercel production environment

I've been encountering an issue where I am unable to fetch a specific JSON data as it times out and fails to receive a response on Vercel deploy. The JSON data I'm trying to fetch is only 18KB in size and the fetch request works perfectly fine in ...

Sending HTML parameters to a PHP file

I have been trying to pass the parameters from the current HTML page to a PHP page using a form. In my header in the HTML, I currently have the following function: <script> function getURLParameter(name) { return decodeURIComponent((new Re ...

"Experience the power of Vue.js 3 and vue-router as the @click event seamlessly refreshes the entire

Just getting started with Vue and I'm trying to figure out how to toggle the menu open/close on mobile navigation without causing the whole page to reload. Any suggestions on how to prevent that? Here's my code: <router-link to="/ " @click="t ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

What is the best way to send an event handler to a sibling component?

I am facing a situation where I have an eventHandler that needs to be handled by its sibling component. The <Brains /> component contains several properties (such as this.randomNumber = 555 inside the constructor) that are required for the proper fun ...

Guide on how to retrieve the parent element's number when dragging starts

Within my div-containers, I have a collection of div-elements. I am looking to identify the parent number of the div-element that is currently being dragged For example, if Skyler White is being dragged, the expected output should be "0" as it is from the ...

Delete an entry from the localStorage

I am attempting to create a basic To-Do list using jQuery, but I have encountered an issue. This is my first time utilizing localStorage. After setting up the structure for my To-Do list, I wanted the items to remain visible when I refresh the page. Initia ...

Emphasize any word starting with an @ symbol to highlight its importance

My goal is to enhance the appearance of words that begin with an "@" symbol by making them bold. For example, transforming the sentence: '@xyzharris has a cat @zynPeter' into: '@xyzHarris has a cat @zynPeter' ...

Is there a way to prevent the conversion of .json/.webmanifest URLs into base64 strings?

I've been grappling with an issue for quite some time now. In my VSCode vite-react-typescript project, I have a link in the index.html file pointing to a webmanifest, which is essentially a json file with a different extension. After building my app, ...

Uploading files with Jquery and Ajax

I'm trying to use JQuery to post a file upload to the current page, then proceed with the file upload and insert it successfully. However, I'm encountering an issue where the code doesn't seem to work as intended. Specifically, JQuery is una ...

Desktop display issue: Fontawesome icon not appearing

Having trouble getting the fontawesome icon to display properly on my website. It appears in inspect mode, but not on the actual site itself. Any suggestions on how to fix this issue? import React, { Fragment, useState} from "react"; import { Na ...

Create an unordered Vue component object

In the data retrieved from the backend, there is an object containing various properties, one of which is the 'average' value. This object is ordered based on that value and when accessed through Postman, it appears as follows: ranking: ...

Attach a button and arrow to the cursor while it is hovering

Can anyone help me figure out how to make a button magnetize the content (arrow) along with it when hovered over by the cursor? I found an example of what I want on this website , but I am struggling to implement it in my own code. I've searched thro ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...

What is the correct way to set up Cypress intercepts within a beforeEach function?

As a newcomer to Cypress, I find some aspects of it challenging despite its apparent simplicity. I am facing a specific issue: const componentsRouteMatcher = { pathname: '/component-management/api/components', query: { size: &apos ...