Vue.js Ajax Post Submitting AJAX Forms using PHP with MySQLi

Vue.js Ajax Post Submitting AJAX Forms using PHP with MySQLi

In this Post We Will Explain About is Vue.js Ajax Post Submitting AJAX Forms using PHP with MySQLi With Example and Demo.Welcome on Live24u.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to How to submit a form using Vue.js Ajax and PHP Example

In this post we will show you Best way to implement Form Submission Using Ajax, PHP and vuejs, hear for Vue.js AJAX Form Submission in PHP server-side validatate with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.




Vue.js Ajax Form Submit with PHP and MySQLi

index.html

This is the main HTML view of our Simple Web Application. In here, we have init Base declared all our simple my this Example(Vue.js directive to submit) dependencies and the HTML Elements that we have created.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vue.js Ajax form Submit Directive using PHP Demo - Live24u.com - How to submit a form using Vue.js Ajax and PHP</title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.min.css" />
	<link rel="stylesheet" href="1.1.3/sweetalert.min.css" />

  </head>
  <body>
    <div id="live24uApp"></div>
    <script src="live24u/dist/build.js"></script>
  </body>
</html>

main.js

This contains our simple custom main.js files Add Like as javascript, vuejs scripts

// Include vue and vue-resource routings
window.Vue = require('vue');
require('vue-resource');

//Simple PHP Ajax Form Validation using vuejs Example from scratch
window.swal = require('sweetalert');
window.$ = window.jQuery = require('jquery');

require('live24u/directives/jquery.ajax-submit');


import App from 'live24u/App.vue';

new Vue({
  el: '#live24uApp',
  http: {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  },
  render: h => h(App)
});

App.vue

vuejs simple HTML template source code availables

<template>
//Form Submission Using Ajax, PHP and vuejs
<div class="live24u container">
    <div id="live24uApp">
        <div class="live24u row">
            <div class="live24u col-sm-8 col-sm-offset-2">
                <div class="live24u card-packge">
                    <img class="site-logo" src="site-logo/assets/live24u.png">
                    <h2>Vue Directive for AJAX form Submit using PHP</h2>
                    <p>by <a href="http://www.live24u.com" target="_blank">Live24u.com</a></p>
						
                    <hr>
                    </img>
					<p>vuejs AJAX form submission with customized server field validation</p>
					<p>Vue submit form data,vue js submit form,vuejs form submit example,vue js ajax post,vue js serialize form,vue js ajax json,form submit using ajax in php,vue prevent form submit,vue ajax call</p>
                </div>
            </div>
        </div>

        <div class="live24u row">
            <div class="live24u col-sm-6">
                <form @success="mydbSqlsuccessQry" action="http://localhost:8000" method="post" v-ajax-submit>
                    <fieldset>
                     
                        <legend>
                           Vuejs Query Form
                        </legend>
                        <div class="lst form-group gst">
                            <label for="name">
                                User Name
                            </label>
                            <input class="gst form-control jdk" id="name" name="name" placeholder="Article Name" type="text">
                            </input>
                        </div>
                        
                        <div class="lst form-group gst">
                            <label for="email">
                                User Email
                            </label>
                            <input class="gst form-control jdk" id="email" name="email" placeholder="Article Email" type="text">
                            </input>
                        </div>
                        
                        <div class="lst form-group gst">
                            <label for="subject">
                                User Subject
                            </label>
                            <input class="gst form-control jdk" id="subject" name="subject" placeholder="Subject" type="text">
                            </input>
                        </div>
                        
                        <div class="lst form-group gst">
                            <label for="query">
                                User Query
                            </label>
                            <textarea class="gst form-control jdk" id="query" name="query" placeholder="Article Query">
                            </textarea>
                        </div>
                      
                        <div class="lst form-group gst">
                            <label for="submit">
                            </label>
                            <input class="btn btn-success" type="submit" value="Submit" />
                        </div>
                    </fieldset>
                </form>
            </div>

            <div class="col-sm-6">

                <div class="panel panel-primary">
                    <div class="live24u panel-body">
                        <div class="live24u upload-img" v-for="pagepost in articles">
                            <div class="upload-img-left upload-img-middle">
                                <a href="#">
                                    <img class="upload-img-object" width="62" :src="avatar(pagepost.article_name)" :alt="pagepost.article_name">
                                </a>
                            </div>
                            <div class="live24u upload-img-body">
                                <h5 class="live24u upload-img-heading">{{ pagepost.article_name }}</h5>
                                <p>{{ pagepost.pagepost }}</p>
                                <form @success="articleRemoved" action="http://localhost:8000" method="post" v-ajax-submit>
                                    <input type="hidden" name="_method" value="DELETE">
                                    <input type="submit" name="delete" value="X" class="live24u brn-remove btn btn-xs btn-danger" data-loading-text="Removing...">
                                </form>
                            </div>
                        </div>
                    
                        <div v-show="articles.length === 0" class="text-center">No Any Articles</div>
                    </div>
                </div>


                <form @success="insertArticle" action="http://localhost:8000" method="post" v-ajax-submit>
                    <fieldset>
                      
                        <legend>
                            Article Article
                        </legend>
                        
                        <div class="lst form-group gst">
                            <label for="pagepost">
                                Article
                            </label>
                            <textarea class="gst form-control jdk" id="pagepost" name="pagepost" placeholder="Article pagepost...">
                            </textarea>
                        </div>
                        
                        <div class="lst form-group gst">
                            <label for="article_name">
                                Name
                            </label>
                            <input class="gst form-control jdk" id="article_name" name="article_name" placeholder="Article Name" type="text">
                            </input>
                        </div>
                        <div class="lst form-group gst">
                            <label for="submit">
                            </label>
                            <input class="btn btn-success" type="submit" data-loading-text="Article reviwing..." value="Article" />
                        </div>
                    </fieldset>
                </form>
            </div>
        </div>
    </div>
    <!-- end #live24uApp vue el -->
