使用javascript和php将值插入数据库

时间:2015-04-17 17:05:33

标签: javascript php ajax

我试图根据选中的复选框从html表中检索数据

function updtBask() {

 if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

var table = document.getElementById("mytable");
var chkBox = document.getElementById("1");
//for (var i = 1, row; row = table.rows[i].cells[4]; i++) {
    if (chkBox.checked) {
        var imgOne = document.getElementById("mytable").rows[1].cells[0].innerHTML;
        var prcOne = document.getElementById("mytable").rows[1].cells[1].innerHTML;
        var nameOne = document.getElementById("mytable").rows[1].cells[2].innerHTML;
        var descOne = document.getElementById("mytable").rows[1].cells[3].innerHTML;
    }

然后将此数据发送到php文件,然后将这些值插入数据库。

xmlhttp.open("POST","updateBasket.php"+{imgOne :imgOne, prcOne: prcOne, nameOne: nameOne, descOne: descOne},true);
xmlhttp.send();

我的php如下

<?php
//create connection
$con = mysqli_connect("csmysql.cs.cf.ac.uk", "c1427641", "adnog9","c1427641");
//get variables from javascript
$one = $_POST["imgOne"];
$two = $_POST["prcOne"];
$three =$_POST["nameOne"];
$four = $_POST["descOne"];

 // command to execute
 $command= "INSERT INTO basket (image, price, name, description) VALUES ('$one', '$two', '$three', '$four')"
//execute command
$result = mysqli_query($con, $command)

//close connection
mysql_close($con)
?>

我是JavaScript的新手,所以我在这里可能完全错了。

2 个答案:

答案 0 :(得分:1)

发布请求不正确。您的代码看起来应该更像这样:

var id = "xyz";
var value = 123;

var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'updateBasket.php');
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState==4) {
        if(xmlhttp.status==200) {
            alert("good");
        }
    }
};
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("userid=" + encodeURIComponent(id) + "&value=" + encodeURIComponent(value));

答案 1 :(得分:-1)

那么问题是什么?如果您想知道如何拨打updtBask(),可以点按一下按钮:<button onclick='updtBask()'>Update</button>