简体   繁体   中英

Insert values into a database using javascript and php

I'm trying to retrieve data from a html table based on which check box is checked

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;
    }

then send this data to a php file which then inserts these values into a database.

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

My php is as follows

<?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)
?>

I'm new to JavaScript so I may be completely wrong here.

The post request is incorrect. You code should look more like this:

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));

So what's the issue? If you're wondering how to call updtBask() you can do so with a button: <button onclick='updtBask()'>Update</button>

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