Query string representation of a JSON object

Utilizing Maxmind.Com's GeoIP2 (Omni) Webservice, my Drupal 7 website can fetch geographic data using the visitor's IP address.

To obtain a JSON document, I use the following code:

<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.0/geoip2.js">
</script>

<script type="text/javascript">

var onSuccess = function(location){
    console.log(
        "Lookup successful:\n\n"
        + JSON.stringify(location.city.names.en, undefined, 4)
    );
};

var onError = function(error){
    alert(
        "Error:\n\n"
        + JSON.stringify(error, undefined, 4)
    );
};

geoip2.omni(onSuccess, onError);

</script>

Among the retrieved values is the name of the visitor's city. How can I incorporate this value into a query string?

For instance, if 'city.names.en' = 'Detroit', how could I use "Detroit" as a key to fetch relevant data (e.g., local phone number) from another source like a document or table?

The ultimate goal is to dynamically insert a "local" phone number in the "contact us" section based on the visitor's location.

Answer №1

Usually, a query string is structured in this manner:

http://exampledomain.com/path?parameterName=value

In the case of your scenario, it could resemble this:

http://exampledomain.com/employees/employeeID?department=Marketing

Answer №2

There are two different ways to accomplish your goal.

  • One option is to load the contact information after retrieving the city name using ajax. Here is a sample code snippet:
<span id="contact"></span>
<script type="text/javascript">
    $(document).ready(function() {
        geoip2.omni(function(data) {
            $.ajax({
                type: "GET",
                url: "your/url/to/contact/getter/service",
                data: {
                    city : data.city.names.en
                },
                success: function(contact) {
                    // update contact information
                    $("#contact").text(contact);
                }
            });
        }, function(data) {
            debugger;
        });
    });
</script>

You will need a resource where you can request the contact information based on the city name.

  • Another approach is to create a map of contact information and use it to easily retrieve contact details for a specific city without making another request.
<span id="contact"></span>
<script type="text/javascript">
    var contactMap = {
        NewYork : "123123",
        London : "9797987"
    }
    $(document).ready(function() {
        geoip2.omni(function(data) {
            // update contact information
            $("#contact").text(contactMap[data.city.names.en]);
        }, function(data) {
            debugger;
        });
    });
</script>

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

Getting a JavaScript response within an Angular promise can be achieved by utilizing the promise

When working with an Angular component, I encountered a situation where I needed to call a JavaScript function that performs an HTTP GET request and returns data. Although I included the JS file in "angular.json" and verified that it was working properly, ...

Database does not retain the updated image during the process

I am currently using Formidable along with the fa-extra module of Node.js to store files in MongoDB. It is functioning properly when I insert data, but I'm encountering difficulties when trying to update using Formidable. form.on('file', fu ...

When changing recipients in Firebase, the Javascript code fetches the same message multiple times even though there is only a single message stored in the database

In the process of developing a chat application using Firebase and JavaScript, I have come across an issue. Whenever I switch receivers multiple times, the message I send is fetched multiple times even though it is only sent once to the database. var selec ...

Searching for specific objects within a nested array in TypeScript

I have been searching for examples for a while now, but I haven't found anything similar. My understanding of the filter function is lacking, so any assistance would be greatly appreciated. The goal is to remove elements from the object where the nest ...

Guide to customizing the sort arrow colors of b-table in Bootstrap 4 within Nuxt framework

https://i.sstatic.net/axVNu.png Using nuxt and bootstrap, I've noticed that the default sorting arrows in the table are too dark for my background. Is there a way to change the color of these sorting arrows? <b-table show-empty small ...

Eliminate the commas in the JSON string except for the commas that separate arrays

I am facing an issue with stringified JSON data that includes commas in the description fields which causes the AJAX post to fail when there are apostrophes or commas present. How can I modify the output of var test = JSON.stringify(data)? The current ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

Learning to establish a connection between JavaScript and an SQL database

As I'm setting up a registration form for a website, I need to ensure that the username being entered by the user is not already in use. The code will check this against the database. ...

What tips do you have for creating a tool that requires automatic updates using ASP.NET MVC Razor, including Views, Controllers, Models, and Ajax?

Hello everyone! I need some advice from those familiar with asp.NET MVC and Ajax. Currently, I am in the process of creating a wishlist application and I want to enhance it by incorporating Ajax functionality to make it more interactive. My idea is that u ...

Converting a List to JSON Attributes using JsonConvert

I need to convert an object that has a list property into a JSON object. However, I don't want the list property to be directly parsed. Instead, I want the items in the list to be added to the JSON object as properties with custom names and index suff ...

Is it possible to prevent a line break in a div tag, or are there other options available?

On my ASP.NET 4 / VB website, I encountered a scenario where I needed to incorporate a class called "noprint" in my footer, as specified in the print.css file. However, there was already a span class present, so I ended up enclosing div tags around it. Mor ...

Is there a way to send an Ajax response to the web browser client as a downloadable file?

In my MVC 3 project, I have generated a csv file in an Action Method on the server named GetCSV() which is designated as an [HttpPost] action method. My goal is to send this csv file directly to the web browser for download. While I was able to achieve t ...

When working with VueJS and Vuex, using the splice method to replace an item (object) in an array stored in Vuex does not trigger a re-render of the

I have an array of records. Each record consists of an object with _id (mongo id), title, and value (value is an object with amount and currency). When displaying the list of records using v-for, the ':key' for each item in the list is set to th ...

AngularJS does not allow empty spaces in textarea inputs

I am working on a form that includes a textarea element for users to input descriptions, however it does not allow any empty spaces. Users can only input alphanumeric and numeric characters, but no spaces. <textarea class="form-control" rows="4" maxl ...

I am having difficulty toggling the show feature

I am currently facing an issue where I want the answer to be displayed when clicking on the question, but unfortunately, it's not working as expected. Can someone please assist me in resolving this problem? Here is my code: <html> <he ...

Send the content written in summernote to an AJAX request

I'm having trouble with ajax and javascript, so I need to ask for assistance. Within a form, I have an editor (using summernote editor). <div id="summernote">summernote text</div> After that, I use this ajax function to send the form dat ...

AutoCompleteExtender within ASP.NET MVC and ASP.NET AJAX Toolkit

I am looking to customize my ASP.NET AJAX AutoCompleteExtender in ASP.NET MVC to utilize a JsonResult instead of an ASMX Webservice. In my ASP.NET MVC View, I have set up an AutoCompleteExtender that calls a JsonResult function from my MVC Controller. He ...

Trigger Screen Reader to Announce When a Component Is Deleted

When the last filter item is removed, I want the screen reader to announce "All Filters Are Removed." However, if the active filter component is removed without any other element to assign an aria-label attribute, I'm not sure how to handle this situa ...

How to display currency input in Angular 2

Is there a way to dynamically format input as USD currency while typing? The input should have 2 decimal places and populate from right to left. For example, if I type 54.60 it should display as $0.05 -> $0.54 -> $5.46 -> $54.60. I found this PLUN ...

JSON schema built to stand the test of time

Can specific objects ("enemy" and "friend") be mandated while allowing other objects? In order to enforce the definition of the two objects ("enemy" and "friend") without interference from another object, I included the last object {"type": "object"} to d ...