0

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

10
  • 6
    You probably just need to replace 'onparam($param);', by "onparam($param);", (double quotes instead of simple) Commented Jun 4, 2019 at 14:30
  • 2
    Possible duplicate of How to pass variables and data from PHP to JavaScript? Commented Jun 4, 2019 at 14:31
  • wha.. just have a .js file with an ajax call inside to the PHP? Commented Jun 4, 2019 at 14:31
  • 1
    This is out of the scope of the question but it's pretty easy to parse GET parameters in Javascript nowadays Commented Jun 4, 2019 at 14:39
  • 2
    (You know that JavaScript has access to the URL as well, right? And that URLSearchParams gives easy access to GET parameters …) Commented Jun 4, 2019 at 14:58

1 Answer 1

2

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>";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.