twitterfacebookgoogle plusrss feed

Pages

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Monday, April 7, 2014

Possible reasons of jQuery library failed to load


Possible reasons of this error is one of the following

Path is incorrect or make sure you are typing the extension of file .js, did you ignored .js in the last as there is already dot before min (minify) so some peoples type jquery-1.7.min instead jquery-1.7.min.js. Or check that file is exists with the same name, it is jquery.js or jquery.min.js. As well as check the version of the file. One time I faced the same problem, mentioning jquery-1.2.min.js instead jquery-1.3.min.js.

If you are using CDN (Content Delivery Network), make sure the server of content provider is up and running.

Your jQuery library is not conflicting with other javascript libraries. Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's $ is an alias for jQuery. So try with jQuery instead $ sign or use jQuery.noConflict() or $.noConflict() before initializing ready() function. Go here to know how .noConflict() works.

Are you validating jQuery library or jQuery plugin with certain jQuery version, if so, then remember plugins developed for older jQuery versions might not function properly with latest version of jQuery. If you are somewhat depending on old jQuery plugin then use jQuery migrate plugin. Get detailed information about jQuery migrate plugin here, or pass comments to ask if you failed to get pie.

Check typography. Copy and past following lines into notepad, save as html and run, if it works (prompts with "hurray") it mean one of above solutions will work for you otherwise hmmm ,, seems annoying in modern era but i suggest you to check your browser's javascript settings, is it enabled.

<html><head>
<title>Validating jQuery</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
   alert("hurray");
});
</script></head><body></body>

Friday, March 28, 2014

How to create file and directory structure for MVC


You will find dozens of free and opensource MVC fameworks (Zend, CodeIgniter, CakePHP are some of them) around you, loaded with hundred of features so on this point making your own MVC is not a good idea. But for practising purposes I will tell you how MVC works and how to build directory and file structure for your very own MVC.

In old fashioned web page/application we handle user input, manipulates or use databases and then redirect user to beautifully organized results suitable to user input. All this activity occurs in single page, its okay if we are working on small application where much business logic isn't repeated. But in enterprise application this approach possibly make duplications in the code.

So what should we do if we are going to build enterprise level application.


MVC (Model-View-Controller)

It is a software pattern or architecture divided and interconnected into three parts, overridden old fashioned web page/application. Controller takes the user input, manipulates and convert input to command and send the formatted user commands to Model. Model is collection of logics and a place where we run database operations and send back required information to Controller, Controller then injects all user requested information in to the View. View might be collection of standard HTML commands, diagrams, charts, Javascript, CSS and any possible client side script. Take a look at the following flow chart it will help you to better understand MVC architecture.





Note: Kindly pass comments if you found any logical problem in flow chart, your comments will worth me a lot.

Break apart

Model: As per Controller request informs associated Controller and View about changes, so View change its representation and Controller update commands.

View: Controls the representation according to Controller commands.

Controller: Manipulate user input and send commands to Model to update model's state. Compile and inject the final out put to the View.


MVC files and folders structure

You need 4 folder and 2 files on the root

1) model (dir)
2) view (dir)
3) controller (dir)
4) engine (dir)

1) index.php



2) .htaccess

"model" directory contains all Models (files) or project.

"view" directory contains the files for the project used as front-end. User will serve and see these files.

"controller" directory contains Controllers (files) for the project

MVC has three basic files, main Controller, main Model and main View file known as engine for your MVC framework. These three files extends by all other Controllers, Models and Views. Besides these files you may also need helpers and libraries to be imported later in the project also placed in "engine" directory.

"index.php" file is very crucial, this is main switch to start your framework. Be careful while approaching professional level. Things started at this point will be available to all our project.

".htaccess" optional file. Just to beautify your URL to make it search engine friendly. Without this file your framework will function properly but I recommend to use it to make your project search engine friendly.

Wednesday, March 26, 2014

Uncaught TypeError: Property '$' of object [object Object] is not a function


If you are getting this error in WordPress then remember that WordPress loads jQuery with noConflict mode or any other application which loads with noConflict mode cause this error, you will no longer able to use jQuery shortcut ($) any more in this mode. On this point you have to use jQuery (case sensitive) instead jQuery shortcut $ (dollar sign) and if you want to use $ sign in code block than must pass $ (dollar sign) as function parameters;

