How to post data using ajax in PHP
form.php
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#abb8c3″ theme=”dark” language=”html” wrapped=”no”]
<html>
<head>
<title>Codelizar</title>
<script src=”https://code.jquery.com/jquery-3.4.1.js”></script>
<script type=”text/javascript”>
$(document).ready(function(){
$(‘#send_data’).click(function(){
var get_username = $(‘#cl_username’).val();
var get_pass = $(‘#cl_pass’).val();
$.ajax({
type:’POST’,
url:’welcome.php’,
data:’user_val=’+get_username+’&user_pass=’+get_pass, // send data using ajax
success: function (get_response_data) {
}
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td><label>Username</label></td>
<td><input type=”text” id=”cl_username”></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type=”text” id=”cl_pass”></td>
</tr>
<tr>
<td></td>
<td><button id=”send_data”>send data using ajax</button></td>
</tr>
</table>
</body>
</html>
[/dm_code_snippet]
welcome.php
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no”]
<?php
$dbhost = ‘localhost’;
$dbuser = ‘root’;
$dbpass = ”;
$db = ‘student_db’;
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db);
if(! $conn ) {
die(‘Could not connect: ‘ . mysql_error());
}else{
$user = $_REQUEST[‘user_val’];
$pass = $_REQUEST[‘user_pass’];
$qry = “INSERT INTO `student_tbl`(`user`, `pass`) VALUES (‘$user’,’$pass’)”;
mysqli_query($conn,$qry);
}
?>
[/dm_code_snippet]