简体   繁体   中英

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:".

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 $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>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM