Reputation: 58
My goal is when I click a button on this webpage, there will be data entered into the MySQL database.
On the .html page:
<html>
<body>
<p id="output">Output here</p>
<!-- Primary Page Layout
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<div class="container" style="background-image: url(images/background.png); width: 640px; height: 1400px; ">
<div class="row">
<div class="one-half column" style="margin-top: 25%">
<button onclick="submitFunction()" style="width: 150px; height: 100px; position: absolute; left: 70px; top: 880px;">test</button>
</div>
</div>
</div>
<!-- Scripts-->
<script>
function submitFunction() {
$.ajax({
url: 'sendcheck.php',
type: 'post',
data: {'Test1': 'data1', 'Test2': 'data2', 'Test3': 'data3', 'Test4': 'data4', 'Test5': 'data5'},
success: function(data, status) {
if(data == "ok") {
document.getElementById("output").innerHTML = "Data sent";
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
}
</script>
<!-- End Document
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>
</html>
The "sendcheck.php" page here:
<?php
$db = "testBase";
$dbu = "root";
$dbp = "test_test";
$host = "localhost";
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['Test1']) && isset($_GET['Test2']) && isset($_GET['Test3']) && isset($_GET['Test4']) && isset($_GET['Test5'])){
$Test1 = strip_tags(mysql_real_escape_string($_GET['Test1']));
$Test2 = strip_tags(mysql_real_escape_string($_GET['Test2']));
$Test3 = strip_tags(mysql_real_escape_string($_GET['Test3']));
$Test4 = strip_tags(mysql_real_escape_string($_GET['Test4']));
$Test5 = strip_tags(mysql_real_escape_string($_GET['Test5']));
$sql = mysql_query("INSERT INTO `$db`.`tester_table` (`ID,`Test1`,`Test2`,`Test3`,`Test4`,`Test5`) VALUES ('','$Test1','$Test2','$Test3','$Test4','$Test5');");
if($sql){
echo 'Your data was submitted';
}else{
echo 'There was a problem. Please try again later.';
}
}else{
echo 'Your test wasnt passed in the request. Make sure you add ?Test1=data1_HERE&Test2=data2_here&Test3=data3_here&Test4=data4_here&Test5=data5_here to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
I have been stumped on this for a couple of days. When I hit the button, nothing happens. Am I even on the right track? Or is there possibly an easier way of doing what I'm trying to accomplish.
Upvotes: 0
Views: 1693
Reputation: 126
You are doing a post with Ajax and in the php you are using $_GET to read the variables. You should use $_POST instead of $_GET.
Upvotes: 1