Leveraging JavaScript variables conditionally within a JSON object

Within the code snippet below, there is a condition written as

(if (epsflag==0)<?php $a=",hide:'true'";?> )
. I am looking to achieve the same condition using JavaScript. Essentially, I want to conditionally utilize a JavaScript variable in my JSON structure. Any assistance with this matter would be greatly appreciated. If my question is unclear, please do not hesitate to let me know.

{display: 'Wave Name', name : 'wavename', sortable : true, align: 'left'<?php echo "$a"?>}

<script type="text/javascript>
function rowdata(epsflag,respflag){
    if (epsflag==0) {
        <?php $a=",hide:'true'";?>
    } else {
        <?php $a=",hide:'false'";?> 
    }

$("#flex1").flexigrid({
    url: myurl, 
    dataType: 'json',
    colModel : [
        {display: 'Nr.', name : 'nr',  sortable : true, align: 'center',width:25},
        {display: 'Datum', name : 'consultationdate',  sortable : true, align: 'left'},
        {display: 'Wave Name', name : 'wavename',  sortable : true, align: 'left'<?php echo "$a"?>},
        {display: 'Name', name : 'respname',  sortable : true, align: 'left'},
        {display: 'E-mail', name : 'email',  sortable : true, align: 'left',width:180},
        {display: 'Telefoon', name : 'telefoon',  sortable : true, align: 'left'},
        {display: 'Medewerker', name : 'consultationwith',  sortable : true, align: 'left'}
    ],  
});

}

Answer №1

It appears there may be a misunderstanding regarding the functionality of web technologies.

PHP is essentially a language dedicated to processing strings. Its primary function is string manipulation and generation. In this context, JavaScript can be seen as a large string when interacting with PHP. To simplify this concept, let's replace the JavaScript code with a basic test string like "bla bla bla..":

bla bla bla bla bla bla
<?php $a=",hide:'true'";?>
bla bla bla bla bla bla
<?php $a=",hide:'false'";?>
bla bla bla bla bla bla
<?php echo "$a"?>
bla bla bla bla bla bla

If we streamline this further:

<?php
    $a=",hide:'true'";
    $a=",hide:'false'";
    echo "$a";
?>

Executing this in PHP results in outputting the string:

bla bla bla bla bla bla    // note: no actual output here
bla bla bla bla bla bla
,hide:'false'
bla bla bla bla bla bla

By replacing the "bla bla" with a simplified version of your original content, the output transforms into:

<script type="text/javascript">
function rowdata(epsflag,respflag){
    if (epsflag==0) {
                    // note: missing output from PHP
    }
    else {
                    // note: missing output from PHP
    }

    $("#flex1").flexigrid({
      colModel : [
        {align:'left',hide:'false'}  // logically, always false
      ]
    });
}

At this point, understanding that PHP does not process JavaScript and remains invisible to the browser leads us back to the fundamental distinction between client-side and server-side programming, exemplified elsewhere (source).

Now equipped with a clearer grasp of web mechanisms, how do we address your issue?

Considering your particular case, it seems unnecessary to transmit data back to PHP. Instead, you aim to modify a value within a JavaScript object. Why complicate matters by involving PHP when JavaScript can directly handle these changes? Here's an adjustment solely in JavaScript:

var wavedata = {
    display: 'Wave Name',
    name : 'wavename',
    sortable : true
};

if (epsflag==0) {
    wavedata.hide = 'true';
}
else {
    wavedata.hide = 'false';
}  


$("#flex1").flexigrid({
    colModel : [
        // other data
        wavedata,
        // other data
    ]
});

Alternatively, for maintaining similarity to your existing structure while setting 'true' or 'false' as strings, consider Grundy's suggestion rewritten slightly:

{/* ... */ align: 'left',hide: epsflag==0 ? 'true' : 'false'}

Answer №2

Perhaps this could be useful:

