My Ajax does not pass values ​​to a php page

I have phppage.php which connects to a MySQL database:


    $list = 'A,B,C';

    $cxn   = mysqli_connect("localhost", $username, $password, $database) or die("Didn't connect");
    $query = "SELECT * FROM Questions3 WHERE 1 IN ($list) ORDER BY RAND() LIMIT 10";

    $result = mysqli_query($cxn,$query) or die ("Didn't work");

    while( $row = mysqli_fetch_assoc($result) )
        echo "<div>";
        echo $row['columnname'];
        echo "</div>";

This pulls out 10 random database entries where columns A, B or C have the value "1".

This page runs fine on its own. But I actually need to call this using AJAX (which I'm new to), from another page using checkboxes. So instead of

$list = 'A,B,C'

I need

$list = "data1"

where the jQuery on my main page is:

    var data1 = 'A,B,C';
    $.ajax({url:"phppage.php", type:"POST", data:data1, success:function(result){

And the html is:

<div id="display">Data should show here</div>

(Obviously in this simplified version I'm ignoring the checkboxes).

However, when I press the button, I get "Didn't work" displayed. So "data1" in my JQuery is not transferring to become my $list in the PHP.

What's wrong with my AJAX: how can I transfer the "data1" string?

The problem is the way you send your data in javascript:

// data1 is a string

The data key expects key - value pairs, so you would have to do something like:

data: {'mydata': data1}

And then you would have your string in php in $_POST['mydata'].

And when you use posted values / user input, you should make sure you avoid sql injection by using a prepared statement or mysqli_real_escape_string() on the input variables.

Also note that when you use IN in mysql, each value you want to use has to be bound individually, you cannot bind a range when you use a prepared statement.

And lastly, do you want to check for the number 1 or do you have a column named 1? If it is the latter, you need to quote it in backticks:

SELECT * FROM Questions3 WHERE `1` IN (?,?,?) ORDER BY RAND() LIMIT 10
                               ^^^ here