2

Sorry for the bad title, but I don't know how to name this. My problem is that whenever I pass a value from a select box I trigger this jquery event in order to check on the check boxes. Bassically I echo $res[]; at selecctedgr.php. Do I need to use json? and how can I do this?

Mainpage:

$("#group_name").change(function(){
    var groupname = $("#group_name").val();
    var selectedGroup = 'gr_name='+ groupname;
    $.post("selectedgr.php", {data: selectedGroup}, function(data){
        $.each(data, function(){
            $("#" + this).attr("checked","checked");
        });
    },"json");


});

PHP (selectedgr.php):

<?php
    include_once '../include/lib.php';
    $gr_name=mysql_real_escape_string($_POST['gr_name']);

    $sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name;
    $resultgr = sql($sqlgr);
    while($rowgr = mysql_fetch_array($resultgr)){
        $res[] = $rowgr['ACT_ID'];
    }

    echo $res[];
?>
Salman A
  • 262,204
  • 82
  • 430
  • 521
Eric T
  • 1,026
  • 3
  • 20
  • 42
  • 4
    Your code has a [SQL injection](http://stackoverflow.com/questions/2216107/what-is-sql-injection) vulnerability – Unicron Mar 21 '11 at 09:04
  • where?? please guide me > <'' – Eric T Mar 21 '11 at 09:05
  • 2
    @Eric you need to escape `$gr_name` using `mysql_real_escape_string()` if it's a string (then you need to add quotes) or if it's a numeric id, check whether it's a number using `intval()`. – Unicron Mar 21 '11 at 09:08
  • what is the purpose of ` $.each(data, function(){ $("#" + this).attr("checked","checked"); });` – Harish Mar 21 '11 at 09:08
  • 1
    `$sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name;` here. You should use sql placeholders (bind vars). Something like this: $sql = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=:n"; $stmt = $pdo->prepare($sql); // bind php variables to the placeholders in the statement $stmt->bindParam(':n', $gr_name); $stmt->execute(); //sorry, i'm not a php guru ;) But you've got an idea... – NilColor Mar 21 '11 at 09:08
  • @NilColor is talking about using PHP's PDO classes from what I can see. http://php.net/manual/en/book.pdo.php for more information. He is right that it is a better method for interacting with the database. – Treffynnon Mar 21 '11 at 09:14
  • Just do a `$sqlgr = sprintf("SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=%d", $_POST['gr_name']);`. AFAIK, this will become `SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=0` when someone posts rubbish value in `$_POST['gr_name']`. – Salman A Mar 21 '11 at 09:19

4 Answers4

9

Change the last line in your PHP sample (echo $res[];) to:

echo json_encode($res);

json_encode() manual page will tell you more.

Also as @Unicron says you need to validate the $gr_name variable before passing it to your SQL statement.

You could use:

if(isset($_POST['gr_name'])) {
    $gr_name = mysql_real_escape_string($_POST['gr_name']);
}

See: http://php.net/manual/en/function.mysql-real-escape-string.php for more information in the PHP manual.

Treffynnon
  • 21,365
  • 6
  • 65
  • 98
6

You can use json_encode function to convert arbitrary data into JSON. Assuming that you want to return an array of strings, here is how you will use json_encode:

<?php
    include_once '../include/lib.php';
    $res = array(); // initialize variables
    $sqlgr = sprintf("
        SELECT ACT_ID
        FROM PRIVILLAGE
        WHERE MAINGR_ID=%d
        ",
        $_POST['gr_name']
    ); // only select those columns that you need
       // and do not trust user input
    $resultgr = sql($sqlgr);
    while($rowgr = mysql_fetch_array($resultgr)){
        $res[] = $rowgr['ACT_ID'];
    }
    echo json_encode($res); // use json_encode to convert the PHP array into a JSON object
                            // this will output something like ['foo', 'bar', 'blah', 'baz'] as a string
?>

On the client side you can use jQuery.post method, like this:

<script type="text/javascript">
$("#group_name").change(function () {
    $.post("selectedgr.php", {
        gr_name: $(this).val()
    }, function (data) {
        // console.log(data);
        // jQuery will convert the string "['foo', 'bar', 'blah', 'baz']" into a JavaScript object
        // (an array in this case) and pass as the first parameter
        for(var i = 0; i < data.length; i++) {
            $("#" + data[i]).attr("checked", "checked");
        }
    }, "json");
});
</script>
Salman A
  • 262,204
  • 82
  • 430
  • 521
1

If you want to use JSON then just use echo json_encode($res); But I don't really understand what you'll gain if your code is working now, since you'll still have to do some processing in the Javascript to handle the result.

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76
0

I found my major problem as below

instead of (before):

 $.post("selectedgr.php", {data: selectedGroup}, function(data){

do this (after):

$.post("selectedgr.php", selectedGroup, function(data){

Forgive my bad. Ahh ya guys, regarding the escaping on mysql actually #group_name is not any input field but a select box. Appreciate for every comment, suggestion and guide.

Eric.

Eric T
  • 1,026
  • 3
  • 20
  • 42
  • 1
    Don't assume that some one will not attempt to post values that you do not expect just because it is a select box. There are plenty of plugins for firefox to change field types in forms, some one could write a bot, make a CURL request your AJAX endpoint or simply write their own HTML form to submit onto your PHP. Validate **everything**! – Treffynnon Mar 21 '11 at 10:04
  • Okay get it, will do escape~ Thx – Eric T Mar 21 '11 at 13:14