</div>

</template>

<script>

export default {
    name: 'live24uApp',
    data() {
        return {
            articles: [{
                article_name: "Delete Request Demo",
                pagepost: "Are you sure, Remove this Data Recordes?"
            }]
        }
    },
    methods: {
        avatar(name) {
                return 'http://www.live24u.com/avatars/62/' + name.toString().toLowerCase().trim().replace(/[\s\W-]+/g, '-') + '@adorable.io.png'
            },

            insertArticle(lresponse) {
                this.articles.push(lresponse.body);
            },

            articleRemoved() {
                this.articles.splice(0, 1);

                swal('Deleted', 'Article has been deleted.', 'info');
            },

            mydbSqlsuccessQry(lresponse) {
                swal('Submitted', 'Article query has been submitted.', 'success');
            }
    }
}

</script>

<style>


#live24uApp .card-packge {
    text-align: center;
    padding: 2em;
}

.card-packge h2 {
    color: #929292;
    text-shadow: 1px 1px 2px #ddd;
}

.card-packge h2 .badge {
    text-shadow: none;
}

.site-logo {
    width: 100px;
}

.upload-img {
    margin-bottom: 1em;
}

.brn-remove {
    position: absolute;
    top: 0;
    right: 15px;
}

</style>

vue-resource-submit.js

simple source code vue-resource-submit.js

Also Read :   Send and Receive WhatsApp messages using PHP Steps

 
function vueHandleValdiateErr(liveError) {
    if(liveError) {

    	deleteErrDesigned();

    	$.each(liveError, function(fieldName, e) {
            msgErr = e[0];

            decorateFields(fieldName, msgErr);
        });
    }
}

function decorateFields(inputName, lstMsgErr) {
        var myinpvlue = $('[name=' + inputName + ']');

        if( myinpvlue.length ) {
            var parentDiv = myinpvlue.closest('.lst form-group gst');
                parentDiv.addClass('has-error');

                var liveBlockhp = parentDiv.find('.help-block');
                if( liveBlockhp.length ) {
                	liveBlockhp.text(lstMsgErr);
                } else {
                	parentDiv.append($('<p />').addClass('help-block').text(lstMsgErr));
                }
        }

        myinpvlue[0].focus();
}

