Sending arguments to the json_callback function

I am utilizing a reverse geolocation technique using MapQuest that is structured as follows:

function fieldVia_changed(a)
            {
                if (document.getElementsByName("via"+a)[0].value.trim().length!=0)
                {
                   var via = document.getElementsByName("via"+a)[0].value ;
                   var strV = via.replace(/ |,/g, "+");
                   var s = document.createElement('script');     
                   s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q='+strV+'&json_callback=cbv&format=json&polygon=1&addressdetails=1';
                document.getElementsByTagName('head')[0].appendChild(s);
                }

            }

The data retrieved from the request is handled by the cbv function which takes in an argument.

 function cbv(json) 
            {
                v_lat[0] = json[0].lat;
                v_lng[0] = json[0].lon; 
             }

However, I require the ability to pass an additional parameter to the cbv function from the fieldVia_changed function in order to properly process the information. The definition of the cbv function would need to be adjusted to include another argument, such as function cbv(json,a). Despite my thorough search efforts, I have been unable to find a solution for this issue. Is it feasible to achieve?

Answer №1

When working with a JSONP system on the server side, passing additional arguments may not be an option. One way to address this is by utilizing the value of a in the callback function name and creating a dynamic function that acts as a mediator between the cbv() function, enabling the passing of a as a second argument.

function fieldVia_changed(a) {
    if (document.getElementsByName("via" + a)[0].value.trim().length != 0) {

        // dynamically create the function
        window['cbv_' + a] = function (json) {
            cbv(json, a);
        };

        var via = document.getElementsByName("via" + a)[0].value;
        var strV = via.replace(/ |,/g, "+");
        var s = document.createElement('script');
        // call the function cbv_x
        s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q=' + strV + '&json_callback=cbv_' + a + '&format=json&polygon=1&addressdetails=1';
        document.getElementsByTagName('head')[0].appendChild(s);
    }
}

function cbv(json, a) {
    v_lat[0] = json[0].lat;
    v_lng[0] = json[0].lon;
    console.log(a);
}

It's important to note that using a as part of the function name works well when it functions as a short identifier. However, if a originates from user input, it may not be ideal for use in the function name. Nevertheless, since you are using it in the name attributes, it should suffice for its intended purpose.

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 adjust the size of a button using CSS within a ReactJS

I am facing an issue where I need to create a button with a specific width, but the template I'm using already has predefined styles for buttons. When I try to customize the button's style, nothing seems to change. Below is the code snippet: Her ...

Managing media file transfers using multer and mongodb in a Node.js environment

As I work on developing a blog-style application for a business website, I have successfully implemented a login system and a basic blog structure. My current focus is on enabling users to upload images along with their blog posts. At the moment, I am trou ...

jQuery includes inArray as the final element in an array or object

There's a strange issue I've noticed where, in some cases, when jQuery is imported, it appends the inArray function as the last element of a defined object or array. This can cause problems with for ... in loops since it counts this unexpected fu ...

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

Searching for nested objects using dynamically generated property names

I am currently facing a challenge with accessing nested objects in MongoDb using the Node.js Driver, particularly when dealing with dynamic property names. Below is an example of my dilemma: //Although this code gives the desired results, it lacks dynamic ...

Unraveling the complexities of NodeJS: Exploring the concepts of nonblocking operations,

Exploring the concept of Node's non-blocking nature as a newcomer. I've put together a simplified diagram below illustrating how requests flow. From what I gather, all processes for a single user in an app operate on one thread. My curiosity ...

What is the best way to activate matching dates within the rangeselector data?

A datepicker has been integrated into a highchart in the following manner. $(function() { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) { // Create the chart $('#co ...

Tips for incorporating a last or recently visited feature similar to Google Docs using MongoDB

Within my database, I have two collections: users and projects. These collections share a many-to-many relationship. One user can be associated with multiple projects and one project can be assigned to multiple users. In the user object, I store an array o ...

Oops! npm start encountered an issue. The error message reads: "listen EADDRINUSE: address already in use :::5000

I seem to be facing a similar issue: MongoDB/React Error: listen EADDRINUSE: address already in use :::5000 Despite trying the command "npx kill-port 5000" and receiving the message "Process on port 5000 killed," I encounter the same error when running "n ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

Is it possible to create a central hub for all routes in a large AngularJS application?

Developing a large angularjs application with the intention of utilizing require.js for lazy-loading additional modules. The main question at hand is whether to create a comprehensive route.js file containing all the routes to other modules, or if each mod ...

Having trouble with removing the disabled attribute from an input file submit button

Currently, I am in the process of validating the file size and extension before it gets uploaded. My code is almost functioning perfectly, but there seems to be an issue with removing the disabled attribute from the submit button when the file meets all th ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

Adding a class to the following DIV and smoothly transitioning the current one out can be achieved using a dynamic number of items in multiple instances

Is there a way to create a scalable CSS slideshow for text divs without using images? Here is the current HTML structure: <div class="mb-panel-container cf"> <div class="mb-panel-section mb-slider"> <div class="mb-panel active" ...

Circe hit a snag while trying to transform the raw JSON into a case class. An error occurred because it couldn't locate the necessary lazy implicit value of type io.circe.generic.decoding.D

Concerning the creation of case classes for JSON representation, I have defined multiple nested case classes and am unsure if it was done correctly. The entities like spec, meta, etc., are all of type JSONObject, including the Custom object itself. Below ...

Retrieving a row from MySQL based on a specific value within a JSON string using regexp

I am storing permissions in the database using an Array JSON String, and I want to select them by a specific permission. Currently, I am selecting them using the following method: 1 | Dog | [3,4] 2 | Cat | [33,4] 3 | Tiger | [5,33,4] 4 | wolf ...

Deliver static assets integrated within Express using HTML template

I have a directory of text files that I'm currently serving through Express using express.static. Here's the code snippet: const express = require('express') const app = express() const port = 3000 var serveIndex = require('serve- ...

The ngIf statement in the template isn't functioning properly after a refresh; instead, it is causing a redirection to the homepage

I've been developing with Angular 7, trying to display a <div> ... </div> based on multiple values that I declared as : Boolean = false; in the .ts file. These values are updated in ngOnInit, but for some reason, the page keeps redirecting ...

Categorize list-items into subgroups according to a specific data attribute

I am looking to transfer the <li> elements from one dynamically created <ul> to another. The goal is to categorize the list-items into new sub-lists based on their data-group attribute. <ul id="sortable1"> <li data-group="A">te ...

Toggle between hiding and showing div elements issue

Currently in the final stages of developing an iPhone web app, I have encountered a small issue that needs to be resolved. I have successfully hidden one layer and displayed another with a button click. However, what I am aiming for is to toggle between s ...