Inserting into MySQL from PHP (Jquery/Ajax)

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>

Inserting into MySQL from PHP (jQuery/AJAX)

Hi here is just a quick example of how one might do it:

The HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Quick JQuery Ajax Request</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<!-- include the jquery lib -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
// fetch where we want to submit the form to
var url = $(formEl).attr('action');

// fetch the data for the form
var data = $(formEl).serializeArray();

// setup the ajax request
$.ajax({
url: url,
data: data,
dataType: 'json',
success: function() {
if(rsp.success) {
alert('form has been posted successfully');
}
}
});

// return false so the form does not actually
// submit to the page
return false;
}
</script>

</head>
<body>

<form method="post" action="process.php"
onSubmit="return ajaxSubmit(this);">
Value: <input type="text" name="my_value" />
<input type="submit" name="form_submit" value="Go" />
</form>

</body>
</html>

The process.php script:

<?php

function post($key) {
if (isset($_POST[$key]))
return $_POST[$key];
return false;
}

// setup the database connect
$cxn = mysql_connect('localhost', 'username_goes_here', 'password_goes_here');
if (!$cxn)
exit;
mysql_select_db('your_database_name', $cxn);

// check if we can get hold of the form field
if (!post('my_value'))
exit;

// let make sure we escape the data
$val = mysql_real_escape_string(post('my_value'), $cxn);

// lets setup our insert query
$sql = sprintf("INSERT INTO %s (column_name_goes_here) VALUES '%s';",
'table_name_goes_here',
$val
);

// lets run our query
$result = mysql_query($sql, $cxn);

// setup our response "object"
$resp = new stdClass();
$resp->success = false;
if($result) {
$resp->success = true;
}

print json_encode($resp);
?>

Please note that none of this has been tested. I hope it helps you thou.

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)

Insert records to mysql database with php using Ajax

I have Solved It ... How To Use Ajax and MYSQL...
PHP CODE

<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables

$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];

$query = "INSERT INTO `user_table`
(`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
// $retval=mysql_query($query,$conn);
if ($query_run)
{
echo 'It is working';
}

mysql_close($conn);
?>

HTML FILE....

<html>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</HEAD>
<body>
<div id="status_text">
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,

ID: <input type="text" id="ID" name="ID"><br><br>
NAME: <input type="text" id="NAME" name="NAME"><br><br>
PASSWORD: <input type="text" id= "PASSWORD"name="PASSWORD"><br><br>
CREDITS: <input type="text" Id= "CREDITS"name="CREDITS"><br><br>
Email_ID: <input type="text" id="EMAIL_ID"name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" id="CREATED_ON" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" id="MODIFIED_ON" name="MODIFIED_ON"><br><br>
<input type="submit" id="btn_submit" name="submit" value="Send"/>
</div>

<script>
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
} }
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
// make the postdata
// var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&CREDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
// alert(postData);
var myData={"ID":ID,"NAME":NAME,"PASSWORD":PASSWORD,"CREDITS":CREDITS,"EMAIL_ID":EMAIL_ID,"CREATED_ON":CREATED_ON,"MODIFIED_ON":MODIFIED_ON};
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "Form_Data.php",
type: "POST",
data : myData,
success: function(data,status,xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}

});
});
</script>

</body>
</div>
</html>

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

PHP jQuery HTML form insert to MySQL then stay on same page

If your main goal is to do this without changing or refreshing the page, you can use Ajax and jQuery like this:

    $(document).on('click', '#submit-my-form', function(){
var title = $("#title").val();
var claim = $("#claim").val();

jQuery.ajax({
type: "POST",
url: "http://your-site-url/db-insert.php",
dataType: 'json',
data: {title: title, claim: claim},
success: function(res) {
if (res)
{
alert('Hurray! Successfully done');
}
},
error: function(xhr) {
if (xhr)
{
alert('There was an error');
}
}
});
});

You can also add code to receive the insert status and process it in the return section of the Ajax code. Modify your html code by adding id tags to the inputs like this:

    <input type="text" name="title" id="title" required>

<textarea name="claim" id="claim" rows="5" cols="40"></textarea>

<input type="submit" name ="submit" id="submit-my-form" value="Submit"/>

That should do it.

Using ajax and php to insert data to MySQL

You mixed plain JS AJAX with jQuery's ajax wrapper.

Change your code to the following:

<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Simple Add</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type ="text/javascript" language="javascript">
var type = $('#type').val();
var vintner = $('#vintner').val();
var myData = {"type": type, "vintner": vintner};
$.ajax({
url: "bottleAdd.php",
type: "POST",
data: myData,
success: function(data) {
$("#responseDiv").html(data);
}
});
</script>
</head>

The rest is without a change.

That way you will use jQuery AJAX.

By the way, it is a good practice to place meta tags a the beginning of your head tag, because tag like the charset will cause the browser to start reading your page again from the beginning.



Related Topics



Leave a reply



Submit