javascript converting a string into a variable

I have a JSON string coming from an ajax call and I want to assign a value to a predefined variable:

var predefined = "hello world";
var foo = {"msg":"predefined"}; // The JSON string

I need to display the standard text by accessing it like this:

alert(foo.msg)

UPDATE: To clarify, here is my AJAX request:

var success_msg = "Your email has been sent successfully!";

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status == "success") {
            msg.text(data.msg).addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
})

The response from ajax-share-email.php is:

{"status":"success", "msg":"success_msg"}

Answer №1

let greetings = {"default":"hello there"};
alert(greetings[foo.message]);

for instance

let notifications = {};
notifications.info_message = "You have a new notification!";

// ...
            message.display(notifications[data.message]).style("color", "green");
             

Answer №2

Here's an idea - display the message inline for success and skip adding it to the JSON object. For errors, include the full message in the response. Your server could return something like this:

{ "status": true }

or

{ "status": false, "msg": "The server encountered an issue." }

This way, you can simply check the boolean value without comparing it as a string.

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status) {
            msg.text('Email sent successfully!').addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
});

In case you find yourself reusing messages across multiple functions, consider restructuring to use a message dictionary. Keep your messages object accessible globally or within the scope of all related functions.

 var messages = {};
 messages.mail_success = 'Your email has been sent successfully!';
 messages.post_success = 'Data updated successfully!';

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status) {
            msg.text(messages.mail_success).addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
});

Answer №3

let greeting = "hi there";
let bar = {"message": greeting}; // JSON object
console.log(bar.message)

What will be printed to the console?

Answer №4

Based on my understanding of your question, I believe all the necessary components are available.

You have a variable called predefined that you want to include in your JSON data and then retrieve its value from the parsed object.

In this scenario, using JSON.parse may not yield the desired outcome in Chrome; however, employing eval should do the trick.

var predefined = "Hello! I am predefined";
// ...

var json = '{"foo": predefined}'; // note the lack of quotation marks
var response = eval("(" + json + ")");
alert(response.foo);

Answer №5

let result = eval(bar.content); // result will be set to "greetings earth"

Please exercise caution when using eval() with unknown content in the variable bar.content.

Alternatively, you can use:

let result = bar.content === "defined" ? definedValue : bar.content;

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

Unable to locate element using document.getElementById in ASP.NET form

Currently, I am working on a project to create an ASP.NET webforms page that will showcase a Google map using the Google Maps JavaScript API with multiple markers. Everything is functioning smoothly as long as I don't place <div id="map-canvas"> ...

The function $(window).hashchange() is not functioning properly

Hey there, I've been exploring how to make use of the browser back button feature, and I've figured out how to capture the event using the hashchange plugin: $(window).hashchange( function(){ alert( location.hash ); });$(window).hashchange( ...

Unable to make changes to the text within the textarea field

Currently, I am in the process of creating a script to streamline the tedious task of providing teaching feedback. To scrape data such as student names and classes, I am utilizing selenium/python. While everything is running smoothly, I have encountered an ...

Simulated FileList for Angular 5 App Unit Testing

Imitation FileList In my pursuit of writing a unit test (Angular5), I have encountered the need for a FileList. Despite researching extensively, I have been unable to uncover any clues or solutions. I am starting to question whether this is even feasible ...

Locate every identifier within the JSON data

I'm currently working with a lengthy JSON tree document, and here is an excerpt: "childs": [ { "id": "id1", "name": "name1", "childs": [] }, { "id&quo ...

What is the best way to extract key/value pairs from an object in javascript that have a specific suffix?

I'm dealing with an object: { a_suff:"Something", b_suff: "Value", c: "Value", d: "Value, e_suff: "Value" } I'm looking for a way to extract all the keys that end in "_suff". What would be the most efficient solution? Currently, I have this im ...

Troubles encountered while generating a title for a tooltip using d3-tip

After successfully creating a chart in a tooltip following the example provided here: https://bl.ocks.org/maelafifi/ee7fecf90bb5060d5f9a7551271f4397, I've encountered an issue with adding a title to it. var tool_tip = d3.tip() .attr("clas ...

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

Can you explain why there is a difference in the output between these two pictures?

This program takes in 5 strings and prints them. Here is the program: #include"stdio.h" #include"conio.h" void main(){ clrscr(); char s[5]; for(int i=0;i<5;i++){ scanf("%s", s[i]); } for(i=0;i<5;i++){ printf("&bso ...

Smoothness issue with fading in Ajax-loaded div using jQuery

When I run the code locally, the fade-in effect is very smooth. However, when it's deployed on a remote server, the content loaded into the target div initially appears, then disappears instantly before fading back in again. What could be causing thi ...

display and conceal elements according to the slider's current value

Currently, I am working on creating a slider that can show and hide elements as the slider bar moves (ui.value). Firstly, I used jQuery to create 30 checkboxes dynamically: var start = 1; $(new Array(30)).each(function () { $('#showChck') ...

Error: Attempting to access the 'client' property of an undefined object

I'm currently working on a basic discord.js bot. Below is the code snippet that generates an embed: const Discord = require('discord.js') require('dotenv/config') const bot = new Discord.Client(); const token = process.env.TOKEN ...

Creating a customized navigation bar with a unique menu list underline feature using JavaScript

I recently created a customized navbar using a script to add a hover effect to the menu links. You can find the script I used here: https://github.com/shadeed/underliner. Although I was able to get it partially working, there are still some issues. The we ...

What is the best way to input individual students' CA and exam scores into distinct fields and then calculate their total scores in a separate text field?

As a beginner in jQuery, I am looking for guidance on creating a script that calculates the Total score, Grade, Remark, and Position based on the user input of CAT score and EXAM score. The result should be displayed dynamically once both scores are entere ...

Rotating an object around the camera coordinate using three.js: A step-by-step guide

var newObj = new THREE.CSS3DObject(el); newObj.matrix=camera.matrix.clone(); newObj.matrix.setPosition(new THREE.Vector3(tarX,tarY,tarZ)); //newObj.applyMatrix(new THREE.Matrix4().makeRotationY(rotY)); //newObj.applyMatrix(new THREE.Matrix4().makeRotati ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Is there a more concise method in Vue to transmit data from the script section to the template section aside from utilizing a function?

My current code structure is as follows: <template> ..somecode {{showEditFlag}} </template> <script> export default{ data: function() { return { showEditFlag }; } } </script> Could it be simplified to something like this in ...

Replacing text within nested elements

I am facing an issue with replacing certain elements on my webpage. The element in question looks like this: <div id="product-123"> <h3>${Title}</h3> <div> ${Description} </div> <div> ${P ...

Direct all paths to the base path "/" using Express

Is there a way to redirect all URLs containing "/something" in Express to the base path "/:=", while still maintaining additional paths to their respective pages? For instance, I would like to implement the following redirects: "/something" redirects to ...

Retrieving information from an Angular service using a specified function

I have been working on accessing data from a method within a service that returns coordinates, which are used to make HTTP requests in my application. I have integrated my Leaflet code into the controller to be able to access the lat,lng coordinates for ...