jQuery(function($) {
    // now are able to use $ sign or jQuery
});

Tuesday, March 25, 2014

Use other libraries with jQuery using $.noConflict()


Just like jQuery, many other Javascript libraries uses $ (dollar sign) as a function. Using other Javascript library on the same page might cause error. So on the safe side, jQuery offers jQuery.noConflict() or $.noConflict; it restores all old references which are saved during jQuery initialization.

How to use it? Well, simply put jQuery.noConflict() at the top of your script. If you are experiencing "Uncaught TypeError: Property '$' of object [object Object] is not a function" error in console; its mean $ (dollar sign) is conflicting with other javascript library, put $.noConflict() on the top of the script. Still same error? no problem, in noConflict mode you cannot use shortcut of jQuery ($) use jQuery and pass $ (dollar sign) as function parameter. By including the $ in parenthesis after the function call you can then use this jQuery shortcut ($) within the code block. 

jQuery(document).ready(function($) {
   // your code here with $ sign
});

or 

jQuery(function($) {
   // your code here with $ sign
});

Thursday, March 20, 2014

Get reference from URL for MVC framework


Look at following URL

http://www.example.com/records/dvds/10

While creating MVC framework you have to follow the URL for reference. In above URL "records" is class or controller name. Controller is used to accept user input, after collecting data it prepare commands for Model and View. Reference to above-mentioned URL, "dvds" is a method of Controller "records" and "10" is parameter of method "dvds".

Note: URL is rewritten using .htaccess (check this post)

Now the question is how we will split the URL to get controller, its method and parameter for method. 

First get the URL by 

$route = $_GET["route"]; // or what ever you passed in .htaccess

Split the $route with "/"

list($class, $method, $param) = explode('/', $route); 

Now $routes is array holds controller name and its method and parameter if passed. 

if (is_file('controller/' . $class . '.php')) {
    $file = 'controller/' . $class . '.php'; // get the file of the Controller
}

Now you have, Controller, Controller file (where class or Controller written), method and parameter. Remember all three parts of URL (Controller, Method and Parameter) will not be passed every time, so be careful when approaching higher level.

Tuesday, March 18, 2014

.htaccess for MVC


In MVC routes are normally sent through query string formatted using .htaccess. You are passing a query string to index.php i.e. domain.com/index.php?route=records/dvds/10 transform into domain.com/records/dvds/10. What you have to do is create a new file .htaccess using any supported editor (netbeans will be best, remember notepad of windows do not support a file with no file name) and put following lines into the file, save and place this file in root of the folder where you want to create operational MVC.


RewriteEngine On

RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteCond %{REQUEST_FILENAME}% !-l

RewriteRule ^(.*)$ index.php?route=$1


It will successfully tranforme junky query string into nice looking url. The first part of url is considered a controller or class, the second part after front slash "/" is known to be method and the last one is parameters for the method. If "route" in query string is records/dvds/10 (looks like domain.com/records/dvds/10) you have to explode this string on "/" and it will returns an array contains three pockets, 0=>records (controller or class), 1=>dvds (method of records), 2=>10 (parameter of records).

Monday, March 17, 2014

QSA or Query String Append



QSA is flag used in .htaccess to append query string in traditional format into formatted or over written url after the URI has been rewritten. For example you are rewrite url from http://www.example.com/index.php?id=foo&user=bar to http://www.example.com/foo/bar and now you want to pass traditional query string to this over written url like http://www.example.com/foo/bar/?action=success then you have to declare following rule in .htaccess like RewriteRule ^([A-Za-z0-9]+)\/([A-Za-z0-9]+)$ index.php?id=$1&user=$2 [QSA]


Wednesday, July 4, 2012

Get file extension


You can use two easy functions to get the file extension in PHP

First


$file = "file.torrent";
echo substr($file,strrpos($file,"."));

Second


$file = "this.is.file.txt";
echo strrchr($file,".");

Restrict file extension using JQuery


