Gaurav Mehta
Gaurav Mehta

Reputation: 1153

Passing URL with query parameters as function parameter in JavaScript

I have a URL that looks like

https://go.feeds4.com/merchants/?pid=1676&mid=4261

How do I pass this as a function parameter. I am trying to pass the value but not able to get anything in the function.

Does the & in query paramter cause issues?

HTML

<a href="javascript:;"
   onclick=rendernewmodal(<?php echo '"'.htmlspecialchars_decode($merchant->affiliate_link).'"'; ?>);>
  <i class="fa fa-angle-right" aria-hidden="true"></i>
</a>

On View Page Source, I can see the following

<a href="javascript:;"
   onclick=rendernewmodal("https://go.feeds4.com/merchants/?pid=1676&mid=4261");>

JS

function rendernewmodal(url) {
  alert (url);
}

I don't see any alert showing value of the URL. Please help.

Upvotes: 1

Views: 827

Answers (1)

Quentin
Quentin

Reputation: 943214

You have two problems:

  1. When putting data into an HTML document, you have to encode it for HTML not decode it from HTML
  2. Attribute values need quoting when they contain certain characters (like quotes)

Mashing strings together to make JavaScript literals is error prone and messy, so you should avoid doing that by hand too.

So:

<?php
    # Get the URL
    $url = $merchant->affiliate_link;

    # Put quotes around it and escape special characters for JS
    $url_as_js_string_literal = json_encode($url);

    # Put it in the rest of the JS
    $js_function_call = "rendernewmodal($url_as_js_string_literal);";

    # Escape special characters for HTML
    $html_safe_js = htmlspecialchars($js_function_call);
?>
onclick="<?php echo $html_safe_js; ?>)">

Upvotes: 1

Related Questions