简体   繁体   中英

Ajax to php and store in database

Hello I am having a problem

I am sending a javascript variable to my php script and attemping to store that variable in mysql db but it just does not work.

Here is my code:

js:

<script type="text/javascript">
        var myData = "Hello";

        function AJAXAction () {
            $.ajax({
                url: 'test.php',
                data: { myPhpData: myData },
               success: function (response) {
                alert (response);
               }
            }); 
        }

        AJAXAction();
    </script>

PHP:

 <?php
$link = mysqli_connect("localhost","root","","testt") or die("Error " . mysqli_error($link));
function goDoIt ($link) {
    $why = $_GET['myPhpData'];  
    $sql = "INSERT INTO test_table (id) VALUES '$why'";
    mysqli_query($link, $sql);
    echo "booooom";
}
goDoIt ($link);     
mysqli_close($link);
?>

The result alerts "boooom" but it does not store my $why variable in my table

Try it:

$why = $_GET['myPhpData'];  
$sql = "INSERT INTO test_table (id) VALUES '$why'";
if(mysqli_query($link, $sql)){
   echo "booooom";
}else{
   echo "error";
}

Then you can get if the query is correct or not.

变量应包含在{}中,并且您需要将其包含在()中

  $sql = "INSERT INTO test_table (id) VALUES ('{$why}')";
$sql = "INSERT INTO test_table (id) VALUES ('".$why."');

你也可以这样做

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM