Insert Data Through Ajax into MySQL Database

Insert data into mysql database using ajax in php

<script>
$("#FORM_ID").submit(function() {
var name= $("#name").val();
var password= $("#password").val();

$.ajax({
type: "POST",
url: "insert.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});

});
</script>

and also either load

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

before your script tag or use

 <script>
$(document).ready(function(){
$("#FORM_ID").submit(function() {
var name= $("#name").val();
var password= $("#password").val();

$.ajax({
type: "POST",
url: "insert.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});

});
});
</script>

Insert data into mysql database using ajax in php multiform

In addition to Bakayaro's answer, if all your forms got the same fields, you can optimize your code to use only one javascript function and one PHP insert script.

Factorise your code ! Rembember one thing : DRY (Don't Repeat Yourself)

HTML

  • Add a click listener on each .send button instead of using onclick() on them
  • Add specific ID on each different form, with kitchen ID
  • Add data to .send button with related form's kitchen ID

Example for kitchen 1A:

<!-- Add specific ID with kitchen ID -->
<form action="" id="kitchen1a" method="" name="1a" novalidate="novalidate">
...
<!-- Add data to each .send button with related form's kitchen and remove onclick() -->
<!-- data-kitchen="1a" -->
<button class = "send" id = "insert-data1a" name = "insert-data1a" data-kitchen="1a" type = "button">Insert Data</button>

Don't use same ID on different HTML elements, as your a and form tag.

Javascript

  • Use click listener
  • Get active form's data from each field's name

Working example based on your code:

$('.send').on('click', function(e) {

var kitchen = $(this).data('kitchen');
var form = $('#kitchen' + kitchen);

var data = {
door: form.find('[name="door"]').val(),
skilt: form.find('[name="skilt"]').val(),
lys: form.find('[name="lys"]').val(),
b_t: form.find('[name="b_t"]').val(),
b_s: form.find('[name="b_s"]').val(),
dato: form.find('[name="dato"]').val(),
// add active kitchen in your POST data
kitchen: kitchen,
};

// AJAX code to send data to php file.
$.ajax({
type: "POST",
// use same PHP script for each forms
url: "insert.php",
data: data,
dataType: "JSON",
success: function (data) {
// use kitchen's specific message tag
$("#message" + kitchen).html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
// alert(err);
console.log(err);
}
});
});

PHP file

Use one single PHP script for each form and generate table name in your SQL query from given kitchen value.

Working example based on your code:

$kitchen = $_POST['kitchen'];

// if your kitchens are all formatted like this : 1a, 2c, 14a, ...
preg_match('/(\d)+([a-z])/', $kitchen, $matches);

$stmt = $DBcon->prepare("INSERT INTO " . $matches[1] . '_' . $matches[2] . "(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");

Generated query for your 1a form:

INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato) VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)

how to insert data to mysql database with Jquery ajax and php?

When you submit via ajax on a click of the submit button.... that condition is always true.

Checking if $_POST['submit'] is set in the PHP will always result in true because if it is not true the ajax never gets processed.

So... remove the if submit condition in the PHP and handle error notification in the ajax call.

Also, as pointed out by @NiettheDarkAbsol in comments, it's a good idea to add e.preventDefault() to the jquery as well to stop the submit button submitting the form as it normally would and allow the jquery to handle the submit (via ajax).

Insert data through ajax into mysql database

Try this:

  $(document).on('click','#save',function(e) {
var data = $("#form-search").serialize();
$.ajax({
data: data,
type: "post",
url: "insertmail.php",
success: function(data){
alert("Data Save: " + data);
}
});
});

and in insertmail.php:

<?php 
if(isset($_REQUEST))
{
mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);

$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
}
?>

Don't use mysql_ it's deprecated.

another method:

Actually if your problem is null value inserted into the database then try this and here no need of ajax.

<?php
if($_POST['email']!="")
{
mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
//echo "You have been successfully subscribed.";
setcookie("msg","You have been successfully subscribed.",time()+5,"/");
header("location:yourphppage.php");
}
if(!$sql)
die(mysql_error());
mysql_close();
}
?>
<?php if(isset($_COOKIE['msg'])){?>
<span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span>
<?php }?>
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<span><span class="style2">Enter you email here</span>:</span>
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit"/>
</form>

Using JQuery AJAX and php to fetch data to a mysql database

I think you should use PDO, to connect to the database instead of the old driver, which PHP no longer supports. with PDO you can use prepared statements to prevent sql injections

PDO tutorial

filter_var() Constants

dbh.php


$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = 'db';

try {

$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
exit($e->getMessage());
}

?>

serve.php

<?php

include("dbh.php");
if (isset($_POST['done'])) {

$q_no = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$total_no = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);

try {

$stmt = $db->prepare("INSERT INTO variables(id, names) VALUES(?, ?)");
$stmt->execute(array($q_no, $total_no));

echo json_encode(["message" => "success"]); // sends success response to front-end

} catch (\Exception $e) {
echo json_encode(["message" => $e->getMessage() ]); // sends error response to front-end
}

}
?>

in your ajax check if the data was inserted or not.

$("#q_answer1").click(function() {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();

$.ajax({
url: "file.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no

},
success: function(data) {

const respose = JSON.parse(data);

if (respose.message === 'success') { // data was inserted

$("#q_no").val('');
$("#total_no").val('');

}else {
alert(respose.message); // some error has occured
}
}
});
});

Ajax success but I can't insert data into MySQL database

Check your code, don't use ' for column or for table names, use " `` " it, like below.
P.S I don't understand why you are using {braces} )

mysqli_query($link, "INSERT INTO `dogcare` (`accion`, `flagtime`,`lunchtime`) VALUES ('{$accion}', '{$flagtime}','{$lunchtime}')");

Inserting data into database using AJAX-php using onclick

Actually you are only checking for post variable test is present or not . You are not checking for your successful database query execution . in your current code check after $query

if(!$query){ 
echo "Form Submitted succesfully"
} else {
die('Invalid query: ' . mysql_error()); // show the error
}

mysql is deprecated functions so i am using mysqli , it is also better for you to use this. Never trust user's input so i am also using prepare statement. You should always looking for updated videos & articles.

$connection = mysqli_connect("localhost", "root", "","event"); // Establishing Connection with Server..

if (isset($_POST['team'])) {
$query = "insert into workshop values (?, ?, ?,?,?,?,?)"; //Never trust user's input so use prepare
$stmt = mysqli_prepare($connection ,$query) ;
mysqli_stmt_bind_param($stmt,'ssssssi',$team,$m1,$m2,$m3,$m4,$email,$number) ;
mysqli_stmt_execute($stmt);
if( mysqli_stmt_affected_rows($stmt) === 1 ) { //it will be int 1 if one row is inserted
echo "Form Submitted succesfully" ;
}else {
echo mysqli_error($connection)
}
}

mysqli_close($connection); // Connection Closed

some sources for future

How can I prevent SQL injection in PHP?

https://phpdelusions.net/pdo (it's about PDO but you will get idea.)

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php



Related Topics



Leave a reply



Submit