John
John

Reputation: 952

How to put PHP inside javascript

I am trying to add a else if statement in my Javascript code but so far it is not succesfull.

Here is the original script:

{ "targets": 4, "render": function ( data, type, full, meta ) { return  '+data+'; } }

+data+ returns a 0 or 1

I tried:

{ "targets": 4, "render": function ( data, type, full, meta ) { return  '<?php if ('+data+' == 0){ <font color=red> } else if ('+data+' == 1){ <font color=blue> } ?>'+data+'</font>'; } }

But when I run this I get a browser error.

Can someone help me with it?

Edit 1:

I am not trying to pass variables and data from PHP to JavaScript. I am trying to get data from Javascript and pass it to my PHP.

Upvotes: 1

Views: 45

Answers (1)

Sandeesh
Sandeesh

Reputation: 11906

That's not how PHP works. You have a simple check here, why don't you use javascript conditionals? Here's how you can do it with JS.

var test = {
    "targets": 4,
    "render": function (data, type, full, meta) {
        return '<font color="'+ (data === 0 ? 'red' : 'blue') +'">'+data+'</font>';
    }
};

// Or

var test = {
    "targets": 4,
    "render": function (data, type, full, meta) {
        if (data === 0) {
            return '<font color="red">'+data+'</font>';
        }

        return '<font color="blue">'+data+'</font>';
    }
};

Upvotes: 1

Related Questions