What is the proper way to extract and pass parameters to call javascript functionality from my PHP page?

This is my situation: I have a search results page in PHP where most of the logic resides in a javascript file in order to avoid refreshing the page every time an action is performed. The first thing I do using PHP is filter out and save valid query string values to PHP variables and I make use of the htmlspecialchars function to prevent injection. Now, I’d like to call my javascript function using those variables, so I created a script tag at the bottom of the page in order to pass the PHP variables to it (see my example).

When I put all of my javascript code inside of its own scope (as I read this was a good security practice), I realized that I could no longer call my function from outside of it. I also realize that the javascript method can still be called with anything a hacker wants, so does that mean I can’t really make use of htmlspecialchars in my situation?

Here’s a stripped-down version of my code:

<?php
try {       
  if (isset($_GET["id"])) {
    if (!is_numeric($_GET["id"]))
      throw new Exception("URL is not in a correct format");
    $id= $_GET["id"];
  }
  elseif (isset($_GET["keyword"])) {
    $keyword = htmlspecialchars($_GET["keyword"]);
  }
}
catch (Exception $e) {
  // handle error
}
?>
<html>
<head></head>
<body>
  <div class="searchResults"><!-- placeholder --></div>
  <?php
  if (isset($id)) { 
    echo '<script type="text/javascript">ShowSearchResults("id",'.$id.');</script>';        
  }
  elseif (isset($keyword)) { 
    echo '<script type="text/javascript">ShowSearchResults("keyword","'.$keyword.'");</script>'; 
  }
  ?>
</body>
</html>

This is basically the js:

function ShowSearchResults(key,value)
{
    $.getJSON("includes/search_results.php?"+key+"="+value, 
    function(data) {
      // populate search results
      $(".searchResults").html( "search results" );
    })
    .error(function() { 
       $(".searchResults").html( "no results" );
    });
}

My questions are (while keeping security and best practices in mind):

Is it bad practice to pass the query string values to my javascript function from within the body? I initially did this because I had the impression that it was not a good idea to extract query string values using javascript. Maybe I’m wrong there.

Should I be extracting the query string values from the $(document).ready function, and then calling the appropriate javascript functions from there? What is the appropriate way to do that (htmlspecialchars equivalent)?

Keep in mind that within my javascript code, I use $.getJSON to call another server side function (in PHP) that can reject anything insecure.

Any insight would be greatly appreciated.

5

Just copy one of the functions from this Stack Overflow post on retrieving values from a query string, and reuse it in your JavaScript code, such as this function:

function getParameterByName(name) {
    name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
    var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
}

There’s nothing wrong with pulling parameters from the query string in your JavaScript code as long as you are not executing anything you get from the query string. The JavaScript equivalent of htmlspecialchars is here.

However, if the $id was not coming from the query string, lets say it was coming directly from your server, it would be fine to echo it into your HTML and access it from JavaScript. (Try pressing ctrl-u now and see this page’s HTML).

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật