update database from html form using ajax - php

I would like some help with ajax. I would like to update a php file which will update a database. I have a form which send the selected check box to a php file which then updates the data base. I would like to do this with ajax but I am struggling with this. I know how to update <div> Html elements by ajax but cannot work this out.
HTML script
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
var boiler = document.getElementByName("boiler").value;
var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function() {
alert("ok");
}
});
}
</script>
</body>
</html>
PHP updateDB.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="14Odiham"; // Mysql password
$db_name="heating"; // Database name
$tbl_name = "test";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
// Insert data into mysql
$sql = "UPDATE $tbl_name SET boiler=$boiler WHERE id=1";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
<?php
//close connection
mysql_close();
header ('location: /ajax.php');
?>
I would like this to update with out refreshing the page.

I just want some suggestion and first your html page code should like-
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form" id="form_id">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
// it's like cumbersome while form becoming larger so comment following three lines
// var boiler = document.getElementByName("boiler").value;
// var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
//var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
// instead of type use method
method: "POST",
url: "updateDB.php",
// instead dataString i just serialize the form like below this serialize function bind all data into a string so no need to worry about url endcoding
data: $('#form_id').serialize(),
cache: false,
success: function(responseText) {
// you can see the result here
console.log(responseText)
alert("ok");
}
});
}
</script>
</body>
</html>
Now i am turning to php code:
You used two line of code right in php
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
$_GET is used in get method and $_POST for post method, thus you are using post method in ajax and above line of code should be like
$boiler = (isset($_POST['boiler'])) ? 1 : 0;
$niamh = (isset($_POST['niamh'])) ? 1 : 0;

Update:
As well as fixing the dataString, stop the form from being submitted so that your function is used:
<form name="form" onsubmit="return false;">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
The ajax call should handle returned data from updateDb.php.
Update the php file to send data back to the server, revert to $_POST instead of $_GET and remove the header call at the bottom:
if($result){
$data['success'=>true, 'result'=>$result];
} else {
$data['success'=>false];
}
echo json_encode($data);
// die(); // nothing needed after that
Update the ajax call to handle the response and fix your dataString with '&' between params (This is why you are not getting your params properly).
var dataString = 'boiler=' + boiler + '&niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function(data) {
var json = $.parseJSON(data);
if(json.success){
// update the page elements and do something with data.results
var results = data.results;
} else {
// alert("some error message")'
}
}
});
}

document.getElementByName not a javascript function, try document.getElementById() instead
You can do this
<form name="form" onsubmit="myfunction()">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<input type="submit" value="Update"/>
</form>
Javascript:
function myFunction() {
var boiler = document.getElementById("boiler").value;
var niamh = document.getElementById("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
// i dont practice using url string in ajax data as it can be compromised with a quote (') string, instead i am using json
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: {
boiler: boiler,
niamh: niamh
},
cache: false,
}).done(function() {
alert('success');
}); // i do this because some jquery versions will deprecate the use of success callback
}
And you are getting to a post so change the $_GET in you php file to $_POST

Related

jquery Ajax not saving to mysql

