Sunday, August 30, 2015

Install Cakephp

Step 1) Download zip file from  github cakephp releases

Step 2)  Once you’ve got a fresh copy of CakePHP setup, open app/Config/core.php  and change the value of  'Security.salt'  and 'Security.cipherSeed'   on line 225 and 230 .
Just change one character from both value.
Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoDubWwvniR2G0FgaC9mi');
Configure::write('Security.cipherSeed', '76859309657853542496749683645');

Step 3) Create database

Step 4) you can see file database.php.default  in  app/Config/ folder so just rename it to database.php and open that file and replace value according your database credential in $default variable.
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'root',
'database' => 'test',
'prefix' => '',
//'encoding' => 'utf8',
);

Step 5) Run your project on browser  http://localhost/yourproject/

You will get output like below if everything is ok



Read More »

Environment Variable Setting For Cake Bake On Window 7

Cakephp is a rapid developement open source framework. It has lots of precious feature, one of them is Cakephp's bake console.

Cakephp bake console automatically generate CRUD(Create,Read,Update,Delete) functionality  for particular model. It means you will be able to step up a full working application in a few minutes using it

To bake CRUD(Create,Read,Update,Delete) functionality we have to run "cake bake" command in command prompt.
C:\Users\ubed>cake bake

I have notice lots of developer try this but they stuck in command line error.
Most common is below errer
'cake' is not recognized as an internal or external command, operable program or batch file.

it's means  you not set up Environment Variable Path. so here we are learning how to set up Environment Variable Path which is necessary before bake.

So just follow below video to set Environment Variable Path







Read More »

Tuesday, June 30, 2015

validation with jQuery validation plugin

Here i am explaining how to do validation with jQuery validation plugin just go through it.

First of all you need to download Jquery library file and validate plugin library file.
Include script in your project like below
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>

Here is your Form

<form name="register" action="" method="post" >
Username: <input type="text" name="username" />
Email: <input type="text" name="email" />
Password: <input type="text" name="password" />
Confirm Password: <input type="text" name="password2" />
<input type="submit" name="submit" value="submit" />
</form>

<script>
$("#register").validate({
 
                rules: {
                    'username':{ required:true, remote: { url: 'http://webpersist.com/username_ajax.php',type: 'POST',}},
                    'email':{ required:true, email:true},
                    'password':{required:true,minlength:5},
                    'password2':{equalTo: "#password"},
                },
             
                messages: {
                  'username': {required:'Please enter username',remote:'Username already exist'},
                  'password':{required:'Please enter password',minlength:'Length should be greate than 5 character'},
                  'password1':{equalTo:'Confirm password should be same as password'},
                  'email':{required:'Please enter email',email:'email should be valid'},
                },
                errorPlacement: function(error, element) {
                     //Note : uncomment error according your html

                      error.appendTo(element.parent().next(".validation"));
                   // error.appendTo(element.parent().last(".validation"));
                   // error.appendTo(element.last(".validation"));
                  // error.appendTo(element.next(".validation"));
   },
                submitHandler: function(form) {
                 form.submit();   //it will load page
                //you can also use ajax here if you don't want to load page after submission of form
                // see below register function and use like bold if you want  register();  and comment form.submit();
                }
            });
</script>

Here is username_ajax.php file
<?php
$user_email = $_REQUEST;
$user_email = $user_email['users']['email'];
if (!empty($user_email))
{
$email = mysql_real_escape_string($user_email);
$query=mysql_query("SELECT * FROM `users` WHERE `email`='" . $user_email . "'");
 if (mysql_num_rows($query) > 0) {
            $valid = false;
  }
  else{
            $valid = true;
    }
header('Content-type: application/json');
echo json_encode($valid);
}
exit;
?>



