What is the best way to transfer a JSON response from VB to JS?

How can I transfer a JSON response from VB to JS?

I'm currently working on updating a company website that processes payments through JSON request/response communication. The site is built in VB, and while I've been able to successfully send the JSON request and receive a response, my challenge lies in passing this response from VB to JS so that the bank's external JS file can inject their payment page into a DIV tag on my page.

I am relatively new to this and have attempted various methods without success. The closest I have come is by transferring the JSON response to a hidden input field and using a JS script to retrieve the value with document.getElementById. However, the hidden input field only captures the opening { character.

The structure of the JSON response is as follows:

{"response" : {"success":"true","ticket":"random ticket number from bank"}}

Below is the current code snippet, apologies for its messiness.

Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Dim reqString() As Byte

Try
    webClient.Headers("content-type") = "application/json"
    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dictData, Formatting.Indented))
    resByte = webClient.UploadData(Me.urlToPost, "post", reqString)
    resString = Encoding.Default.GetString(resByte)
    Dim sb As New System.Text.StringBuilder()
    sb.Append(resString)
    Dim JSONData As String = sb.ToString()
    Dim p As Page = TryCast(HttpContext.Current.Handler, Page)
    p.ClientScript.RegisterStartupScript(Me.GetType, "alert", JSONData)

    System.Web.HttpContext.Current.Response.Write(String.Format("<input id=""jsonResponse"" value=""{0}"">", resString))

    Dim jScript As String = "<script>var myCheckout = new bankCheckout();myCheckout.setMode('qa');myCheckout.setCheckoutDiv('bankCheckout');var form1Display = document.getElementById('form1');function showCheckout(){form1Display.style.visibility = 'hidden';bankCheckoutDisplay.style.visibility = 'visible';}var bankCheckoutDisplay = document.getElementById('bankCheckout');let result = document.querySelector('.result');var json = document.getElementById('jsonResponse');var obj = JSON.parse(json);alert(obj.response.ticket);myCheckout.startCheckout(obj.response.ticket);showCheckout();</script>"


    p.ClientScript.RegisterStartupScript(Me.GetType, "Script", jScript, False)

    webClient.Dispose()
    Return True            
            
End Try      

Answer №1

If you require further information, feel free to visit: https://github.com/beatum/demo-Json-manipulation-vbs

    'transform into JSON object
    Set JsonObject = ConvertToJSONObject(JsonData)
    'Members of the object
    Set Members = JsonObject.Members
    'calculate array length
    lenOfArray = GetByProperty(Members, "length")
    'iterate through the array
    For i = 0 To CInt(lenOfArray) - 1
       Set mem = GetByIndex(Members, i)
       Debug.Print "Name:" & mem.Name
       Debug.Print "Age: " & mem.Age
       Debug.Print "SecretIdentity: " & mem.SecretIdentity
       Set Powers = mem.Powers
       lenOfPowers = GetByProperty(Powers, "length")
       Debug.Print "################Powers#################"
       For j = 0 To CInt(lenOfPowers) - 1
          Power = GetByProperty(Powers, j)
          Debug.Print Power
       Next
    Next
   Debug.Print "......Complete......";

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

Logging in asynchronously in an ASP.net MVC application with user roles

Working perfectly on my desktop, this code is giving me a headache on my laptop. It keeps throwing an error stating that "SignInAsync" does not exist in the current context. [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async ...

Creating numerous duplicates of a highly nested immutable Object can be done by using a combination of spread operators

I am currently working on retrieving data from firebase/firestore using Javascript. I have created a function where I retrieve my products collection and pass this data to the React state.products by utilizing the setState() method. My objective is to tra ...

Transform your CSV data into JSON using Node.js and store it within a variable for easy access

Currently, I have this code snippet as a starting point and my task is to utilize it in order to convert the content of "world_data.csv" into JSON format. I am unsure of how to store this JSON data in a variable. I suspect that the desired data is tempora ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

SailsJS fails to transpile Bootstrap.js in a timely manner

In my backend development with Sails JS, I am utilizing ES6/7 and have created a class to handle background tasks. After reading a post on StackOverflow (link), it was recommended to initiate background tasks in config/bootstrap.js. Following this advice, ...

What is the process for updating a document with two specific filter conditions?

I have a structure in my document that appears as follows: type Document = { _id: string title: string variants: VariantType[] } type VariantType = { timestamp: Int active: Boolean content: any[] } I am attempting to filter a document using ...

Focus on an empty <input> tag with just the type attribute

In what way can React Testing Library be utilized to isolate a blank <input> element that solely possesses a type attribute? For instance, consider an input field that will eventually have attributes added dynamically, much like the surrounding labe ...

Laravel - Error in Symfony\Component\HttpFoundation\JsonResponse Argument 2

How can I retrieve the data in $users as an array and the data in $this->guard()->user() separately without it being inside an array? I attempted the following, but encountered an error - Argument 2 passed to Symfony\\Component\\H ...

Ways to inform an observer of an Object's change?

Is there a way to ensure that an observer receives notification of a change, regardless of Ember's assessment of property changes? While the ember observer pattern typically works well for me, I've encountered a specific issue where I'm unc ...

Javascript - combining selections from several forms to produce a final outcome

Hello everyone, I am a newcomer to this community and also to the world of programming. Despite my limited experience with coding, I have been eager to enhance my workplace by creating a basic form for my colleagues. In summary, I have successfully create ...

Updating the value of a specific property within an object in an array

I'm in the process of developing a stock trading application, and I have an empty array to store the stocks that are bought. Each time a stock is purchased, it adds an object to the array. If the same stock is bought again, I want to check for that sp ...

Learn how to bypass the problem of self-signed certificates in request-promise

In my node application, I am utilizing the request-promise module to make API calls. You can find more information about it here. import request from 'request-promise'; let options = { method: GET, json: true, ...

Ways to display and conceal a div when hovering over another div

Currently, I have 4 divs grouped under the class "menubut." I am attempting to create a small overlay that appears when hovering over the menubut classes. Additionally, I want another div called "red" to show up about one-tenth of the size of the menubut ...

JavaScript makes Chrome Hard Reload a breeze

We've created a browser-based app using AngularJS and are currently testing it with a group of clients. One major challenge we're facing is explaining how to "Empty Cache and Hard Reload" using the Chrome browser (by pressing F12, then clicking o ...

"Troubleshooting: Android - getSharedPreferences method not Resolving

Hello, I am facing an issue with getSharedPreferences not resolving. I have searched for solutions extensively but nothing seems to fix it. How can I implement getSharedPreferences in onclick inside ViewHolder? Here is the code snippet from MyHolder.class ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

Having trouble assigning a default value to an array in the useState declaration

When attempting to set a default value for my state, I encountered an issue where it was returning undefined. However, upon refreshing the page, the values were correctly assigned to categoryIds. const si = [...searchParams.getAll("cat")]; c ...

Algorithm for File Naming

Given an array of desired file names in the order of their creation, where two files cannot have the same name. If a file has a duplicate name, it will be appended with (k), where k is the smallest positive integer that creates a unique name. Output an ar ...

Choosing a single random key-value pair from a specific attribute within a JSON schema

Is there a way to generate a new JSON schema based on the existing one, but with only one key-value pair chosen randomly from the "properties" attribute? The new schema should retain the "title" and "type" attributes as well. { "title": "animals object" ...

Issue - Basic Data Protection and Unscrambling - Node.js

I have been working on some basic code to encrypt and decrypt text, but I keep encountering an error when using the .final() function of createDecipherIV. I have tried experimenting with different encodings like Binary, Hex, and base64. Node Version: &apo ...