Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it.


function address(adres) {

this.address_string = adres;
var self = this;
$.ajax({
    type: 'POST',
    url: "http://nominatim.openstreetmap.org/search?q="+adres+"&format=json&polygon=0&addressdetails=0",
    success: function(data) {
        self.responseArray = eval('(' + data + ')');
    }
});

//Method returning point coordinates in EPSG:4326 system
this.getLonLat = function() {
    var lonlat = new OpenLayers.LonLat(this.responseArray.lon, this.responseArray.lat);
    return lonlat;
}
}

The issue arises when writing the following in the application code:


var adr = new address('Zimna 3, Warszawa');
adr.getLonLat();

This does not return anything as there is no time to receive the response from the server. How can this be resolved properly for optimal performance? I have come across the when().then() method in jQuery, which seems promising. I am eager to learn about best practices.

Answer №1

Understanding AJAX involves grasping the asynchronous aspect of it. Indeed, when you trigger adr.getLonLat(), the response has not arrived yet. A recommended approach would be to pass a reference to a callback function in the adres constructor:

function adres(adres, callbackFun) {
  //...
  success: function(data) {
    var responseArray = eval('(' + data + ')')
    var lonlat = new OpenLayers.LonLat(responseArray[i].lon, responseArray[i].lat);
    callbackFun(lonlat)
}

You can then utilize it like this:

adres('Zimna 3, Warszawa', function(lonlat) {
  //...
})

A few important points to consider:

  • The revised adres essentially functions as a regular function; an object is unnecessary.

  • Avoid using eval for JSON parsing; instead, rely on the JSON object.

  • Ensure that you can make a POST request to

    http://nominatim.openstreetmap.org
    without encountering same-origin policy issues.

  • Where is the i variable sourced from in responseArray[i]?

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

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

hiding elements yet passing down

Despite disabling the style sheet, a dynamically created form is displaying strangely. This form will show or hide various details based on selected options. For instance, many of the elements are generated with C#.net... formOutput += "<div class=&bs ...

Issue with React: Children's state is altering the state of the parent component

Question : Why is it possible for a child component to change the state of its parent when each component has its own state? Below is the complete code for my app: import React, { Component } from 'react'; import { render } from 'react-do ...

Google App Engine does not properly interpret PHP code when making AJAX requests

I am currently facing an issue with using AJAX request on Google App Engine. In my local development environment, everything works fine and the request is correctly interpreted. However, when I deploy the code to production, the AJAX request renders the co ...

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...

Incorrect format for a date in AngularJS

I have a time input field where I am receiving the date and time format 'Thu Jan 01 1970 12:59:00 GMT+0530 (India Standard Time)', but I only want to display the time. Is there an issue with the time picker in AngularJS? Can anyone help me resolv ...

Steps for dynamically loading the correct pane without having to refresh the header, footer, or left navigation

Looking to create a web application using HTML, Bootstrap, and jQuery that includes a header, footer, left navigation, and right pane. The content of the right pane will be loaded from a separate HTML page based on what is clicked in the left navigation. ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

What is the best way to include a new class into the current class in this particular scenario?

Just starting out with Javascript and Jquery, so please bear with me if this question seems basic I'm dynamically constructing HTML like this: var favoriteresultag = '<ul>'; favoriteresultag += "<section id='"+name+"' ...

Comparing prevProps and this.props in React Native Redux: What is the most effective method?

Does anyone know how to efficiently handle triggering a function in my React Native app only when a specific prop has changed? This is the current implementation I have: componentDidUpdate(prevProps) { if (prevProps.a !== this.props.a) { <trigger ...

Updating the progress state of MUI linear determinate diligently

I currently have a modal set up that handles some asynchronous logic for submitting data to a database. The component I am using, called LinearDeterminate, is designed using Material-UI. You can find more information about it here: MUI Progress import { u ...

Understanding JavaScript's JSON Path Variables

I've scoured the internet for solutions to a similar issue but haven't been able to find any helpful information yet. My current challenge involves accessing a picture path (in JSON format) based on the material type of the selected element. Her ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

The $_POST variable is not filled with the information displayed in the payload

When submitting a form with AJAX, I am able to view the payload data using the developer tools in Chrome: ------WebKitFormBoundaryiwCAdpY9aJH3D9h9 Content-Disposition: form-data; name="datafixId" 666 ------WebKitFormBoundaryiwCAdpY9aJH3D9h9 Content-Dispo ...

Tips for optimizing Firestore database requests on the web to minimize the number of API calls

On my product page, every time a user presses F5, the entire list of products gets loaded again. I am looking for a way to save this data locally so that it only needs to be updated once when a new product is added, instead of making multiple API calls. ...

Choosing the perfect interface between JQuery Mobile and a Java backend for a mobile web application

Currently, we are in the process of developing a mobile web app to replace an older Java web app - specifically, just the database from that app. We have chosen not to migrate the original app completely due to its outdated custom ORM solution and Struts ...

Efficiently uploading multiple files using AJAX in conjunction with Codeigniter

Greetings! I'm attempting to utilize ajax and codeigniter to upload multiple images. As a beginner in ajax and jquery, I would greatly appreciate any assistance in identifying where I might be going wrong or missing something. Below is my controller ...

Output text in Javascript (not to the console)

I'm on the lookout for a way to welcome a user by their name when they enter it into a JavaScript application. I have tried this code snippet: function getname() { var number = document.getElementById("fname").value; alert("Hello, " + fnam ...

react validation for dropdown, react-datepicker, and hour input at intermittent intervals

I have integrated the following packages into my project :- react-datepicker library for selecting from time and to time date validation with date-fns, moment.js, additional validations using jQuery and lodash libraries/packages If you want to view my pr ...