使用ajax将变量值传递到php文件

使用ajax将变量值传递到php文件,php,jquery,ajax,Php,Jquery,Ajax,我想要实现的是在数据库中存储变量的值。现在我的js代码中有了var currentValue,它等于输入字段的值。我必须实现的是将该变量的值传递给sql数据库。其余的代码工作正常-我可以存储日期时间和ip地址 HTML: <html> <head> <?php include('add.php') ?> <link rel = "stylesheet" href = "styles.css" type = "text/css">

我想要实现的是在数据库中存储变量的值。现在我的js代码中有了var currentValue,它等于输入字段的值。我必须实现的是将该变量的值传递给sql数据库。其余的代码工作正常-我可以存储日期时间和ip地址

HTML:

<html>

<head>


  <?php include('add.php') ?>
  <link rel = "stylesheet" href = "styles.css" type = "text/css">
  <link href="https://fonts.googleapis.com/css?family=Vollkorn" rel="stylesheet">
  <script
        src="https://code.jquery.com/jquery-3.1.1.min.js"
        integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
        crossorigin="anonymous"></script>

    <title>Тестовое задание Трофимов</title>

</head>

<body>

  <div id = "main_container">

    <div id = "success_message">

      <p>Товар добавлен в корзину</p>

      <div id = "tooltip_arrow"></div>

    </div>

    <div class = "clearfix"></div>
    <div id = "form">
    <input name = "submit" type = "button" value = "купить" id = "button">

    <div class = "quantity_counter" id = "minus"><a href="#" id="decrease">&#8211;</a></div>

    <input type = "text" size = "3" value = "1" id = "input_quantity" name = "input_quantity"></input>

    <div class = "quantity_counter" id = "plus"><a href="#" id="increase">&#43;</a></div>

    </div>
    <div class = "clearfix"></div>  

    <div id = "error_message"><br/><p>Укажите количество товаров!</p></div>


  </div>



  <script type ="text/javascript" src = "js.js"></script>

</body>