function rowData(epsFlag, respFlag){

    $("#flex1").flexigrid(
    {

    url: myURL, 
    dataType: 'json',
    colModel : [
        {display: 'Nr.', name : 'nr',  sortable : true, align: 'center', width:25},
        {display: 'Datum', name : 'consultationdate',  sortable : true, align: 'left'},
        {display: 'Wave Name', name : 'wavename',  sortable : true, align: 'left', hide: (epsFlag==0)},
...

UPDATE

If you prefer not to use a variable inside the object, you can try something like this:

function rowData(epsFlag, respFlag){

    var colModel = {};
    if(epsFlag == 0){
        colModel = [
            {display: 'Nr.', name : 'nr',  sortable : true, align: 'center', width:25},
            {display: 'Datum', name : 'consultationdate',  sortable : true, align: 'left'},
            {display: 'Wave Name', name : 'wavename',  sortable : true, align: 'left', hide: true }
            ...
    }else{
        colModel = [
            {display: 'Nr.', name : 'nr',  sortable : true, align: 'center', width:25},
            {display: 'Datum', name : 'consultationdate',  sortable : true, align: 'left'},
            {display: 'Wave Name', name : 'wavename',  sortable : true, align: 'left', hide: false }
            ...
    }

    $("#flex1").flexigrid(
    {

    url: myURL, 
    dataType: 'json',
    colModel : colModel,
    ...

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

Are there any possible resolutions to the issues plaguing Next.Js?

After switching from React to Next.JS, I've encountered some challenges that I'm hoping to find solutions for: In contrast to React, Next.JS doesn't allow me to change a specific part of a webpage and maintain a static element like a navb ...

Discover the method for measuring the size of a dynamically generated list

I'm currently working on a chat box that displays messages as a list. One issue I'm facing is that when I click on the start chat button, the chat box opens but the length of the list always remains zero. How can I resolve this problem? $(docu ...

Convert HTML Tables to PDF Format

I am facing an issue with exporting my table data into a PDF using jQuery. I have made sure to install all the necessary library files, but my code doesn't seem to be working correctly. Can anyone spot any errors in my code or suggest what might be mi ...

Establish a connection with the hivemq broker using MQTT protocol

Within my app.js file: const mqtt = require('mqtt') const client = mqtt.connect('mqtt://localhost:1883') topic = 'testTopic' client.on('connect', ()=> { client.subscribe(topic) }) client.on(&a ...

Do we need to handle promise resolution after sending a response to the client?

After sending the response to the client, I have a requirement to execute an asynchronous function. res.json({}); someAsyncFunction(); //this function does not require await Is it considered problematic to call this function without awaiting its promise? ...

What could be the reason for the failure of .simulate("mouseover") in a Jest / Enzyme test?

I have a scenario where a material-ui ListItem triggers the display of a material-ui Popper containing another ListItem on mouse over using the onMouseOver event. While this functionality works as expected, I am facing difficulties replicating the behavior ...

.value not showing correct data in JavaScript

I am attempting to retrieve the value entered by the user in an HTML input field. While I can display a fixed, predetermined value with ease, this is not my intention. My goal is for users to input a numerical value and for that value to be displayed/adj ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Disconnect occurred during execution of Node.js "hello world" on a Windows 7 operating system

Issue Resolved: Oh no! jimw gets 10000 points for the solution! I've decided to delve into a hobby project using Node.js. Here's where I started: Downloaded and installed Node version 0.6.14 Copied and pasted the classic "hello world" program ...

JavaScript Equivalent of Declaration in TypeScript

In my Next JS application, I encountered a situation where a line of code relies on a variable from a script src in the app.tsx page. Here's how it looks: app.tsx: <script src="https://js.stripe.com/v3/"></script> config.ts: de ...

Designing a photo frame slider for a unique touch

My skills in javascript and jQuery are limited, but I am looking to create a customizable slider. While exploring options like Flexslider (), I found it challenging to meet the following specifications: Eliminate color gaps between thumbnails Enable thu ...

In order to showcase the data from the second JSON by using the unique identifier

SCENARIO: I currently have two JSON files named contacts and workers: contacts [ { "name": "Jhon Doe", "gender": "Male", "workers": [ "e39f9302-77b3-4c52-a858-adb67651ce86", "38688c41-8fda-41d7-b0f5-c37dce3f5374" ] }, { "name": "Peter ...

Storing filtered data objects for future use

Introduction to my User Administration Page Currently, I am working on the User Administration page of my project and facing a minor issue. The page includes a table that displays material-ui's Usercard for each user in the system. These cards are ge ...

Utilize Google Tag Manager to search and substitute characters within a variable

Within my GTM setup, I have a CSS selector variable in the DOM. This variable pertains to real estate and specifically represents the price of a listing. My goal is to eliminate the characters ($) and (,) from this variable as part of meeting the requireme ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...

Guide on converting a JSON object to GSON in Java

Here is the API response returned in JSON format: {"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_ ...

What is the method for extracting JavaScript code as data from a script tag?

I have a file external (let's say bar.js) function qux() {} Then in my webpage, I include it using the script tag: <script type="text/javascript" src="bar.js"></script> I am looking for a way to retrieve the JavaScript code from within ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

The velocity of jQuery selectors

Which is more efficient: using only the ID as a selector or adding additional identifiers? For instance $('#element') vs $('#container #element') or getting even more detailed: $('body div#container div#element') ? ...

Utilize Vue-cli 3.x to load static resources

In my vue-cli 3 project, I have organized the static assets in the public directory. When compiled and built on localhost, all assets load successfully, except for some images not appearing in the browser. Despite guyana-live-logo.png, slide-1.jpg, and 97 ...