-
Jeetendra Singh - 22 Aug, 2017
Stripe Subscriptions using php – Download Full Source Code
Hi Guys, In This blog article i am going to explain about STRIPE SUBSCRIPTIONS USING PHP and making available the source code also. by extending this code you can make a complete subscription management script. Here in this article about stripe subscriptions using php , i am going to create a pricing table where 3 type of plans are defined that plan will create on stripe if plan not exists on stripe panel and then create a customer and create a subscription in that customers reference. Note: the Stripe account is the pre requisite for you , where we will require stripe publishable key and secret key. and the stripe php library will be require for including in config file so dont worry about the stripe php library it will be available in full source code download of this article. Step 1: Create a config file and put following code : "sk_test_456456546hgjhg", "publishable_key" => "pk_test_567hjhgjghgjhg" );\Stripe\Stripe::setApiKey($stripe['secret_key']); ?> Note : you need to change the publishable key and secret key in this config file Step 2: Create a file index.php where pricing table and stripe client side code will come as following : .spacing { margin-top:20px; } .success { color: #fff; background-color: green; } .error { color: #fff; background-color: red; }</style> <meta name="viewport" content="width=device-width, initial-scale=1.0">* { box-sizing: border-box; } body { margin:50px 0; padding:0; text-align:center; }.content { margin:0 auto; text-align:left; padding:15px;}.columns { float: left; width: 33.3%; padding: 8px; }.price { list-style-type: none; border: 1px solid #eee; margin: 0; padding: 0; -webkit-transition: 0.3s; transition: 0.3s; }.price:hover { box-shadow: 0 8px 12px 0 rgba(0,0,0,0.2) }.price .header { background-color: #111; color: white; font-size: 25px; }.price li { border-bottom: 1px solid #eee; padding: 20px; text-align: center; }.price .grey { background-color: #eee; font-size: 20px; }.button { background-color: #4CAF50; border: none; color: white; padding: 10px 25px; text-align: center; text-decoration: none; font-size: 18px; }@media only screen and (max-width: 600px) { .columns { width: 100%; } }Stripe Subscriptions using php with Responsive Pricing Tables Basic $ 9.99 / year 10GB Storage 10 Emails 10 Domains 1GB Bandwidth <form action="" method="POST" class="spacing"> <input name="plan" type="hidden" value="Basic" /> <input name="interval" type="hidden" value="year" /> <input name="price" type="hidden" value="9.99" /> <input name="currency" type="hidden" value="usd" /> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="<?php echo $stripe['publishable_key']; ?>" data-image="https://www.w3school.info/wp-content/uploads/2017/08/w3school_logo.png" data-name="BASIC PLAN" data-description="Start with basic plan" data-panel-label="Subscribe Now" data-label="Subscribe Now" data-locale="auto"> </script> </form></li> Pro $ 24.99 / year 25GB Storage 25 Emails 25 Domains 2GB Bandwidth <input name="plan" type="hidden" value="Pro" /> <input name="interval" type="hidden" value="year" /> <input name="price" type="hidden" value="24.99" /> <input name="currency" type="hidden" value="usd" /> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="<?php echo $stripe['publishable_key']; ?>" data-image="https://www.w3school.info/wp-content/uploads/2017/08/w3school_logo.png" data-name="Pro PLAN" data-description="Start with Pro plan" data-panel-label="Subscribe Now" data-label="Subscribe Now" data-locale="auto"> </script> </form> </li> Premium $ 49.99 / year 50GB Storage 50 Emails 50 Domains 5GB Bandwidth " data-image="https://www.w3school.info/wp-content/uploads/2017/08/w3school_logo.png" data-name="Premium PLAN" data-description="Start with Premium plan" data-panel-label="Subscribe Now" data-label="Subscribe Now" data-locale="auto">Note : here you have 3 plans listed with different subscription plan and data(like plan name,plan price,plan interval [month/year/week/day] and currency) which are defined in hidden fields in every stripe form tag inside every pricing options.Step 3: Now the Stripe Server Side code where after inputing the card details Actyual payment need to be done So create a file create-subscription.php which is already included in index.php code in top lines, and this file wil have following Code: $_POST['plan'], "id" => "plan-".$_POST['plan'], "interval" => $_POST['interval'], "currency" => $_POST['currency'], "amount" => $_POST['price']*100, )); $customer = \Stripe\Customer::create(array( "email" => $_POST['stripeEmail'], "source" => $_POST['stripeToken'], // The token submitted from Checkout )); \Stripe\Subscription::create(array( "customer" => $customer->id, "items" => array( array( "plan" => "plan-".$_POST['plan'], ), ), )); $success = "Thanks! You've subscribed to the " . $_POST['plan'] . " plan."; } catch(\Stripe\Error\Card $e) { // Since it's a decline, \Stripe\Error\Card will be caught $body = $e->getJsonBody(); $error = $body['error']['message']; } // Probably want to log all of these for later or send yourself a notification catch (\Stripe\Error\RateLimit $e) { $error = "Sorry, we weren't able to authorize your card. You have not been charged."; } catch (\Stripe\Error\InvalidRequest $e) { $error = "Sorry, we weren't able to authorize your card. You have not been charged."; } catch (\Stripe\Error\Authentication $e) { $error = "Sorry, we weren't able to authorize your card. You have not been charged."; } catch (\Stripe\Error\ApiConnection $e) { $error = "Sorry, we weren't able to authorize your card. You have not been charged."; } catch (\Stripe\Error\Base $e) { $error = "Sorry, we weren't able to authorize your card. You have not been charged."; } catch (Exception $e) { $error = "Sorry, we weren't able to authorize your card. You have not been charged."; } } ?> Now you are Ready it will look like this : stripe subscriptions preview and if we click on any subscription button it will prompt a stripe popup like this stripe subscriptions credit card prompt by stripe Click HERE to download full source code Note: this is completely Free script. if you have any trouble in download this then please contact me at [email protected] or ask query in comments below
-
Jeetendra Singh - 16 Apr, 2017
Implement Stripe in 3 steps using php
Hi Geeks, This Article is focused on Implement Stripe in 3 steps using php, where you can easily accept payments through stripe by using this code. the stripe checkout.js is used here with server side code also. Step 1: Create a product list page named index.php with following code: Digital cart demo with Stripe checkoutbody{ margin-top:20px; background:#eee; }.prod-info-main { border: 1px solid #CEEFFF; margin-bottom: 20px; margin-top: 10px; background: #fff; padding: 6px; -webkit-box-shadow: 0 1px 4px 0 rgba(21,180,255,0.5); box-shadow: 0 1px 1px 0 rgba(21,180,255,0.5); } .prod-info-main .product-image { background-color: #EBF8FE; display: block; min-height: 238px; overflow: hidden; position: relative; border: 1px solid #CEEFFF; padding-top: 40px; } .prod-info-main .product-deatil { border-bottom: 1px solid #dfe5e9; padding-bottom: 17px; padding-left: 16px; padding-top: 16px; position: relative; background: #fff } .product-content .product-deatil h5 a { color: #2f383d; font-size: 15px; line-height: 19px; text-decoration: none; padding-left: 0; margin-left: 0 } .prod-info-main .product-deatil h5 a span { color: #9aa7af; display: block; font-size: 13px } .prod-info-main .product-deatil span.tag1 { border-radius: 50%; color: #fff; font-size: 15px; height: 50px; padding: 13px 0; position: absolute; right: 10px; text-align: center; top: 10px; width: 50px } .prod-info-main .product-deatil span.sale { background-color: #21c2f8 } .prod-info-main .product-deatil span.discount { background-color: #71e134 } .prod-info-main .product-deatil span.hot { background-color: #fa9442 } .prod-info-main .description { font-size: 12.5px; line-height: 20px; padding: 10px 14px 16px 19px; background: #fff } .prod-info-main .product-info { padding: 11px 19px 10px 20px } .prod-info-main .product-info a.add-to-cart { color: #2f383d; font-size: 13px; padding-left: 16px } .prod-info-main name.a { padding: 5px 10px; margin-left: 16px } .product-info.smart-form .btn { padding: 6px 12px; margin-left: 12px; margin-top: -10px } .load-more-btn { background-color: #21c2f8; border-bottom: 2px solid #037ca5; border-radius: 2px; border-top: 2px solid #0cf; margin-top: 20px; padding: 9px 0; width: 100% } .product-block .product-deatil p.price-container span, .prod-info-main .product-deatil p.price-container span, .shipping table tbody tr td p.price-container span, .shopping-items table tbody tr td p.price-container span { color: #21c2f8; font-family: Lato, sans-serif; font-size: 24px; line-height: 20px } .product-info.smart-form .rating label { margin-top:15px; } .prod-wrap .product-image span.tag2 { position: absolute; top: 10px; right: 10px; width: 36px; height: 36px; border-radius: 50%; padding: 10px 0; color: #fff; font-size: 11px; text-align: center } .prod-wrap .product-image span.tag3 { position: absolute; top: 10px; right: 20px; width: 60px; height: 36px; border-radius: 50%; padding: 10px 0; color: #fff; font-size: 11px; text-align: center } .prod-wrap .product-image span.sale { background-color: #57889c; } .prod-wrap .product-image span.hot { background-color: #a90329; } .prod-wrap .product-image span.special { background-color: #3B6764; } .shop-btn { position: relative } .shop-btn>span { background: #a90329; display: inline-block; font-size: 10px; box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset 0 -1px 0 rgba(0, 0, 0, .07); font-weight: 700; border-radius: 50%; padding: 2px 4px 3px!important; text-align: center; line-height: normal; width: 19px; top: -7px; left: -7px } .product-deatil hr { padding: 0 0 5px!important } .product-deatil .glyphicon { color: #3276b1 } .product-deatil .product-image { border-right: 0px solid #fff !important } .product-deatil .name { margin-top: 0; margin-bottom: 0 } .product-deatil .name small { display: block } .product-deatil .name a { margin-left: 0 } .product-deatil .price-container { font-size: 24px; margin: 0; font-weight: 300; } .product-deatil .price-container small { font-size: 12px; } .product-deatil .fa-2x { font-size: 16px!important } .product-deatil .fa-2x>h5 { font-size: 12px; margin: 0 } .product-deatil .fa-2x+a, .product-deatil .fa-2x+a+a { font-size: 13px } .product-deatil .certified { margin-top: 10px } .product-deatil .certified ul { padding-left: 0 } .product-deatil .certified ul li:not(first-child) { margin-left: -3px } .product-deatil .certified ul li { display: inline-block; background-color: #f9f9f9; padding: 13px 19px } .product-deatil .certified ul li:first-child { border-right: none } .product-deatil .certified ul li a { text-align: left; font-size: 12px; color: #6d7a83; line-height: 16px; text-decoration: none } .product-deatil .certified ul li a span { display: block; color: #21c2f8; font-size: 13px; font-weight: 700; text-align: center } .product-deatil .message-text { width: calc(100% - 70px) } @media only screen and (min-width:1024px) { .prod-info-main div[class*=col-md-4] { padding-right: 0 } .prod-info-main div[class*=col-md-8] { padding: 0 13px 0 0 } .prod-wrap div[class*=col-md-5] { padding-right: 0 } .prod-wrap div[class*=col-md-7] { padding: 0 13px 0 0 } .prod-info-main .product-image { border-right: 1px solid #dfe5e9 } .prod-info-main .product-info { position: relative } } HOT Sports Dress Sports </h5> <p class="price-container"> $<span class="price" >199</span> </p> <span class="tag1"></span> </div> <div class="description"> <p class="desc">this is my product desc </p> </div> <div class="product-info smart-form"> <div class="row"> <div class="col-md-12"> <a href="javascript:void(0);" class="btn btn-danger stripe_pay">Buy Now</a> </div> <div class="col-md-12"> <div class="rating">Rating: <label for="stars-rating-5"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-4"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-3"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-2"><i class="fa fa-star text-warning"></i></label> <label for="stars-rating-1"><i class="fa fa-star text-warning"></i></label> </div> </div> </div> </div> </div> </div> </div> <!-- end product --> HOT Travel Natural places Tours $5000 this is my product desc Buy Now </div> <div class="col-md-12"> <div class="rating">Rating: <label for="stars-rating-5"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-4"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-3"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-2"><i class="fa fa-star text-warning"></i></label> <label for="stars-rating-1"><i class="fa fa-star text-warning"></i></label> </div> </div> </div> </div> </div> </div> </div> <!-- end product --> Special Free Food DeliveryFood $50 this is my product desc Buy Now </div> <div class="col-md-12"> <div class="rating">Rating: <label for="stars-rating-5"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-4"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-3"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-2"><i class="fa fa-star text-warning"></i></label> <label for="stars-rating-1"><i class="fa fa-star text-warning"></i></label> </div> </div> </div> </div> </div> </div> </div> <!-- end product --> SALE Bar & Pubs Nightlife $1000 this is my product desc Buy Now </div> <div class="col-md-12"> <div class="rating">Rating: <label for="stars-rating-5"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-4"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-3"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-2"><i class="fa fa-star text-warning"></i></label> <label for="stars-rating-1"><i class="fa fa-star text-warning"></i></label> </div> </div> </div> </div> </div> </div> </div> <!-- end product --> SALE Fashion And Style Fashion $1000 this is my product desc Buy Now </div> <div class="col-md-12"> <div class="rating">Rating: <label for="stars-rating-5"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-4"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-3"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-2"><i class="fa fa-star text-warning"></i></label> <label for="stars-rating-1"><i class="fa fa-star text-warning"></i></label> </div> </div> </div> </div> </div> </div> </div> <!-- end product --> SALE Business Working Style Business $1000 this is my product desc Buy Now </div> <div class="col-md-12"> <div class="rating">Rating: <label for="stars-rating-5"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-4"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-3"><i class="fa fa-star text-danger"></i></label> <label for="stars-rating-2"><i class="fa fa-star text-warning"></i></label> <label for="stars-rating-1"><i class="fa fa-star text-warning"></i></label> </div> </div> </div> </div> </div> </div> </div> <form action="pay.php" id="pay_form" method="post"> <input type="hidden" name="price" /> <input type="hidden" name="title" /> <input type="hidden" name="category" /> <input type="hidden" name="image" /> <input type="hidden" name="desc" /> <input type="hidden" name="_pay_" value="1" /> </form> <!-- end product --> <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"> $(document).ready(function(){ $(".stripe_pay").click(function(){ var obj_prd=$(this).parents('.prod-info-main'); var price=obj_prd.find('.price').text(); var title=obj_prd.find('.title').text(); var desc=obj_prd.find('.desc').text(); var category=obj_prd.find('.category').text(); var img=obj_prd.find('.product-image img').attr('src'); console.log(img) $("input[name='price']").val(price); $("input[name='title']").val(title); $("input[name='desc']").val(desc); $("input[name='category']").val(category); $("input[name='image']").val(img); $("#pay_form").submit(); }); }); </script>Output Screen for this will look like this:Note: you can get products from database also,but here for demonstration i am showing these static. Step 2: Create a Checkout Page with name pay.php, here you need to replace the stripe public key mention in the comment also. Stripe Checkout demo</head> <body> Product title is : Category is : Description is : Amount is :$ " />" /> " data-name="" data-description="" data-image="" data-locale="auto" data-zip-code="true">Output Screen:Step 3: Create a server side script for charge customer named as charge.php with following code, here you need to replace the Stripe private key mention in comment also: FINAL PAYMENT STATUS- STRIPE SERVER SIDE CODE DEMOif(isset($_POST['stripeToken']) && $_POST['stripeToken']!=""){ // Set secret key \Stripe\Stripe::setApiKey("sk_test_g0654565464569");//replace your secreet key of stripe here // Get the credit card details submitted by the form $token = $_POST['stripeToken']; // Create the charge on Stripe's servers - this will charge the user's card try { $customer = \Stripe\Customer::create(array( 'email' => $_POST['stripeEmail'], 'source' => $token )); $charge = \Stripe\Charge::create(array( "amount" => $_POST['stripePrice'], "currency" => "usd", "customer" => $customer->id ));echo "<h1 style='color:green'>PAYMENT SUCCESSFULLY DONE</h1>"; } catch(\Stripe\Error\Card $e) { // The card has been declined echo "PAYMENT FAILED!"; } } ?> Output Screen:Note: there should be a stripe library in the root folder you can download it from here: https://github.com/stripe/stripe-php/archive/v4.7.0.zip and extract it with name stripe as you can see in following screenshotStill you have any problem in integrating you can directly call me and i will send you the complete working code, you can comment here or send me a email on [email protected] Thanks
-
Jeetendra Singh - 28 Jan, 2017
Radio and Checkbox use in Angularjs Post method
Hi Geeks, When I was working with angular form posts then I was tried radio and checkboxes as normal inputs in angular js form post then it is sending [Object Object] to the webservices and that object couldn’t be parsed by the server-end , and also inserted [Object Object] text into the database also. But I need to send the controls in key val pair So I Write following code written to sent it, These are the steps which I follow to achieve it. First I created the Html controls like this : <!— html radio box for item condition —> Bad Good Better Car Byke TV Now in your Controller ‘s submit function ( I am assuming that you have already go through my previous article for form process in angular js or you already aware with form processing in angular js ) as following: //collect the radio opted value data in a var var single_option= $scope. postAdd.condition1;//it will come directly because same group for radio will get only the selected value //collect the checkboxes data in a var with comma seperated var checked_items=””; angular.forEach($scope. postAdd .prd_type, function(val,key) { checked_items+=","+key; }); Now complete post action inside the respective controller will look like this $scope.submit_form = function() { $http({ url: base_url+"services.do/add_business",//or your service url method: "POST", processData: false, headers: { 'Content-Type': undefined }, data : $scope. postAdd,//it will get all other normal text or select inputs in the form form using common modal >> postAdd transformRequest: function (data) { var formData = new FormData(); //collect the radio opted value data in a var var single_option= $scope. postAdd.condition1;//it will come directly because same group for radio will get only the selected value formData.append(“item_condition”, single_option); //collect the checkboxes data in a var with comma seperated var checked_items=””; angular.forEach($scope. postAdd .prd_type, function(val,key) { checked_items+=","+key; }); formData.append(“item_types”, checked_items); return formData; }, }).success(function(data, status, headers, config) { //success callback, show success or alert depends on return data in first callback response named > data console.log("form submitted successfully"); }).error(function(data, status, headers, config) { //error callback here console.log("Error in form process"); }); } you can ask any confusion and if something not clear then put your query in comments , i will type to reply on same and try to resolve your problem where you stucked
-
Jeetendra Singh - 20 Nov, 2016
Image or file Upload in angular js
This tutorial is based on Image or file Upload in angular js . i am providing simple steps to image or file upload , I am assuming that you have already submitted the form using angular js, i have provided all steps in my previous tutorial Now follow these steps in existing one: add input type file inside your form as following: Image/File:Image/File is required. In above code we have passed a method name ‘uploadedFile’ in onchange of that input type file so need to create that function in our existing controller as following:$scope.uploadedFile = function(element) { $scope.$apply(function($scope) { $scope.files = element.files; }); } now we need to make some modification(related to add files and header info) and need to add transformRequest param, in our http post method as following: $http({ url: "http://localhost/web_services/add_enquiry.php",//or your add enquiry services method: "POST", processData: false, headers: { 'Content-Type': undefined }, data : $scope.formdata, transformRequest: function (data) { var formData = new FormData(); var file = $scope.files[0]; formData.append("file_upload",file); //pass the key name by which we will recive the file angular.forEach(data, function (value, key) { formData.append(key, value); }); return formData; }, }).success(function(data, status, headers, config) { $scope.status=data.status; if($scope.status==1) { $scope.formdata=""; $scope.myform.$setPristine();//for flush all the validation errors/messages previously alert(data.message); } else { alert(data.message); } }).error(function(data, status, headers, config) { alert("Something Error in form process"); });Now we can easily Recieve the image or file with ‘file_upload’ named field in php $_FILES array in our webservice, we need to save the file in uploads or any other folder and save its name to database as follow. 0,"message"=>"File not choosen!"); print json_encode($response); exit; } $f_name=uniqid("img_").str_replace(" ","-",$_FILES['file_upload']['name']); $target_file="./uploads/".$f_name; if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], $target_file)) { $response=array("status"=>0,"message"=>"File Upload Failed!"); print json_encode($response); exit; } $uploaded_file=$f_name; //now in your further code/insert query you can use $uploaded_file varriable as file name into your db //your further code here// //.....// //.....// //.....// ?>
-
Jeetendra Singh - 16 Nov, 2016
Form Processing and validation in Angular js
Hi Geeks, In this tutorial you will learn form processing and validation in angular js. where i have focused on validation in angular js, and after validation save the formdata to server/database using webservice. Step 1: Include the angular js in head section byStep 2:Define app name in body tagStep 3: Create a controller div, and for this controller we will write handler in javascript codeStep 4 : Create your form inside controller div and take name of that form it will use in validation the form fieldsFull Name:Your Name is required.Email:Your Email is required/Invalid.Mobile: +91-Your Mobile is required/Invalid.Message: Message is required.Submithere we’ll create a submit form named function in controller of this view to submit the information over server.but this function will call only when our form passes all validations. All data will binds to super object named formdata which we have used in every ng-model by using that single object we will send data to server. it will very usefull to collect data from every fields and create a bunch. thats why we have used formdata.{field_name} in every ng-model Now validation directives used in this form are following:Define form name attribute is must for validation , we have take myform as form name.For making a field required , we need to use required attribute For patter use ng-pattern , following pattern is a email syntaxng-pattern=”/^[^\s@]+@[^\s@]+.[^\s@]{2,}$/”ng-minlength is use for minimum length of input number/characters ng-maxlength is for maximum length of input number/characterswe have used minimum and maximum length of mobile number as per indian mobile standards ng-minlength=”10″ ng-maxlength=”10″ Showing a message below of each field ng-show=”{form_name}.{field_name}.$invalid && !{form_name}.{field_name}.$pristine” for example of full_name in this form we will use >> ng-show=”myform.full_name.$invalid && !myform.full_name.$pristine” Step 5: Now write angular controller code for form processing: Create a module for the ng-app var MyApp = angular.module('MyApp',[]); Now after it define the controller method body MyApp.controller('contactForm_CTRL', function ($scope, $http){ //form submit handler will come here }); Now create a method which we have used in form tag ng-submit directive name ‘submit_form()’ so create a method submit_form() inside the controller as following //create a submit action on form submit// $scope.submit_form = function() { $http({ url: "http://localhost/web_services/add_enquiry.php",//or your add enquiry services method: "POST", processData: false, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param($scope.formdata) // load the formdata named super object that already binds with using ng-model }).success(function(data, status, headers, config) { $scope.status=data.status; if($scope.status==1) { $scope.formdata=""; //Set back to pristine. $scope.myform.$setPristine(); } else { alert(data.message); } }).error(function(data, status, headers, config) { alert("Error in form process"); });} this function send your data to server and get response in json and handle the response in success callback if all data is fine then we will save it to db in webservices and return 1 and reset the formdata and show success message that is returned by webservice in alert with following: $scope.formdata=""; $scope.myform.$setPristine();//for flush all the validation errors/messages previously alert(data.message); If In status ,any error then we will return status 0 and failed message also. We will show that failed message in alert as following alert(data.message); Note: there is a error callback for any unexpected error from webservices that time we have alert following message: alert("Error in form process"); Now in your web_services/add_enquiry.php you can use following code : 1,"message"=>"Successfully Inserted");// data that will use to return to the angular/client app } else { //if query fails $response=array("status"=>0,"message"=>"Failed to add!"); } //now convert the array of response into json by using $return_json=json_encode($response); print $return_json; //print the json to return to client}mysqli_close($conn);//close connection ?> Note: Or write your own code just like a normal post of form. Now complete index.html code is following:Form PROCESSING & validation Angular App Form PROCESSING & validation Angular Demo AppYour Name is required.Your Email is required/Invalid.Your Mobile is required/Invalid. Message is required.Submitvar MyApp = angular.module('MyApp',[]);MyApp.controller('contactForm_CTRL', function ($scope, $http){ //create a submit action on form submit// $scope.submit_form = function() { $http({ url: "http://localhost/web_services/add_enquiry.php",//or your add enquiry services method: "POST", processData: false, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param($scope.formdata) // load the formdata named super object that already binds with using ng-model }).success(function(data, status, headers, config) { $scope.status=data.status; if($scope.status==1) { $scope.formdata=""; $scope.myform.$setPristine();//for flush all the validation errors/messages previously alert(data.message); } else { alert(data.message); } }).error(function(data, status, headers, config) { alert("Something Error in form process"); });} });Comment here if you face any problem in this Thanks.
-
Jeetendra Singh - 14 Nov, 2016
Url rewriting example in angular js
Hi Geeks, I am sharing Url rewriting example in angular js with complete steps to achieve it . If you are beginner with angular js then you might faced some issues with hash(#) in angular. So i am proving you the complete snippet and steps for making your url clean/pretty to make your angular js website seo friendly. you can download full source code from here or you can follow the steps, leave comments in comment box if you face any problem to achieve this Step 1 . for your index.html file write following code in your htaccess file. RewriteEngine on Don't rewrite files or directories RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^ index.html [L] Step 2. In index.html head section please put following lines :Note : in base href you need to provide your project url if on local, and for server you can set it only slash (/) . Step 3. Now according to the uri we need to load the page content , So we need to create a dynamic view and it will load the content as per the uri component :**Step 4**: write the Routing for load different different html views as per the uri component, in index.htmlSo wee need to initialize and use this code for configure and defining route provider and need to enable the html5 mode to true. Here locationprovider and routeprovider and http angular predefined directves wil be use here define app name in body using ng-app directive using as follow: ng-app="MyApp" and include the angular and routing libraries as follow :Now we initialize and define configuration for the MyApp as follow with injecting the ngRoute Directive:var MyApp = angular.module('MyApp', ["ngRoute"]);MyApp.config(['$routeProvider', '$locationProvider', function ($routeProvider,$locationProvider,$http){ $locationProvider.hashPrefix('!'); $locationProvider.html5Mode(true); $routeProvider .when('/', {templateUrl:'home.html' }) .when('/about', {templateUrl:'about.html' }) .when('/services', {templateUrl:'services.html' }) .when('/not-found', {templateUrl:'404.html' }) .otherwise({ redirectTo:'/not-found' }); }]);Note: I specify the url slugs and assign the template url according to the uri . you need to make each page to load the content as per the url. You have sucessfully done the url rewriting in angular js . Now full code of your index.htmlMy SEO Friendly ANGULAR APP MY ANGULAR SEO REWRITING DEMO APP Home About Services var MyApp = angular.module('MyApp', ["ngRoute"]); MyApp.config(['$routeProvider', '$locationProvider', function ($routeProvider,$locationProvider,$http){ $locationProvider.hashPrefix('!'); $locationProvider.html5Mode(true); $routeProvider.when('/', {templateUrl:'home.html' }) .when('/about', {templateUrl:'about.html' }) .when('/services', {templateUrl:'services.html' }) .when('/not-found', {templateUrl:'404.html' }).otherwise({ redirectTo:'/not-found' }); }]);Download full source code here
-
Jeetendra Singh - 21 Oct, 2016
Codeigniter best tricks and hacks
Hi Friends, Today I am sharing you some best tricks i have used in couple of projects, may be these things are common but we need these in all of our projects and we can find it on google but by different different authors, i am providing all the codeigniter tips tricks and hacks in this single article. if i missed any other trick then please let me know through comments, I will update it to my article. Now please find the Codeigniter best tricks and hacks 1: Remove index.php from url codeigniter Solution : we need to update the .htaccess with following code: RewriteEngine on #RewriteBase / RewriteRule ^(application|system|.svn) index.php/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.)$ index.php?/$1 [QSA,L] #RewriteRule ^(.)$ index.php?/$1 [L] 2: Call Controller function or varriable from view Solution : We need to pass the controller self object to its view to call the function or varriable of that controller . please follow instructions: /* controller code here .... .... ..my function 1 ..my function 2 { //returning any calculation } */ //Now in function 1 we are loading view 1 //and we want to call the function 2 after loaded the //view 1 //in controller file assign a self object to view $this->data['items']=$data_from_database; $this->data['controller']=$this; $this->load->view('view1',$this->data); //now in view1.php you can call the function 2 directly as $get_rates=$controller->function2(); //user the rate in running view 3: Db prefix in core queries Solution : in database.php we need to pass swap_pre in configuration index in db config array. please see example: In database.php there is a config array start with following: $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', ..... ..... So in this list there is a index named db_prefix this is general usage in CI auto qyuiry builder class but if we are writing the core queries then we need to pass any string like: 'swap_pre' => '{pre}', now we can use the swap_pre value appending before table name in our query as following: $result = $this->db->query("SELECT * FROM {pre}records WHERE record_id ='34' and category NOT IN (78,65,98) GROUP BY create_date"); return $result ->result_array(); 4: Call model and its function from library and helpers Solution : we can load any model from helper or library by instantiating the ci global object using call by refrence as following: //create a object in helper or library in codeigniter $this->CI = &get_instance(); //now if we want to load any model then $this->CI->load->model('Home_model'); //or load library using $this->CI->load->library('Pdf_custom_library'); 5: Get rendered html of your view in a Controller’s varriable Solution : Use third parameter as true in this load view Eg: $mydata_to_view=array(“bla”=>”bla bla value”); $myEmail_html=$this->load->view(“my_email_template”, $mydata_to_view,true); //Now this statement will not print output instead of it will return the html string.
-
Jeetendra Singh - 10 Sep, 2016
check value already exists in codeigniter
Callback function of codeigniter which checks whether the value already exists in particular column of table or not. This function work on add and edit both cases,it return false if value exists and return true if value not exists. following is the function that you need to put in your controller file: public function check_exist($string,$token){ if(!empty($string)){ $token=explode("-",$token); $column=$token[1]; if($token[0]=="add") { $where = array( $column => $string ); } if($token[0]=="edit") { $where = array( $column => $string, 'id!=' => $token[2] ); } $this->db->select('id'); $this->db->from('table_name'); $this->db->where($where); $num_results = $this->db->count_all_results(); if($num_results>0){ $this->form_validation->set_message('check_exist', 'The %s value is already exists.'); return false; }else{ return true; } } }Note: change the table name in function and in edit case you can change the primary key!= with your table’s key name. Now time to using this callback function for adding and editing forms.We need to pass the callback function in validation rules. For the time of adding you can pass the rule in your add action like as: array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[add-cat_name]' ),or $config = array ( array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[add-cat_name]' ), array( 'field' => 'slug', 'label' => 'Category Slug', 'rules' => 'trim|required|callback_check_exist[add-slug]' ), array( 'field' => 'description', 'label' => 'Category Description', 'rules' => 'trim|required' ), array( 'field' => 'parent_id', 'label' => 'Parent Category', 'rules' => 'trim' ), ); $this->form_validation->set_rules($config);and in your edit action you can use the rule as following: array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[edit-cat_name-'.$cat_id.']' ), OR $config = array ( array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[edit-cat_name-'.$cat_id.']' ), array( 'field' => 'slug', 'label' => 'Category Slug', 'rules' => 'trim|required|callback_check_exist[edit-slug-'.$cat_id.']' ), array( 'field' => 'description', 'label' => 'Category Description', 'rules' => 'trim|required' ), array( 'field' => 'parent_id', 'label' => 'Parent Category', 'rules' => 'trim' ), ); $this->form_validation->set_rules($config); Thanks for reading full article , Now use it in your project and if you face any trouble then comment here.
-
Jeetendra Singh - 28 Jul, 2016
CREATE OWN CAPTCHA FOR YOUR WEBSITE
Hi Geeks, I am sharing you a program forcreating a captcha script using php and javascript. Following are the simple steps to create captcha in php Step 1: Create a php script named ‘captcha.php’ with following code that generate and return a captcha image.Step 2: Now create a captcha.js file and put following code in the file. function reload() { img = document.getElementById("capt"); img.src="captcha.php"; } $(document).ready(function(){ var htm=' '; $('#custom_captcha').html(htm);//set the captcha data in element having id > custom_captcha . you can change as your div/Element id }); Step 3: Now we need to create a Placeholder Element inside the form as following:Step 4: Now after submitting you from validate the captcha was right or not. So in your form submit action use following code.Note 1: In which page/form you are using the capcha , there should be session start in top of the file as following:and also include the js file in your php page head section. jquery should be available before the captcha.js inclusion as following:Note 2: PHP GD LIBRARY SHOULD BE INSTALLED ON YOUR SERVER.
-
Jeetendra Singh - 25 Jul, 2016
Pagination code using php and mysql
Hi Geeks, We have gone through some user requests for pagination code for php mysql project.So we have created a simple class where you can easily create pagination for any grid or listing. following are the simple steps for making a pagination system in php. Step 1: Create a class file ‘Paginator.class.php’ in your project with following code snippet _conn = $conn; $this->_query = $query; $rs= $this->_conn->query( $this->_query ); $this->_total = $rs->num_rows; } public function getData( $limit = 10, $page = 1 ) { $this->_limit = $limit; $this->_page = $page; if ( $this->_limit == 'all' ) { $query = $this->_query; } else { $offset=( ( $this->_page - 1 ) * $this->_limit ); $query = $this->_query . " LIMIT " . $offset . ", $this->_limit"; } $rs = $this->_conn->query( $query ); $results=array(); while ( $row = $rs->fetch_assoc() ) { $results[] = $row; } $result = new stdClass(); $result->page = $this->_page; $result->limit = $this->_limit; $result->total = $this->_total; $result->data = $results; return $result; } public function append_existing_query_string($qstring) { if(isset($_GET)) { foreach($_GET as $k=>$v) { $qstring.="&".$k."=".$v; } } return $qstring; } public function createLinks( $links, $list_class ) { if ( $this->_limit == 'all' ) { return ''; } $last = ceil( $this->_total / $this->_limit ); $start = ( ( $this->_page - $links ) > 0 ) ? $this->_page - $links : 1; $end = ( ( $this->_page + $links ) _page + $links : $last; $html = ''; $class = ( $this->_page == 1 ) ? "disabled" : ""; // $qstring='?limit=' . $this->_limit . '&page=' . ( $this->_page - 1 ); $qstring=$this->append_existing_query_string($qstring); // $html .= '«'; if ( $start > 1 ) { // $qstring='?limit=' . $this->_limit . '&page=1'; $qstring=$this->append_existing_query_string($qstring); // $html .= '1'; $html .= '...'; } for ( $i = $start ; $i _page == $i ) ? "active" : ""; // $qstring='?limit=' . $this->_limit . '&page=' . $i; $qstring=$this->append_existing_query_string($qstring); // $html .= '' . $i . ''; } if ( $end ...'; // $qstring='?limit=' . $this->_limit . '&page=' . $last; $qstring=$this->append_existing_query_string($qstring); // $html .= '' . $last . ''; } $class = ( $this->_page == $last ) ? "disabled" : ""; $qstring='?limit=' . $this->_limit . '&page=' . ( $this->_page + 1 ); $qstring=$this->append_existing_query_string($qstring); $html .= '»'; $html .= 'Total records : '.$this->_total.''; return $html; }} ?> Step 2: Include the paging class before extracting data to showStep 3: Now extract the data for any page as following getData( $limit, $page ); ?> Step 4 : Now we are ready with data. So just showing the data and links as followingShow the data first and after it showing the pagination links as following: <th>Customer Id</th> <th>Customer Name</th> <th>Customer Email</th> <th>Customer Address</th> </tr> </thead> <tbody> <?php if(isset($results) && count( $results->data ) > 0){ for( $i = 0; $i < count( $results->data ); $i++ ) { ?> <tr> <td><?php echo $results->data[$i]['id']; ?></td> <td><?php echo $results->data[$i]['name']; ?></td> <td><?php echo $results->data[$i]['email']; ?></td> <td><?php echo $results->data[$i]['address']; ?></td> </tr> <?php } } ?> </tbody> </table>Show the paging links after the datacreateLinks( $links, $class="pagination"); ?>