function deleteErrDesigned() {
	$('.lst form-group gst').each(function(){
		$(this).removeClass('has-error');
		$(this).find('.help-block').remove();
	});
}

function responseErrorHandler(dataRes) {
    if( dataRes.status === 401 ) {
        swal({
            title: dataRes.statusText,
            text: dataRes.body.mliveMessage,
            timer: 1500
        }, function(){
            window.location.reload();
        });
    }

    if( dataRes.status >= 400 ) {
        if( dataRes.status === 422 ) {

            vueHandleValdiateErr(dataRes.body);
        } else {
            var mliveMessage = dataRes.body.mliveMessage || 'Unable to process your request.';
            swal(dataRes.statusText, mliveMessage, 'error');
        }
    }
}


function responseSuccessHandler (dataRes) {
	console.log(dataRes);

	if ( dataRes.body.startsWith('http') ) {
		
    	window.location = dataRes.body;
    } else {

        window.location.reload();
    }
}

 
Vue.http.interceptors.push(function(request, next) {
	request.headers.set('Content-Type', 'application/x-www-form-urlencoded');
    next();
});


Vue.directive('ajax-submit', {
    bind: function (el, binding, vuemstnd) {
        var $el = $(el),
            livefrmSubmitBtn = $el.closest('form').find(':submit'),
            frmsubmit_txt = livefrmSubmitBtn.val(),
            loadingText = livefrmSubmitBtn.data('loading-text') || 'Submitting...',
            method = $el.find('input[name=_method]').val() || $el.prop('method'),
            url = $el.prop('action');

        $el.on('submit', function(e) {
            e.preventDefault();
            var myfrmdta = $el.serialize();
            livefrmSubmitBtn.val(loadingText);
            livefrmSubmitBtn.prop('disabled', true);
        	vuemstnd.context.$http({ url: url,  method: method,  body: myfrmdta })
        		.then( function(lresponse) {
	        		livefrmSubmitBtn.val(frmsubmit_txt);
	                livefrmSubmitBtn.prop('disabled', false);
	                deleteErrDesigned();
	                $el[0].reset();
	        		if( vuemstnd.data.on && vuemstnd.data.on.success ) {
	        			vuemstnd.data.on.success.fn.call(this, lresponse);
	        		} else {
	        			responseSuccessHandler(lresponse);
	        		}
	            }, function(liveError) {
	            	livefrmSubmitBtn.val(frmsubmit_txt);
	                livefrmSubmitBtn.prop('disabled', false);

	            	if( vuemstnd.data.on && vuemstnd.data.on.error ) {
						vuemstnd.data.on.error.fn.call(this, liveError);
	            	} else {
	            		responseErrorHandler(liveError);
	            	}
	            });
        	});
    }
});

jQuery.ajax-submit.js

simple source code availables in vuejs jQuery.ajax-submit.js

Also Read :   PHP Laravel 5.6 - Send Email using Mail configure SMTP

function vueHandleValdiateErr(liveError) {
    if(liveError) {
    	deleteErrDesigned();

    	$.each(liveError, function(fieldName, e) {
            msgErr = e[0];
            decorateFields(fieldName, msgErr);
        });
    }
}
function decorateFields(inputName, lstMsgErr) {
        var myinpvlue = $('[name=' + inputName + ']');

        if( myinpvlue.length ) {
            var parentDiv = myinpvlue.closest('.lst form-group gst');
                parentDiv.addClass('has-error');

                var liveBlockhp = parentDiv.find('.help-block');
                if( liveBlockhp.length ) {
                	liveBlockhp.text(lstMsgErr);
                } else {

                	parentDiv.append($('<p />').addClass('help-block').text(lstMsgErr));
                }
        }


        myinpvlue[0].focus();
}


function deleteErrDesigned() {
	$('.lst form-group gst').each(function(){
		$(this).removeClass('has-error');
		$(this).find('.help-block').remove();
	});
}

 
function responseErrorHandler(dataRes) {
    if( dataRes.status === 401 ) {
        swal({
            title: dataRes.statusText,
            text: dataRes.body.mliveMessage,
            timer: 1500
        }, function(){
            window.location.reload();
        });
    }

    if( dataRes.status >= 400 ) {
        if( dataRes.status === 422 ) {
            vueHandleValdiateErr(dataRes.body);
        } else {
            var mliveMessage = dataRes.body.mliveMessage || 'Unable to process your request.';
            swal(dataRes.statusText, mliveMessage, 'error');
        }
    }
}

