qpA
qpA

Reputation: 95

How I send PHP parameter/variable to JS function?

I want to get URL parameter with PHP and send the parameter (ID) to a JS function.

This is what I tried.

PHP:

$param = $_GET['param']; 

if($param != "" || $param == NULL || (!empty($param))){

    echo '<script type="text/javascript">',
        'onparam($param);',
    '</script>';
}

JS:

function onparam(param) {
    $.ajax({url: "AJAX.php", data: 'id=' + param + '&switch_content=details', success: function(result){
            $("#data-table").html(result);
        }});
    document.getElementById("overlay").style.display = "block";
}

I tried to put the parameter in a variable and call the JS function with it. In the next step I tried to catch the variable in the JS function to put it in the string of "data:".

Upvotes: 0

Views: 72

Answers (1)

frobinsonj
frobinsonj

Reputation: 1167

You want to use double quote instead of singles quotes (as suggested by gogaz). You also want to put quotation marks around the variable if it's a string.

One more thing - You can remove $param != "" || $param == NULL as both "" & null are considered to be empty. I am assuming you mean $param != "" && $param != NULL here, if not, just ignore. But that may also be causing the issue if $param is null.

$param = $_GET['param']; 

if(!empty($param)) {

    echo "<script type='text/javascript'>",
        "onparam('$param');",
    "</script>";
}

Upvotes: 2

Related Questions