I have a php file that has jquery ajax on it to submit a form and save its contents into a mysql without doing a page refresh.
My issue is if I load the file that the ajax call does the contents are saved into the database however if I try to use the form nothing gets saved to the database even though I get a success message.
Here is my code
The HTML file
<div id='backinstock-form'>
<form>
<input id='instockemailadr'>
<input id='instockpid' value='5' type='hidden'>
<input name='submit' class='submitbackinstock' type='button' value='Submit'>
</form>
<span class='error' style='display:none'> Please Enter A Valid Email</span>
<span class='success' style='display:none'> Email Submitted Success</span>
</div>
require(['jquery'], function($)
{
$(".submitbackinstock").click(function()
{
var instockemailadr = $("#instockemailadr").val();
var instockpid = $("#instockpid").val();
var dataString = 'usereaddr='+ instockemailadr + '&sku=' + instockpid;
if(instockemailadr =='' || instockpid =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//console.log(dataString);
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
$.ajax({
type: "POST",
url: "<?php echo $block->getBaseUrl(); ?>/pub/media/theme_customization/backin-stock-email-code/backinstock_process_email.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
The PHP File
<?php
// MySQL portion
$conn = mysqli_connect("localhost", "root", "root");
mysqli_select_db($conn,"multisitedb");
$usereaddr = mysqli_real_escape_string($conn, $_POST['usereaddr']);
$stockproductid = mysqli_real_escape_string($conn, $_POST['sku']);
$created_on = date('Y-m-d h:i:s');
$result = mysqli_query($conn, "INSERT INTO multisitedb.backinstock_email_addresses(email_addr, product_sku, created_on)
VALUES ('$usereaddr','$stockproductid','$created_on')");
if($result) {
echo $result; // or whatever you want
} else {
echo "Something went wrong.";
}
?>
First, you didn't specify a Database in your php script. The format is mysqli_connect(host, username, password, database);
Secondly, your ajax code seems wrong. You're making a post request. The data should be an instance of formData(). You can modify this way:
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
//...
data: dataString,
success: function(){
Also, your PHP script is not doing security checks. You need to validate user inputs as well as use prepared statements to prevent against SQL injection attack.

Insert into mysql database from html form without redirecting [duplicate]

This question already has answers here:
Form submit with AJAX passing form data to PHP without page refresh [duplicate]
(10 answers)
Closed 7 years ago.
I'm working with a mysql database and a webpage that i'm trying to make comunicate with it.
Here's my situation:
i have the listmat.php file that echoes all the records in the table Material and it works.
Now i manage to show the output of the listmat.php file inside a specific div witouth refreshing the hole page with the following code:
<script>
$(document).ready(function(){
$("#matbutton").click(function(){
$("#matins").load('listmat.php');
});
});
</script>
Where matbutton is the id of the submit button in the form and matins is the id of the div where i show the output of listmat.php
Here's my form:
<form id="formmatins" method="post" action="listmat.php">
<p>Name:<input type="text" Name="Mat" id="Material"></p>
<center><input type="submit" value="Insert/Remove" id="matbutton"></center>`
</form>
What i'd like to do is to use the matbutton to also insert the value of the textbox in the table that listmat.php echoes all his records. So that everytime i click a record is inserted and in the div is shown the new table
The problem is that if i insert the button in the form with the method post , by clicking it redirects to the output changing page but if i put it out the echoes work but i cannot pass obviously the value of the textbox to the listmat.php file to be the argument of the insert because the button is not interested by the method post.
I looked around and looks like the solution is using some articulated structure in jquery/ajax but i really don't know how to fix. Any help would be really appreciated
UPDATE
<script>
$(function () {
$('#formmatins').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function () {
$("#matins").load('listmat.php');
alert('form was submitted');
}
});
});
});
</script>
And again it switch page
UPDATE
<?php
$user = "**";
$pass = "**";
$db = "**";
$host = "localhost";
$con = mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$m = $_POST['Mat']; //the text box in the form
$ins = $con->query("INSERT INTO mattemp (Material) VALUES ('$m')");
$query = $con->query("SELECT Material FROM mattemp");
while ($row = $query->fetch_assoc()) {
echo $row['Material']."<br>";
}
?>
It print the table updated everytime but still in a new page...what am i doing wrong?
SOLVED BY MYSELF
Thanks to all have tried to help me. The solution that gave me -1 on the post was not correct and here the solution of my code , in case someone would encounter the same problem
`<script>
$(function () {
$('#matbutton').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function (data) {
$("#matins").load('listmat.php');}
});
});
});
</script>`
You'll need $.ajax
For exemple :
$.ajax({
url: "your_url.php",
type: "POST",
data: $('#formmatins').serialize(),
success: function(response){
// Do something, or not...
}
})

Sending form ID to AJAX on button click

I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.

ajax and php to enter multiple forms input to database

I have a php generated form with multiple input fields the number of which is determined by user select. I would like to use an ajax function to enter all the data to database. The problem is that I am new to ajax and not sure ho to go about it. The ajax javascript function below is a sample of what I would like to achieve and I know it is not correct. Can someone point me in the right direction. I have looked around and from what I see, Json may be a solution but I know nothing about it and reading up on it I still don't get it.
sample ajax:
function MyFunction(){
var i = 1;
var x = $('#num_to_enter').val();
while (i <= x){
var name = $('#fname[i]').val();
var lname = $('#lname[i]').val();
var email = $('#Email[i]').val();
i++;
}
$('#SuccessDiv').html('Entering Info.<img src="images/processing.gif" />');
$.ajax({url : 'process.php',
type:"POST",
while (i <= x){
data: "fname[i]=" + name[i] + "&lname[i]=" + lname[i] + "&email[i]=" + email[i],
i++;
}
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
}
A sample of form :
<?php
echo "<form method='post'>";
$i=1;
while($i <= $num_to_enter){
$form_output .= "First Name:
<input id='fname' type='text' name='fname[$i]'><br />
Last Name:
<input id='lname' type='text' name='lname[$i]'><br />
Email:
<input id='Email' type='text' name='Email[$i]'><br />
$i++;
}
echo"<input type='button' value='SUBMIT' onClick='MyFunction()'></form>";
?>
Then DB MySQL Sample
<?php
while ($i <= $x){
$x = $_POST['num_to_enter'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['email[$i]'];
$sql = "INSERT INTO `mytable`
(`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');";
$i++;
}
?>
Here is a simple demo of AJAX:
HTML
<form method="POST" action="process.php" id="my_form">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[custom1]">
<input type="text" name="firstname[custom2]">
<br><br>
<input type="submit" value="Submit">
</form>
jQuery
// listen for user to SUBMIT the form
$(document).on('submit', '#my_form', function(e){
// do not allow native browser submit process to proceed
e.preventDefault();
// AJAX yay!
$.ajax({
url: $(this).attr('action') // <- find process.php from action attribute
,async: true // <- don't hold things up
,cache: false // <- don't let cache issues haunt you
,type: $(this).attr('method') // <- find POST from method attribute
,data: $(this).serialize() // <- create the object to be POSTed to process.php
,dataType: 'json' // <- we expect JSON from the PHP file
,success: function(data){
// Server responded with a 200 code
// data is a JSON object so treat it as such
// un-comment below for debuggin goodness
// console.log(data);
if(data.success == 'yes'){
alert('yay!');
}
else{
alert('insert failed!');
}
}
,error: function(){
// There was an error such as the server returning a 404 or 500
// or maybe the URL is not reachable
}
,complete: function(){
// Always perform this action after success() and error()
// have been called
}
});
});
PHP process.php
<?php
/**************************************************/
/* Uncommenting in here will break the AJAX call */
/* Don't use AJAX and just submit the form normally to see this in action */
// see all your POST data
// echo '<pre>'.print_r($_POST, true).'</pre>';
// see the first names only
// echo $_POST['firstname'][0];
// echo $_POST['firstname'][1];
// echo $_POST['firstname'][2];
// echo $_POST['firstname']['custom1'];
// echo $_POST['firstname']['custom2'];
/**************************************************/
// some logic for sql insert, you can do this part
if($sql_logic == 'success'){
// give JSON back to AJAX call
echo json_encode(array('success'=>'yes'));
}
else{
// give JSON back to AJAX call
echo json_encode(array('success'=>'no'));
}
?>
var postdata={};
postdata['num']=x;
while (i <= x){
postdata['fname'+i]= name[i];
postdata['lname'+i]= lname[i];
postdata['email'+i]= email[i];
i++;
}
$.ajax({url : 'process.php',
type:"POST",
data:postdata,
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
PHP
$num=$_POST['num'];
for($i=1;i<=$num;i++)
{
echo $_POST['fname'.$i];
echo $_POST['lname'.$i];
echo $_POST['email'.$i];
}

Show DIV with AJAX in PHP After Saving Data to Mysql

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

Categories