如何向服务器发送ajax调用并在数据库中插入数据?

时间:2021-07-12 06:34:30

I have 3 buttons each button means a type of error :

我有3个按钮,每个按钮意味着一种错误:

<button id="E1_<?= $c['code'] ?>">Type error 1</button>
<button id="E1_<?= $c['code'] ?>">Type error 2</button>
<button id="E1_<?= $c['code'] ?>">Type error 3</button>

This's my table :

这是我的表:

  CREATE TABLE button_check
   (
      code varchar(255),
      button_1 int(11),
      button_2 int(11),
      button_3 int(11)
   );

//Click & De-click :

//点击并取消点击:

$(function()
 {

 jQuery.fn.clickToggle = function(d,c){
    function cb(){ [d,c][this._tog^=1].call(this); }
    return this.on("click", cb);
 };

var all_errors = {'E1':0,'E2':0,'E3':0};

var btn1 = false;
btn2 = false;
btn3 = false;

  $("[id^='E1_']").clickToggle(function(){
    all_errors.E1++;
    console.log(errors);
},function(){
    if(all_errors .E1 > 0) all_errors .E1--;
});

});


  $.ajax({ url: 'data_insert.php',
   data: {id: value,value: all_errors},
   type: 'post',
   success: function(output) {
     console.log(output);
   }

data_insert.php :

    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    $id = $_POST['id'];
    $value = $_POST['value'];
    try {      
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,  $password);

    $sql = "INSERT INTO button_check (code,button_1, button_2,button_3) VALUES ('$code','$btn1', 'btn2', 'btn3')";
    $conn->exec($sql);
    catch(PDOException $e)
     {
      echo $sql . "<br>" . $e->getMessage();
     }
    } 

I want to send an ajax call and insert all clicks in my table.

我想发送一个ajax调用并在我的表中插入所有点击。

Please i need help. Thanks a lot.

我需要帮助。非常感谢。

1 个解决方案

#1


0  

You will do something like jquery post $.post to the php file. The file will read the post contents and insert into database.

您将执行类似jquery post $ .post到php文件的操作。该文件将读取帖子内容并插入数据库。

//jquery code

$.post('insert.php', {data:data}, function(raw){
//success here 
});

//insert.php

$dataJSON = $_POST['data'];
$data = json_decode($dataJSON);
//setup connection and do insert with that data

#1


0  

You will do something like jquery post $.post to the php file. The file will read the post contents and insert into database.

您将执行类似jquery post $ .post到php文件的操作。该文件将读取帖子内容并插入数据库。

//jquery code

$.post('insert.php', {data:data}, function(raw){
//success here 
});

//insert.php

$dataJSON = $_POST['data'];
$data = json_decode($dataJSON);
//setup connection and do insert with that data