//if you want to submit form with ajax use this function in submit handler instead of form.submit()
<script>
function register(){
    var serverurl = 'http://webpersist.com/';
    var data= $( "#register" ).serialize();
 
    $.ajax({
            type: "POST",
            url: serverurl+"register_ajax.php",
            data:data,
            success: function(res) {
           alert('Register succesfully);
    },
            error: function() { console.log("error"); }
    });

}
</script>

Handle custom error in your own div and hide error if everything is correct by using following functions.
   errorPlacement: function(error, element) {
             $('.validation').show();
             element.next(".validation").html(error.text());
 },
          success: function (element){
             
                element.next(".validation").hide();
            }

//if your field name is multi dimensional array  like below and you want to validate all fields then you need to user add rule.
<input type="text" name="data[Link][0][link]" placeholder="URL" />
<input type="text" name="data[Link][1][link]" placeholder="URL" />

$(document).on('click', 'button', function() {
            $("[placeholder=URL]").each(function () {
            $(this).rules("add", {
            required: true,
            url: true,
            remote: {url: 'links/url_check', type: 'POST'},
            messages: {
                required: "This field is required.",
                remote: "Sorry we can't accept this url."
},
} );
     
    });
 
    });

//you can use below jquery selector also to loop all fields but remember field name should be without index like <input type="text" name="data[Link][][link]" placeholder="URL" />

$('input[name="data[Link][\\][link]"]').each(function () {

if else condition in validation using depends function
"data[Campaign][text_message]":{
                    required:{
                       depends: function(element) {
                           if ($('#CampaignCampaignType2').is(':checked') || $('#CampaignCampaignType3').is(':checked')){
                               return true;
                           }else{
                               return false;
                           }
                       }
                    }
                }

Ignore hidden fields in forms
$("#postJobStep1").validate({
        ignore: "input[type='text']:hidden",
        errorElement: "div",
        errorClass: "cust_error",

Check image extension while uploading file
$("#BannerAdminAddForm").validate({

            ignore: "input[type='text']:hidden,input[type='file']:hidden",
            errorElement: "div",
            errorClass: "cust_error",
            rules: {
                    'data[Banner][image]': {
                    extension: "jpg|jpeg|png|gif"
                    }
            },
            messages: {
                'data[Banner][image]': {
                extension: "Please provide jpg,jpeg,png or gif only"
                },
            }
    });

Validation for dynamic added fields and check above field not same as below fields
$('#addRosterForm').submit(function(e) {
            $.each($('input' ,'#addRosterForm'), function(key) {
                if($(this).hasClass( "firstname" )){
                    $(this).rules("add", {
                        required: true,
                        lettersonly: true,
                        messages: {
                            required: "Please enter the first name.",
                            lettersonly: "Names can contain only alphabets."
                        }
                    });
                }
               
                if ($(this).hasClass('lastname')) {
                    $(this).rules("add", {
                        required: true,
                        lettersonly: true,
                        messages: {
                            required: "Please enter the last name.",
                            lettersonly: "Names can contain only alphabets."
                        }
                    });
                }
               
                if ($(this).hasClass('dob')) {
                    $(this).rules("add", {
                        required: true,
                        messages: {
                            required: "Please enter the dob."
                        }
                    });
                }
               
                if ($(this).hasClass('jersey')) {
                   
                    $(this).rules("add", {
                        required: true,
                        min:1,
                        maxlength:10,
                        messages: {
                            required: "Please enter the jersey number greater than 1.",
                            maxlength :"Please enter less than 10 characters jersey no"
                        }
                    });
                }
               
                if ($(this).hasClass('email')) {
                    var id = this.id;
                    $(this).rules("add", {
                        required: true,
                        email: true,
                        notEqualToGroup: ['.email'],
                        remote: {url: 'emailExist', type: 'POST',data: {email: function() {return $('#'+id).val();}}},
                        messages: {
                            required: "Please enter email.",
                            email :"Please enter valid email.",
                            remote :"Email already exist."
                        }
                    });
                }
            });
           
            e.preventDefault();

            // test if form is valid
            if($('#addRosterForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
           
       });

   jQuery.validator.addMethod("notEqualToGroup", function (value, element, options) {
    // get all the elements passed here with the same class
    var elems = $(element).parents('form').find(options[0]);
    // the value of the current element
    var valueToCompare = value;
    // count
    var matchesFound = 0;
    // loop each element and compare its value with the current value
    // and increase the count every time we find one
    jQuery.each(elems, function () {
        thisVal = $(this).val();
        if (thisVal == valueToCompare) {
            matchesFound++;
        }
    });
    // count should be either 0 or 1 max
    if (this.optional(element) || matchesFound <= 1) {
        //elems.removeClass('error');
        return true;
    } else {
        //elems.addClass('error');
    }
}, jQuery.format("Please enter a unique value."));



Validate image height width
https://jsfiddle.net/3fr8s9x7/39/

Note: also implement server side validation in registration function for security reason

Read More »

Wednesday, April 8, 2015

Mysql query to find nearest user to your current location

Following query will find records which came under 1.5 km on the basis of user current latitude and longitude

user latitude is 21.153518
user latitude is 79.045513

SELECT *
        FROM users
        WHERE ( 3959 * ACOS( COS( RADIANS( 21.153518 ) ) * COS( RADIANS( users.latitude ) ) * COS( RADIANS( users.longitude ) - RADIANS( 79.045513 ) ) + SIN( RADIANS( 21.153518) ) * SIN( RADIANS( users.latitude ) ) ) )  < 1.5


Here is some more query may be helpful to you guys :)

SELECT users. * ,ACOS( SIN( RADIANS( users.`latitude` ) ) * SIN( RADIANS( 21.153518 ) ) + COS( RADIANS( users.`longitude` ) ) * COS( RADIANS( 21.153518 ) ) * COS( RADIANS( users.`longitude` ) - RADIANS( 79.045513 ) ) ) *6380 FROM users


SELECT * , ( 3959 * ACOS( COS( RADIANS( 21.153518 ) ) * COS( RADIANS( users.latitude ) ) * COS( RADIANS( users.longitude ) - RADIANS( 79.045513 ) ) + SIN( RADIANS( 21.153518) ) * SIN( RADIANS( users.latitude ) ) ) ) AS distance
        FROM users
        ORDER BY distance
Read More »

Wednesday, April 23, 2014

How do you set and get ckeditor value by javascript



How do you get data from ckeditor ?
use below code to get data from ckeditor , assume your editor name is 'description'

alert(CKEDITOR.instances.description.getData());

How do you set data in ckeditor ?
use below code to set data in ckeditor , assume your editor name is 'description'

CKEDITOR.instances.description.setData( '<h1>Hello Ubed Khan PHP programmer</h1>' );
Read More »

Monday, April 21, 2014

How to build cordova project

How to build  cordova project

Step 1) Make sure Node.js is installed on you computer. If not installed please install latest version from http://nodejs.org/

Step 2)  Open terminal and type the following command  to install the Cordova CLI
 sudo npm install -g cordova

Step 3) Change directory where you want to store project by following command
cd ~/project_directory

step 4) Create a project called “myfirstapp” by following command
cordova create myfirstapp com.yourname.myfirstapp myfirstapp

step 5)  Change directory to myfirstapp by following command
cd myfirstapp

step 6) Add platform support for your app here we are adding platform support for IOS by following command
cordova platforms add ios

