Reputation: 2530
I'm trying to update a database using javascript and PHP, this is my index.html
code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<input type="text" id="descriptioninput">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="addToDB()">Add to database</button>
<script>
function addToDB()
{
var descriptioninput = document.getElementById('descriptioninput').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
$.ajax ( {
type: 'POST',
url: 'addtodb.php',
data:{descriptioninput:descriptioninput, budgetin:budgetin, budgetout:budgetout},
success:function (data) {
// Completed successfully
alert('success!');
}
});
</script>
</body>
</html>
Here's my addtodb.php
code:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb";
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn === TRUE)
{
$descriptioninput = $_GET['descriptioninput'];
$budgetin = $_GET['budgetin'];
$budgetout = $_GET['budgetout'];
$query = "INSERT INTO budget (description, budgetin, budgetout) VALUES ('$descriptioninput', '$budgetin', '$budgetout')";
$conn->query($query);
$conn->close();
}
?>
But it appears as if my PHP script doesn't run. No changes appear in my database. I've tried to do warning() in the PHP file and alert it it using.done(function(text)), but nothing is displayed.
Upvotes: 2
Views: 148
Reputation: 24276
This is happening because you are doing the ajax request using POST
method in js but you are trying to get the variables using the GET
method in PHP. Switch it to GET
and it will work.
Be aware of SQL Injection. You can prevent it either by using prepared statements or escaping the string as:
$descriptioninput = $conn->real_escape_string($_GET['descriptioninput']);
Also, the first if
condition is not valid. You just need to do it like if ($conn)
instead of if ($conn === TRUE)
Upvotes: 2
Reputation: 6661
Change ajax type to GET
$.ajax ( {
type: 'GET',
url: 'addtodb.php',
data:{descriptioninput:descriptioninput, budgetin:budgetin, budgetout:budgetout},
success:function (data) {
// Completed successfully
alert('success!');
}
});
Upvotes: 1
Reputation: 852
I could be wrong but i believe description may be a reserved keyword in mySQL. try encapsing it
INSERT INTO budget (`description`, `budgetin`, `budgetout`) VALUES ('$descriptioninput', '$budgetin', '$budgetout')
Upvotes: 1
Reputation: 852
its a little messy with your mix between ajax and JS. Try using this getHTTP function for regular JS.
function httpGet(theUrl){
//FETCH Data From Server
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", theUrl , false );
xmlhttp.send();
return xmlhttp.responseText;
}
then just build your url as +addtodb.php?param1="+param1value+"¶m2="+param2value
Upvotes: 0