I am trying to insert data into a database with ajax. The problem is that everything works excepting the insertion of data in the database.
When I click the submit button I get the proper message "You have been subscribed" just that it doesn't insert the data in the database. And don't understand exactly why.
I have dbconn.php
<?php
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
?>
common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($name)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
subscribe.php
HTML
<form name="subscribe" class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
AJAX
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
Remove the quotes and substitute with backticks here
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed')
^ ^
Related
I m trying to send data value in database using ajax but it's not working. please any one help me.
I m trying to send data value in database using ajax but it's not working. please any one help me.
form.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="send_value" action="form.php" method="post">
<input type="text" name="name" value="" id="name">
<input type="text" name="address" value="" id="address">
<input type="submit" value="submit" id="save">
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#save').click(function() {
var name = $('#name').val();
var address = $('#address').val();
$.ajax({
type: "POST",
cache: false,
url: 'ajax.php',
data: { name: name, address: address},
success: function(data) {
alert('data has been stored to database');
}
});
});
});
</script>
</body>
</html>
and php file
<?php
include('DataModel.php');
$con = mysqli_connect("localhost","root","","ajax_test");
if (!$con)
{
die();
}
$name = $_POST['name'];
$address = $_POST['address'];
$sql = "INSERT INTO `test`(`name`, `address`) VALUES ($name,$address) ";
$query = mysqli_query($sql,$con);
$fetch = mysqli_fetch_assoc($query);
echo json_encode($fetch);
?>
Quotes are missing around the query
$sql = "INSERT INTO `test`(`name`, `address`) VALUES ('$name', '$address')";
You should also use prepared statements but in the very very least please escape your strings before passing them into the query
$name = mysqli_real_escape_string($con, $_POST['name']);
$address = mysqli_real_escape_string($con, $_POST['address']);
Lest you encounter bugs with addresses or names containing single quotes or leave yourself open to SQL injection attacks.
You have forgot the quotes here
$sql = "INSERT INTO `test`(`name`, `address`) VALUES ('$name','$address') ";
Or you can bind param like this
$stmt = $mysqli->prepare("INSERT INTO `test`(`name`, `address`) VALUES (?,?)");
$stmt->bind_param('ss', $name, $address);
$stmt->execute();
I made this typical form which shows a fade in message when submitting it! It works perfectly with up to 2 variables, but when i'm trying to change my code and insert a third variable or more a problem comes up when submitting.
The html code is:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Basic Form</title>
<meta name="description" content="A basic fade in form">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<title>Enable Disable Submit Button Based on Validation</title>
<style>
body{width:50%;min-width:200px;font-family:arial;}
#frmDemo {background: #98E6DB;padding: 40px;overflow:auto;}
#btn-submit{padding: 10px 20px;background: #555;border: 0;color: #FFF;display:inline-block;margin-top:20px;cursor: pointer;font-size: medium;}
#btn-submit:focus{outline:none;}
.input-control{padding:10px;width:100%;}
.input-group{margin-top:10px;}
#error_message{
background: #F3A6A6;
}
#success_message{
background: #CCF5CC;
}
.ajax_response {
padding: 10px 20px;
border: 0;
display: inline-block;
margin-top: 20px;
cursor: pointer;
display:none;
color:#555;
}
</style>
</head>
<body>
<h1>jQuery Fade Out Message after Form Submit</h1>
<form id="frmDemo" action="post-form.php" method="post">
<div class="input-group">Name </div>
<div>
<input type="text" name="name" id="name" class="input-control" />
</div>
<div class="input-group">Message </div>
<div>
<textarea name="comment" id="comment" class="input-control"></textarea>
</div>
<div class="input-group">Lastname </div>
<div>
<input type="text" name="lastname" id="lastname" class="input-control" />
</div>
<div style="float:left">
<button type="submit" name="btn-submit" id="btn-submit">Submit</button>
</div>
<div id="error_message" class="ajax_response" style="float:left"></div>
<div id="success_message" class="ajax_response" style="float:left"></div>
</form>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#frmDemo").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var comment = $("#comment").val();
var lastname = $("#lastname").val();
if(name == "" || comment == "" || lastname == "" ) {
$("#error_message").show().html("All Fields are Required");
} else {
$("#error_message").html("").hide();
$.ajax({
type: "POST",
url: "form4.php",
data: { name:name, comment:comment, lastname:lastname }, // *** Modify this
success: function(data){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
}
})
</script>
</body>
</html>
and the php code is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['lastname'])) { // **Change this
$name = $_POST['name'];
$comment = $_POST['comment'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}' '{$lastname}')";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Either Name or Comment field not set"; // **Change this
}
$conn->close();
?>
I suppose that the problem has to do with some error in my php code in the if isset POST method, because it can handle 2 variables but no more...
You muss a comma in SQL query - but, if You setup default values in database, it will not throw an error.
I think, the problem is in JSON object in 'data' field in AJAX options.
Try to change syntax:
$.ajax({
type: "POST",
url: "form4.php",
data: "name="+name+"&comment="+comment+"&lastname="+lastname,
success: function(data){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
You have syntax in your query, you forgot about comma:
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}' '{$lastname}')";
between '{$comment}' '{$lastname}'.
Put it there as follows:
{$comment}', '{$lastname}
so your code should look as follows:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['lastname'])) { // **Change this
$name = $_POST['name'];
$comment = $_POST['comment'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}', '{$lastname}')"; // here the problem occurs
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Either Name or Comment field not set"; // **Change this
}
$conn->close();
?>
In error you can look inside your query:
Error: INSERT INTO step4 (name, comment, lastname) VALUES ('aths',
'as' 'asa') Column count doesn't match value count at row 1
which says your query doesn't have comma between values as and asa
I am unable to connect insert the date into sql server using angularjs & php.
I want to know how to insert data in sql and fetch the data from db.
<body>
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<input type="button" value="submit" ng-click="insertdata()"/> <br/>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
var app = angular.module('myapp',[]);
app.controller('empcontroller', function($scope, $http){
$scope.insertdata=function(){
$http.post("insert.php",{'emp_no':$scope.emp_no,'first_name':$scope.first_name,'last_name':$scope.last_name,'dept_name':$scope.dept_name})
.success(function(data,status,headers,config){
console.log("data insert succesfully");
});
}
});
</script>
</body>
PHP CODE:
$data = json_decode(file_get_contents("php://input"));
$empno = mysql_real_escape_string($data->emp_no);
$fname = mysql_real_escape_string($data->first_name);
$lname = mysql_real_escape_string($data->last_name);
$dept = mysql_real_escape_string($data->dept_name);
$con = mysql_connect("localhost", "root", "root");
mysql_select_db("company", $con);
mysql_query("INSERT INTO employee('emp_no', 'first_name', 'last_name', 'dept_name')VALUES('".$empno."','".$fname."','".$lname."','".$dept."')");
Here You go Try this
HTML
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<button ng-click="postData()">Submit</button><br>
</form>
</div>
CONTROLLER:
app.controller('empcontroller', function ($scope, $http) {
/*
* This method will be called on click event of button.
*/
$scope.postData = function () {
var request = $http({
method: "post",
url: window.location.href + "insert.php",
data: {
emp_no: $scope.emp_no,
first_name: $scope.first_name,
last_name: $scope.last_name,
dept_name: $scope.dept_name,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
});
PHP CODE:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$emp_no = $request->emp_no;
$first_name = $request->first_name;
$last_name = $request->last_name;
$dept_name = $request->dept_name;
$servername = "localhost";
$username = "root";
$password = "root"; //Your User Password
$dbname = "myDB"; //Your Database Name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO employee (emp_no, first_name, last_name, dept_name)
VALUES ($emp_no, $first_name, $last_name , $dept_name)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Three problems with your code:
When executing $scope functions with ng-click, best practice is to pass in the variables as you use them.
Since your PHP controller is expecting JSON, you should form a JSON object and indicate it in the headers.
.success() is being deprecated. You should use the promise .then() instead.
HTML:
<!-- need to pass model in the ng-click function -->
<input type="button" value="submit" ng-click="insertdata(emp_no, first_name, last_name, dept_name)"/>
Controller:
$scope.insertata = function(empNo, firstName, lastName, deptName) {
//make json payload object
var payload = {
emp_no: empNo,
first_name: firstName,
last_name: lastName,
dept_name: deptName
};
//pass to API
$http.post('insert.php', payload, {
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function(data, status, headers, config) {
//success
}, function(data, status, headers, config) {
//an error occurred
});
}
well, using the code of KKKKKKKK now you need a php code.
To retrieve information from a json file posted using post to php you should do something like this:
$json = file_get_contents('php://input');
$obj = json_decode($json); // this will retrieve the json.
And now manipulate as you want.
I want to display data retrieved from the table in the same page. I know if i use ajax, work becomes easier. But how do i do it? I don't know anything about ajax. My current program is combined with html and php. The program is below. All i want is, when i click the button, the requested action and the data must be displayed in the same page.
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{
echo '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>
</table>';
//$row[0],$row[1],$row[2]';
}
mysqli_free_result($result);
}}}
$conn->close();
?>
<h2>SELECT THE OPERATION YOU WANT TO PERFORM<h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Id: <input type="text" name="Id" />
Name: <Input type="text" name="Name" />
BloodGroup: <input type="text" name="BloodGroup" /><br /><br />
<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
<input type="submit" name="retrieve" value="retrieve" />
</form>
</body>
</html>
$.ajax({
method: "POST",
url: "{php file url}",
data: { name: "John", location: "Boston" } // data list need to sent
})
.done(function( msg ) {
$("#div1").html(result); //#div1 is container element where you want to show output of ajax
});
For more details refer
http://api.jquery.com/jquery.ajax/
Just start learning jquery and jquery ajax
http://api.jquery.com/jquery.ajax/
you will find something like this:
$.ajax({
type: "POST",
url: '', //write your php file url from where you want to get data
data:{}, //to post data like data:{customerName:'xyz'},
success: function(res){ //data returned from your php file
console.log(res); //use data as per your need
}
});
I've had my code working some time ago. Actually, I've asked for test and it still works in other pcs.
I formated mine, installed eclipse, wamp AND easyphp for double check and all the stuff, and now I have this issue.
It's a simple insert, a HTML with 2 textboxes, the table exists and it works directly by the MySQL workbench.
When I run the script via Browser, I wrote some echoes along the code, and it starts the ajax, calls the insert.php, and inside it it echoes before the require_once config.php
After that, no response at all.
I have put alert status and thown error in the error section in the ajax call, but nothing at all.
What may have happened to it ?
I use Windows, and I suspect of something deeper, but it can be an obvious mistake, I just have no idea where to search, as it works in other computers.
Here goes the code:
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CRUD</title>
</head>
<body>
<form id="myForm" method="post" action="" >
Nome:
<input type="text" name="nome" required />
<br/>
Tipo:
<input type="text" name="tipo" required />
<br/>
<input type="submit" name="submit" value="save" id="sub"/>
</form>
<script src="script/jquery-2.1.0.js" type="text/javascript"></script>
<script src="script/ajaxInclude.js" type="text/javascript"></script>
</body>
</html>
ajax call
$(document).ready(function(){
$('#myForm').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "DAO/insert.php",
type: "POST",
data: data,
dataType: "html",
success: function( data )
{
alert( data );
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
config.php
<?php
echo "DENTRO DO CONFIG";
define('HOST', 'localhost');
define('DB_NAME', 'wms');
define('PORT', '3306');
define('USER', 'root');
define('PASS', '');
$dsn = 'mysql:host='.HOST.'; port='.PORT.'; dbname='.DB_NAME;
try {
$bd = new PDO($dsn, USER, PASS);
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Houve algum erro no Banco de Dados';
}
?>
insert.php
<?php
echo "FORA DO INSERT";
require_once('config.php');
if(isset($_POST['submit'])){
echo "DENTRO DO INSERT, SUBMIT POSTED";
$nome = $_POST['nome'];
$tipo = $_POST['tipo'];
$sql = 'INSERT INTO produto(id, nome, tipo, criado_em) ';
$sql .= ' VALUES (NULL, :nome, :tipo, NOW())';
try {
echo "DENTRO DO TRY";
$query = $bd->prepare($sql);
$query->bindValue(':nome', $nome, PDO::PARAM_STR);
$query->bindValue(':tipo', $tipo, PDO::PARAM_STR);
if($query->execute()){
echo "Dados inseridos com sucesso";
}else{
echo "Falha na insercao de dados";
}
} catch (Exception $e) {
echo $e->getMessage();
}
die();
}
?>
On insert.php, change:
if(isset($_POST['submit'])){
for
if(isset($_POST['nome']) && isset($_POST['tipo'])){