Passing data to php script using Ajax –
here we will use j query to get data from inputs
and then create an Ajax method to pass data to php script (asynchronous request).
Ajax is sued to asynchronously send data to a script.
By asynchronous we mean that the user can continue doing some other tasks at the front end till the script is being executed. User need not wait for response.
with create two file like this
1.
first.php
-------------------------------------------
<html>
<head>
<title>Passing data to php script using Ajax -steps</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function submit_form() {
var data1=$("#uname").val();
var data2=$("#pwd").val();
var dataTosend='user='+data1+'&pwd='+data2;
$.ajax({
url: 'add_vac_to_healthcheck.php',
type: 'POST',
data:dataTosend,
async: true,
success: function (data) {
alert(data)
},
});
}
</script>
</head>
<body>
<form method="post">
<input type="text" placeholder="username" id="uname" />
<input type="password" placeholder="passowrd" id="pwd" />
<button type="button" onclick="submit_form();">Submit</button>
</form>
</body>
</html>
-----------------------------------------
The type attribute is set to button, because we are going to send data using a function in an asynchronous way. Setting type=”submit” will cause synchronous transfer of data and also page reloading or re-direction.
then second file is
2.
add_vac_to_healthcheck.php
-----------------------------------------
<?php
$user=$_POST['user'];
$pwd=$_POST['pwd'];
// now this data can be used for any function.
//One can even add this to database.
//We will just echo the data. //echo "username=".$user."password=".$pwd;
//Save into DB
$h='localhost';
$u='root';
$p='testtest';
$d='epiapp_db';
$link = mysql_connect($h, $u, $p); // step1-connect
if (!$link) { die('Could not connect: ' . mysql_error());}
$db_selected = mysql_select_db($d, $link); // step2-select DB
if (!$db_selected) { die ('Can\'t use $d : ' . mysql_error());}
$mq="INSERT INTO vac_table(vacname1,vaclot1) VALUES('$user','$pwd')"; $result = mysql_query($mq);
if (!$result) { die('Invalid query: ' . mysql_error());
}else{
echo "Insert Success...";
}
?>
----------------------------------------
Ref : https://www.quora.com/How-do-I-pass-a-value-to-a-PHP-script-using-AJAX