article

Friday, February 11, 2022

Vue.js PHP Mysql Submit Form Data with Alert Message

Vue.js PHP Mysql Submit Form Data with Alert Message

vuejs
https://v2.vuejs.org/v2/guide/installation.html
CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

Axios 
CDN : https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js PHP Mysql Submit Form Data with Alert Message</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="alert">

	<div class="topcorner alert_danger" v-if="isError">
		<span class="closebutton" @click="clearMessage();">×</span>
		<span class="glyphicon glyphicon-alert"></span> {{ responseMessage }}
	</div>
	<div class="topcorner alert_success" v-if="isSuccess">
		<span class="closebutton" @click="clearMessage();">×</span>
		<span class="glyphicon glyphicon-check-square-o"></span> {{ responseMessage }}
	</div>
	
	<div class="container">
		<h1 class="page-header text-center">Vue.js PHP Mysql Submit Form Data with Alert Message</h1>
		<div class="col-md-4">
			<div class="form-group">
				<label>First Name:</label>
				<input type="text" class="form-control" v-model="newMember.firstname" v-on:keyup="keymonitor">
			</div>
			<div class="form-group">
				<label>Last Name:</label>
				<input type="text" class="form-control" v-model="newMember.lastname" v-on:keyup="keymonitor">
			</div>
			<button class="btn btn-primary" @click="insertMember();"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button> <button class="btn btn-danger" @click="clearForm();"><span class="glyphicon glyphicon-refresh"></span> Clear</button>
		</div>
		<div class="col-md-8">
			<table class="table table-bordered table-striped">
				<thead>
					<th>Member ID</th>
					<th>First Name</th>
					<th>Last Name</th>
				</thead>
				<tbody>
					<tr v-for="member in members">
						<td>{{ member.id }}</td>
						<td>{{ member.firstname }}</td>
						<td>{{ member.lastname }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="app.js"></script>
<style type="text/css">
		.topcorner{
			position:absolute;
			top:5px;
			right:5px;
		}
		.alert_danger {
		    padding: 15px;
		    background-color: #f44336;
		    color: white;
		}

		.alert_success {
		    padding: 15px;
		    background-color: #4CAF50;
		    color: white;
		}

		.closebutton {
		    margin-left: 15px;
		    color: white;
		    font-weight: bold;
		    float: right;
		    font-size: 22px;
		    line-height: 20px;
		    cursor: pointer;
		    transition: 0.3s;
		}

		.closebutton:hover {
		    color: black;
		}
</style>
</body>
</html>
app.js
//app.js
var app = new Vue({
	el: '#alert',
	data:{
		newMember: {firstname: '', lastname: ''},
		alertMessage: false,
		isSuccess: false,
		isError: false,
		responseMessage: "",
		members: []
	},

	mounted: function(){
		this.fetchMembers();
	},

	methods:{
		keymonitor: function(event) {
       		if(event.key == "Enter"){
         		app.insertMember();
        	}
       	},

       	fetchMembers: function(){
			axios.post('action.php')
				.then(function(response){
					app.members = response.data.members;
				});
       	},

		insertMember: function(){
			var memberForm = app.toFormData(app.newMember);
			axios.post('action.php?action=add', memberForm)
				.then(function(response){
					console.log(response);
					if(response.data.error){
						app.alertMessage = true;
						app.isError = true;
						app.isSuccess = false;
						app.responseMessage = response.data.message;
						setTimeout(function(){
							app.clearMessage();
						},3000);
					}
					else{
						app.isSuccess = true;
						app.isError = false;
						app.alertMessage = true;
						app.responseMessage = response.data.message;
						app.newMember = {firstname: '', lastname:''};
						app.fetchMembers();
						setTimeout(function(){
							app.clearMessage();
						},3000);
					}
				});
		},

		toFormData: function(obj){
			var form_data = new FormData();
			for(var key in obj){
				form_data.append(key, obj[key]);
			}
			return form_data;
		},

		clearMessage: function(){
			app.isError = false;
			app.isSuccess = false;
		},

		clearForm: function(){
			app.newMember=app.newMember = {firstname: '', lastname:''};
		}



	}
});
action.php
//action.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$out = array('error' => false);

$action="show";

if(isset($_GET['action'])){
	$action=$_GET['action'];
}

if($action=='show'){
	$sql = "select * from members";
	$query = $conn->query($sql);
	$members = array();

	while($row = $query->fetch_array()){
		array_push($members, $row);
	}

	$out['members'] = $members;
}

if($action=='add'){
	$firstname=$_POST['firstname'];
	$lastname=$_POST['lastname'];

	if($firstname==''){
		$out['error']=true;
		$out['message']='Add Member Failed. Username Empty.';
	}
	elseif($lastname==''){
		$out['error']=true;
		$out['message']='Add Member Failed. lastname Empty.';
	}
	else{
		$sql="insert into members (	firstname, lastname) values ('$firstname', '$lastname')";
		$query=$conn->query($sql);

		if($query){
			$out['message']='Member Successfully Added';
		}
		else{
			$out['error']=true;
			$out['message']='Error in Adding Occured';
		}
		
	}
}




$conn->close();

header("Content-type: application/json");
echo json_encode($out);
die();

?>

Related Post