step 7) Now build cordova project
You need the iOS SDK installed on your computer to build an iOS version of your application using the following command
cordova build ios


The project is built in the myfirstapp/platforms/ios folder. Double-click Workshop.xcodeproj to open the project in XCode, and run it in the emulator.

You will see "Device Ready".....

Note: this guide will work only on Mac operating system
Read More »

Wednesday, December 25, 2013

How to escape quotes in php

Here i have paste two example of how to escape quotes in php we face always when we use php , html and javascript event combine.

First Example
<?php

echo $chkbox = '<input type="checkbox" name="pages" id="chk_'.$val['sb_id'].'" value="'.$val['sb_id'].'" onclick=\'assignSidebar('.$val['sb_id'].',"'.$val['sb_name'].'")\' />';

?>
Second Example
<?php

$name = "khan's";
$name = htmlentities(str_replace("'", "\'", $name));
echo $response = "<img src=\"images/action_delete.gif\" onClick=\"confirmDelete('" . $name . "')\"/>";

?>

php to encode special characters but not html tags

For Latin-1 you can escape characters easily with:
$html = preg_replace('/[\x80-\xFF]/e', '"&#x".dechex(ord("$0")).";"', $html);
For UTF-8 it's a bit more involving:
$html = preg_replace_callback("/(?!\w)\p{L}/u", "xmlent", $html);
function xmlent($m) {
    $str = mb_convert_encoding( $m[0] , "UCS-2BE", "UTF-8");
    return "&#x" . bin2hex($str) . ";";
}
Read More »