Retrieve a JSON object by making a request to a URL with specific parameters

Struggling with a common coder's mental block:

The idea:

Imagine entering a URL like www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345

Rather than receiving a webpage, the goal is to get back a json object for parsing on another page.

The challenge:

Although achievable through calling an MVC controller with parameters and returning a json object, what if the task involves creating that json object within a js file using URL parameters?

The questions:

Can JavaScript files receive parameters and return json objects? Or can a controller call a JavaScript file with parameters, then retrieve a json object? Is it necessary to call a controller through a URL, or could a javascript file be called with URL parameters to generate and return the json?

How should this scenario be handled effectively using MVC, JavaScript, jQuery... any advice?

Appreciate your insights!

Answer №1

There are a few different routes you can take

1) Generating the JSON using JavaScript

In order to do this, you will need to set up a basic webpage that includes a JavaScript JSON encoder (like https://github.com/douglascrockford/JSON-js). This page would be hosted at "/getStuff/index.html" and accessed by typing "www.mysite.com/getStuff/?arg=val..." For instance:

<html>
    <head>
        <script src="json.js" type="text/javascript"></script>
        <script type="text/javascript">
                    //this function will parse the window.location.search string of ?name=val and
                    //create an object like {'name':'val'}
            var parseUrl = function(urlParams) {
                var retObj = {};
                var urlParameters = null;

                if (!urlParams || urlParams.length == 0) {return retObj}
                if (urlParams.charAt(0) == '?') {
                    urlParameters = urlParams.substring(1);
                }else {
                    urlParameters = urlParams;
                }
                if (urlParameters.length == 0) {return retObj}
                var parameterPairs = urlParameters.split('&');
                var x;
                for (x in parameterPairs) {
                    var parameterPair = parameterPairs[x];
                    parameterPair = parameterPair.split('=');
                    retObj[parameterPair[0]] = parameterPair[1];
                }
                return retObj;
            };
            var createJson = function(){
                var params = parseUrl(window.location.search);
                //do work here
                var retObj = {}; //assume this is the result of the work
                document.print(JSON.stringify(retObj)); //use the included JSON encoder
            };
        </script>
    </head>
    <body onload="createJson();">
    </body>
</html>

2) Utilize an MVC framework

Any MVC framework available will provide access to the search parameters used in the page request. Some may require them to be provided in /function/arg1/arg2 format (such as /getStuff/jerry/engineer/12345, in your case). Others use a more traditional /function/?argName=argVal... approach. Once you have the arguments, it's easy to output them on the page in JSON format (http://php.net/manual/en/book.json.php).

Decision Time

Personally, I would opt for the MVC method since it involves less hassle in obtaining the desired JSON. However, if you're not familiar with an MVC framework (like cake), getting started may be a bit challenging - these frameworks are primarily designed for delivering page content, and configuring them to serve JSON isn't always straightforward.

Answer №2

To extract URL parameters using jQuery, you can add the following code inside a <script> tag before creating the JSON object. The code snippet can be found in this helpful tutorial by LekisS.

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

// Retrieve URL parameters as an object
var allVars = $.getUrlVars();

// Get URL parameter by name
var byName = $.getUrlVar('name');

In a separate script tag, you should create your JSON object after including the Json2.js plugin for converting objects to JSON format.

With the necessary scripts and variables in place, you can construct a JSON object by referencing the parameters with jQuery. Remember to determine whether you need to convert the JSON data to a string or an object based on the Json2.js functionality.

Now that everything is set up within various scripts, how do you access the JSON object through a URL call?

The solution is straightforward:

Simply create an HTML page containing these scripts, where the final script generates and returns the JSON object. Upload this page to your server and utilize URL parameters like

www.mysite.com/getStuff?para1=value&para2=value2
to retrieve the JSON object.

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

Learning to parse a JSON file in Java