$(function() {
    $("input[type=button]").click(function() {
        if (!$("input[type=file]").val()) {
            alert("Select file to Upload !");
            return false;
        }
        var allowedTypes = ["jpg", "jpeg", "gif", "png"];

        var path = $("input[type=file]").val();
        var ext = path.substring(path.lastIndexOf('.') + 1).toLowerCase();

        if (allowedTypes.lastIndexOf(ext) == -1) {
            alert("Select valid file i.e.\n" + allowedTypes);
        }
        alert("Valid file selected");
    });
});

Sunday, July 1, 2012

JQuery checkboxes implementation


I found many queries about "how we will make multiple check/unchecked button using JQuery, as well as how to count selected check boxes and then delete the selected records?". Its too easy!

Before working on this example I want to say, always follow the documentation of the product because you will found answers for many questions. Searching on internet not just take your a lot of time but you make yourself addicted of copy and paste.


$(function() {
    $("input[rel=main]").click(function() {
        $("input[rel=records]").attr("checked", this.checked);
        var c = $("input[rel=records]:checked").length;
        $("div > span").text((c > 1) ? c + " records are selected" : c + " record selected");
    });

    $("input[rel=records]").click(function() {
        var c = $("input[rel=records]:checked").length;
        $("div > span").text((c > 1) ? c + " records are selected" : c + " record selected");

        if ($("input[rel=records]").length == $("input[rel=records]:checked").length) {
            $("input[rel=main]").attr("checked", "checked");
        } else {
            $("input[rel=main]").removeAttr("checked");
        }
    });

    $("input[type=button]").click(function() {
        var n = $("input[rel=records]:checked").length;
        if (n <= 0) {
            alert("Select at least one record to delete");
        } else if (n >= 1) {
            var answer = confirm("Are you sure you want to delete " + n + " record(s)?");
            if (answer) {
                $("input[rel=records]:checked").parent().hide();
                $("input[type=button]").after((n > 1) ? " " + n + " records are deleted :)" : " " + n + " record deleted :)");
                $("input:checkbox").removeAttr("checked");
                $("div > span").text("");
            }
        }
    });
});

Friday, June 29, 2012

Multiple checkbox selection using JQuery


JQuery multiple checkbox selection is quite easy, simply put the following code and amend according to your choice

$("#maincheckbox").click(function() {
    $("input[type=checkbox]").attr("checked", this.checked);
});
 
$("input[rel=default]").click(function(){
    if($("input[rel=default]").length == $(".case:checked").length) {
        $("#maincheckbox").attr("checked", "checked");
    } else {
        $("#maincheckbox").removeAttr("checked");
    }
});


Wednesday, June 27, 2012

SQL Injection and user input


Many hacker try to temper sql queries which you are using while collecting data from your forms. If you are not formatting the data coming from public forms. Your own scripts may cause dangerous results including open access to your database and server access. 

Lets take a common example of user input for login forms.
While you are validating user to login; you commonly use following steps.

$user = $_POST["user_fld"];
$pass = $_POST["password_fld"];

SELECT * FROM tablename WHERE username = '$user' AND password = '$pass';

Now if you are not formatting your input, user may temper you above sql query by providing admin'; // or admin'; -- in username field. When processing by the server, your query will look like 

SELECT * FROM tablename WHERE username = 'admin'; //' AND password = '$pass';

In above case password checking is excluded from WHERE clause by commenting remaining part of the query. Now you know what this query means. It will allow user to login without providing a valid associated password.

This is the single example of sql injection, many others are available; if hacker is smart enough he or she may harm you valuable data.

So, what will be the solution? You may get rid of this serious problem if you format your incoming data by using PHP built-in functions or other user-defined functions.

I have developed a function written in PHP to override SQL Injection problem. You can download your copy from my github (https://github.com/adnnor/cleanX) repository.


Short form of if condition


Short form or Ternary operator is often used in many server and client side languages. The syntax of operator is usually same. I am going to give an example of PHP.

You are going to use an if condition in your PHP like

if ($country=="us")
   $language = "us english";
else
   $language = "uk english";

You may ternary oeprator to do same operation in short form; use following line of code

$language = ($country=="us")?"us english":"uk english";

is it cool ... isn't it :)