function responseSuccessHandler (dataRes) {
	console.log(dataRes);
	if ( dataRes.body.startsWith('http') ) {

    	window.location = dataRes.body;
    } else {

        window.location.reload();
    }
}
Vue.directive('ajax-submit', {
    bind: function (el, binding, vuemstnd) {
        var $el = $(el),

            livefrmSubmitBtn = $el.closest('form').find(':submit'),

            frmsubmit_txt = livefrmSubmitBtn.val(),

            loadingText = livefrmSubmitBtn.data('loading-text') || 'form Loading...',

            method = $el.find('input[name=_method]').val() || $el.prop('method'),
            url = $el.prop('action');

        $el.on('submit', function(e) {
            e.preventDefault();

            var myfrmdta = $el.serialize();

            livefrmSubmitBtn.val(loadingText);
            livefrmSubmitBtn.prop('disabled', true);
            $.ajax({ url: url,  method: method,  data: myfrmdta })
                .done(function(lresponse) {
                    lresponse.body = lresponse;

                    deleteErrDesigned();

                
                    $el[0].reset();

                    
                    if( vuemstnd.data.on && vuemstnd.data.on.success ) {
                        vuemstnd.data.on.success.fn.call(this, lresponse);
                    } else {
                      
                        responseSuccessHandler(lresponse);
                    }
                }).fail( function(liveError) {
                    
                    liveError.body = liveError.responseJSON;

                   
                    if( vuemstnd.data.on && vuemstnd.data.on.error ) {
                        vuemstnd.data.on.error.fn.call(this, liveError);
                    } else {
                        
                        responseErrorHandler(liveError);
                    }
                }).always(function() {
                   
                    livefrmSubmitBtn.val(frmsubmit_txt);
                    livefrmSubmitBtn.prop('disabled', false);
                });
        });
    }
});

index.php

here data call to server-side api and fetch data using vuejs ajax request to server-side form submit.

Also Read :   Simple Random Passwords Generator using ASP. NET and C#

<?php

vuecors_bro_enable();


$getErroDebugs = [];

sleep(2);


foreach (array_reverse($_POST) as $liveinpt => $value) {
	if( empty($value) ) {
		addError($liveinpt, ucwords( str_replace('_', ' ', $liveinpt)) . " is required.");
	}

	if( $liveinpt == 'email' ) {
		if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
			addError($liveinpt, 'Invalid email address');
		}
	}
}

if( count($getErroDebugs) ) {
	return json_response($getErroDebugs, 422);	
} else {
	return json_response($_POST);
}


function json_response($data, $status_code = 200) {
	$data = is_string($data) ? [$data] : $data;

	http_response_code($status_code);
	header('Content-Type: application/json');
	die(json_encode($data));
}


function addError($field, $mliveMessage) {
	global $getErroDebugs;

	if( isset($getErroDebugs[$field]) ) {
		array_push($getErroDebugs[$field], $mliveMessage);
	} else {
		$getErroDebugs[$field] = [$mliveMessage];
	}
}


function vuecors_bro_enable() {

	if (isset($_SERVER['HTTP_ORIGIN'])) {
	    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
	    header('Access-Control-Allow-Credentials: true');
	    header('Access-Control-Max-Age: 86400');    
	}

//vuejs Form validation using AJAX with PHP server-side CORS
	if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

	    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
	        header("Access-Control-Allow-Methods: GET, PUT, PATCH, DELETE, POST, OPTIONS");         

	    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
	        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

	    exit(0);
	}
}

vuejs Form validation using AJAX with PHP

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example





Example

I hope you have Got What is Simple PHP Ajax Form Validation using vuejs Example from scratch And how it works.I would Like to have FeedBack From My Blog(live24u.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(live24u.com) Are Most Always Welcome.