I need assistance with reading a Json file. The content of my Json File is as follows: [ { "arguments" : [ { "IsEnabled" : "false", "class" : "UITextField", "width" : 238, "parent" : { "class" : "UIVie ...

Having trouble showing the material-ui icon on my navigation menu

How can I use Material-UI icons like <AddOutlinedIcon /> in my nav menu without displaying the actual code before the menu name? Do I need to escape the icon code somehow to make it appear correctly? The intended result is to have a + icon displaye ...

Struggling to get the ReactJS.NET MVC tutorial to function properly?

After deciding to start a new project in Visual Studio with MVC 5 and a single page app using ReactJS, I consulted the guide on the ReactJS website. Upon running the project for the first time, I encountered a syntax error due to JSX. It seemed that the b ...

The functionality of .getJSON() in JSON/JQuery is not compatible with IE8 or IE9 browsers

It seems that this particular code is not functioning properly in IE8/IE9, and I am uncertain whether it is caused by the JSON or JQuery .getJSON() element. The main objective of this code is to retrieve data from foursquare and present it on a webpage. I ...

Dealing with JWT management in the absence of Cookies

After doing some research on JSON Web Token (which is a new concept to me), I have learned about its secure mechanism for transmitting information between parties without the need for server Sessions. Currently, I am in the process of building a web app f ...

How can you nest a map within a map in JavaScript?

Here is the code snippet I am working with: _renderChannels() { return this.state.channelsData.map(channelData => { return this.state.channelsStreamData.map(channelStreamData => { return <Channel channelData={channelData} ch ...

Implementing AngularJS to display different divs according to the selected value

I am attempting to utilize the value of an HTML select element to toggle the visibility of specific div tags using AngularJS. Below is the code snippet I have been working with: <body ng-app="kiosk" id="ng-app" > <div class="page" ng-controll ...

Animate images using mouse vertical movement

Creating websites is just a hobby for me, not something professional. Recently, I came across a beautifully designed website that had some unique features I hadn't seen before, like placing three images in one div (which I researched and learned how t ...

Struggling to deal with conditionals in Express

Just starting with Express and I've come across the following code: const { response } = require("express"); const express = require("express"); const app = express(); app.get("/api/products/:id", function (req, res) { ...

Python can be used to add or update an item in a list within a MongoDB

As a beginner with mongo, I am attempting to append another number to the list of stgids within this document: { "hash" : "45ewqd34dewrqfer24ferferf24frec", "date_found" : "2020-03-17 14:34:52", " ...

Is it possible to compare every element in an array with one another using an asynchronous process in NodeJS?

I am currently utilizing Resemble.js for image comparison within my web application. I have an array of image URLs that I need to compare with each other in order to calculate a unique score for each image. For example: [url1, url2, url3, url4] The minimu ...

Master the art of utilizing angular-filter

Encountering some challenges while attempting to utilize angular-filter: The following links have been imported into the HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src=" ...

Having trouble replicating bugs with jqUploader and contemplating a switch to Uploadify. Would love to hear any suggestions or opinions on this

Recently, I've been facing some issues with jqUploader. It seems to fail on certain browsers and machines, as well as not functioning properly with HTTP Basic authentication. After numerous attempts to fix these problems, I am considering switching to ...

In Internet Explorer 11, React 15.4.1 does not support using objects as valid child components

When trying to render a collection of children in React, make sure to use an array instead of objects. If you encounter the error "Objects are not valid as a React child," consider wrapping the object using createFragment(object) from the React add-ons. Do ...

Uploading large files on Vuejs causes the browser to crash

Whenever I try to upload a file using my browser (Chrome), everything goes smoothly for files with a size of 30mb. However, if I attempt to upload a file that is 150mb in size, the browser crashes. The server's maximum upload size has been configured ...

Implementing a versatile free text filter with numerous values using MUI

I am currently working on incorporating a free text filter view using MUI. Although the Autocomplete component already has this feature (when the 'multiple' attribute is enabled), I am looking to input free-form text instead of selecting from pre ...

There is no POST data present in the jquery ajax request

I have been attempting to send data back to a controller using ajax from a lightbox, but unfortunately, it is not working as expected. The issue arises when I select values from two populated select lists and click submit – an error message briefly appe ...

User must wait for 10 seconds before closing a JavaScript alert

Can a JavaScript alert be set to stay open for a certain amount of time, preventing the user from closing it immediately? I would like to trigger an alert that remains on screen for a set number of seconds before the user can dismiss it. ...

Is there a way to transfer an array of strings and integers from JavaScript to Python 3.8?

I have reviewed similar questions but haven't found a solution that works for me. My inquiry is regarding the following code snippet: function pyInput(){ const buffers = []; proc.stdout.on('data', (chunk) => buffers.push(chunk)) ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...