</html>
  $(document).ready(function(){

var currentValue = 1;

  $('#increase').click(function(e){
      e.preventDefault();
      currentValue = parseInt($('#input_quantity').val());
      currentValue++;
      $('#input_quantity').val(currentValue);
  });


  $('#decrease').click(function(e){
    e.preventDefault();
    currentValue = parseInt($('#input_quantity').val());
    currentValue--;
    if(currentValue < 1) {
       currentValue = 0;
    }
    $('#input_quantity').val(currentValue);


  });


  function Messager(){
      this.showMessage = function(container){
      $(container).fadeIn();
      setTimeout(function() { 
        $(container).fadeOut(); 
      }, 3000);
    };
      this.success = function(){
      this.showMessage("#success_message");
    };
      this.error = function(){
      this.showMessage("#error_message");
    };
  }

    $('#button').click(function(e){
        $.ajax({
         url: "add_to_cart.php",
         type: 'post',
         dataType: 'html',
         data: {
              id: currentValue,
         }
        }).done(function(response){


          var msg = new Messager();
          if (currentValue != 0) {
            msg.success();

          } else {
            msg.error();
          }
        });     
    });

});
<?php


    $servername = "myhost";
    $username = "myUsername";
    $password = "mypassword";
    $dbname = "mydbname";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $currentValue = $_POST['currentValue'];
    $date = date('Y/m/d H:i:s');
    $sql = sprintf("INSERT INTO test (amount, ip, date)
    VALUES ('%s', '%s', '%s')", $currentValue, $_SERVER['REMOTE_ADDR'], $date);

    if ($conn->query($sql) === TRUE) {
        echo  '<script type="text/javascript">',
         'Messager();',
         '</script>'
    ;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
?>

Тестовое задание Трофимов
бббббббзб


JS:

<html>

<head>


  <?php include('add.php') ?>
  <link rel = "stylesheet" href = "styles.css" type = "text/css">
  <link href="https://fonts.googleapis.com/css?family=Vollkorn" rel="stylesheet">
  <script
        src="https://code.jquery.com/jquery-3.1.1.min.js"
        integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
        crossorigin="anonymous"></script>

    <title>Тестовое задание Трофимов</title>

</head>

<body>

  <div id = "main_container">

    <div id = "success_message">

      <p>Товар добавлен в корзину</p>

      <div id = "tooltip_arrow"></div>

    </div>

    <div class = "clearfix"></div>
    <div id = "form">
    <input name = "submit" type = "button" value = "купить" id = "button">

    <div class = "quantity_counter" id = "minus"><a href="#" id="decrease">&#8211;</a></div>

    <input type = "text" size = "3" value = "1" id = "input_quantity" name = "input_quantity"></input>

    <div class = "quantity_counter" id = "plus"><a href="#" id="increase">&#43;</a></div>

    </div>
    <div class = "clearfix"></div>  

    <div id = "error_message"><br/><p>Укажите количество товаров!</p></div>


  </div>



  <script type ="text/javascript" src = "js.js"></script>

</body>

</html>
  $(document).ready(function(){

var currentValue = 1;

  $('#increase').click(function(e){
      e.preventDefault();
      currentValue = parseInt($('#input_quantity').val());
      currentValue++;
      $('#input_quantity').val(currentValue);
  });


  $('#decrease').click(function(e){
    e.preventDefault();
    currentValue = parseInt($('#input_quantity').val());
    currentValue--;
    if(currentValue < 1) {
       currentValue = 0;
    }
    $('#input_quantity').val(currentValue);


  });


  function Messager(){
      this.showMessage = function(container){
      $(container).fadeIn();
      setTimeout(function() { 
        $(container).fadeOut(); 
      }, 3000);
    };
      this.success = function(){
      this.showMessage("#success_message");
    };
      this.error = function(){
      this.showMessage("#error_message");
    };
  }

    $('#button').click(function(e){
        $.ajax({
         url: "add_to_cart.php",
         type: 'post',
         dataType: 'html',
         data: {
              id: currentValue,
         }
        }).done(function(response){


          var msg = new Messager();
          if (currentValue != 0) {
            msg.success();

          } else {
            msg.error();
          }
        });     
    });

});
<?php


    $servername = "myhost";
    $username = "myUsername";
    $password = "mypassword";
    $dbname = "mydbname";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $currentValue = $_POST['currentValue'];
    $date = date('Y/m/d H:i:s');
    $sql = sprintf("INSERT INTO test (amount, ip, date)
    VALUES ('%s', '%s', '%s')", $currentValue, $_SERVER['REMOTE_ADDR'], $date);

    if ($conn->query($sql) === TRUE) {
        echo  '<script type="text/javascript">',
         'Messager();',
         '</script>'
    ;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
?>
$(文档).ready(函数(){
var currentValue=1;
$(“#增加”)。单击(函数(e){
e、 预防默认值();
currentValue=parseInt($('#input_quantity').val();
currentValue++;
$('输入数量').val(当前值);
});
$(“#减少”)。单击(函数(e){
e、 预防默认值();
currentValue=parseInt($('#input_quantity').val();
当前值--;
如果(当前值<1){
currentValue=0;
}
$('输入数量').val(当前值);
});
函数Messager(){
this.showMessage=函数(容器){
$(container.fadeIn();
setTimeout(函数(){
$(容器).fadeOut();
}, 3000);
};
this.success=function(){
此.showMessage(“成功消息”);
};
this.error=函数(){
此.showMessage(“错误消息”);
};
}
$(“#按钮”)。单击(函数(e){
$.ajax({
url:“将_添加到_cart.php”,
键入:“post”,
数据类型:“html”,
数据:{
id:currentValue,
}
}).完成(功能(响应){
var msg=new Messager();
如果(当前值!=0){
msg.success();
}否则{
msg.error();
}
});     
});
});
PHP:

<html>

<head>


  <?php include('add.php') ?>
  <link rel = "stylesheet" href = "styles.css" type = "text/css">
  <link href="https://fonts.googleapis.com/css?family=Vollkorn" rel="stylesheet">
  <script
        src="https://code.jquery.com/jquery-3.1.1.min.js"
        integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
        crossorigin="anonymous"></script>

    <title>Тестовое задание Трофимов</title>

</head>

<body>

  <div id = "main_container">

    <div id = "success_message">

      <p>Товар добавлен в корзину</p>

      <div id = "tooltip_arrow"></div>

    </div>

    <div class = "clearfix"></div>
    <div id = "form">
    <input name = "submit" type = "button" value = "купить" id = "button">

    <div class = "quantity_counter" id = "minus"><a href="#" id="decrease">&#8211;</a></div>

    <input type = "text" size = "3" value = "1" id = "input_quantity" name = "input_quantity"></input>

    <div class = "quantity_counter" id = "plus"><a href="#" id="increase">&#43;</a></div>

    </div>
    <div class = "clearfix"></div>  

    <div id = "error_message"><br/><p>Укажите количество товаров!</p></div>


  </div>



  <script type ="text/javascript" src = "js.js"></script>

</body>

</html>
  $(document).ready(function(){

var currentValue = 1;

  $('#increase').click(function(e){
      e.preventDefault();
      currentValue = parseInt($('#input_quantity').val());
      currentValue++;
      $('#input_quantity').val(currentValue);
  });


  $('#decrease').click(function(e){
    e.preventDefault();
    currentValue = parseInt($('#input_quantity').val());
    currentValue--;
    if(currentValue < 1) {
       currentValue = 0;
    }
    $('#input_quantity').val(currentValue);


  });


  function Messager(){
      this.showMessage = function(container){
      $(container).fadeIn();
      setTimeout(function() { 
        $(container).fadeOut(); 
      }, 3000);
    };
      this.success = function(){
      this.showMessage("#success_message");
    };
      this.error = function(){
      this.showMessage("#error_message");
    };
  }

    $('#button').click(function(e){
        $.ajax({
         url: "add_to_cart.php",
         type: 'post',
         dataType: 'html',
         data: {
              id: currentValue,
         }
        }).done(function(response){


          var msg = new Messager();
          if (currentValue != 0) {
            msg.success();

          } else {
            msg.error();
          }
        });     
    });

});
<?php


    $servername = "myhost";
    $username = "myUsername";
    $password = "mypassword";
    $dbname = "mydbname";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $currentValue = $_POST['currentValue'];
    $date = date('Y/m/d H:i:s');
    $sql = sprintf("INSERT INTO test (amount, ip, date)
    VALUES ('%s', '%s', '%s')", $currentValue, $_SERVER['REMOTE_ADDR'], $date);

    if ($conn->query($sql) === TRUE) {
        echo  '<script type="text/javascript">',
         'Messager();',
         '</script>'
    ;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
?>

将数据:{id:currentValue,}更改为数据:{currentValue:currentValue,}并且您正在使用数据类型:'html',而不是使用text/jsoni如果我将数据类型更改为json,消息会因某种原因停止显示:(您能否仅将代码:{id:currentValue,}更新为数据:{currentValue:currentValue,}在Ajax中,$currentValue=$\u POST['currentValue']之后,只需使用print_r($currentValue');退出;然后查看您是否从ajaxYes获取值,这就成功了!谢谢。仍然必须坚持html数据类型,因为如果选择json,我将停止接收消息。将数据:{id:currentValue,}更改为数据:{currentValue:currentValue,}并且您正在使用数据类型:'html',而不是使用text/json如果我将数据类型更改为json,消息会因为某种原因停止显示:(您能否仅将代码:{id:currentValue,}更新为数据:{currentValue:currentValue,}在$currentValue=$\u POST['currentValue'];只需使用print_r($currentValue);退出;然后查看您是否从ajaxYes获取值,这就成功了!谢谢。仍然必须坚持使用html数据类型,因为如果选择json,我将停止接收消息。