Hi, I needed to change the contents (li) of the my carousel whenever a tab is click
so i used the example of dynamic content loading through js over here
http://sorgalla.com/projects/jcarousel/examples/dynamic_javascript.html
But i need to reset the carousel on tab change so for that the code is
var carousel = $(’#mycarousel’).data(’jcarousel’);
carousel.reset();
This will reset the caraousel and then again I can load different content in it.
Learn , Share , Enjoy
initializing jcarousel without page refresh
handling custom form in wordpress
I had a custom login form in WP(3.1.2) and the problem i was facing is whenever the form was submitted i used to get empty $_POST array.This was my code
<form method=”post” action=”<?php echo bloginfo(’url’).’/?page_id=221′; ?>”>
After some google search I found the solution which was :
<form method=”post” action=”<?php echo $_SERVER['PHP_SELF'].’/?page_id=221′; ?>”>
which means if you are submitting the form on the same page use $_SERVER else you wont get the data in post
Passing parameters to a function called with setTimeout
setTimeOut(myfunction(parameter),myTimeout);
The above line will not work. To achieve this you will have to do it with closure
setTimeOut(function(){myFunction(parameter)},myTimeout);
a simple but useful hack regarding annotated spring form and binding result
I was adding an form to an annotated spring controller with the use of binding result parameter.Code for the same is :
@RequestMapping(value = “/save.do”)
public String save(@ModelAttribute(”advertisement”) Advertisement advertisement,HttpServletRequest request,BindingResult result){//your code
}
While executing I got the error :
Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!
After some google search I figured out that :
“The
BindingResultparameter must be positioned directly after the corresponding model argument that is being validated.”Which means :
@RequestMapping(value = “/save.do”)
public String save(@ModelAttribute(”advertisement”) Advertisement advertisement,BindingResult result,HttpServletRequest request){//your code
}
send an array in ajax and get it in java
Here’s a simple ajax request :
$.ajax({
url : “xyz/functionName.htm”,
dataType : “html”,
type : “post”,
data : { ‘countryName’ : countryName, },
success : function (resp) {
}
});
Now on the server side,to get the value of post variable we normally write :
String name = request.getParameter(”countryName”);
But suppose the data I am sending is array
data : { ‘countryName[]‘ : ['india','australia','africa'] }
Then to access the array on the server side we have to write :
String [] name = request.getParameterValues(”countryName”);
accessing outer class variable within inner class
the syntax to access outer class variable within inner class is OuterClassName.this.varName.
Ex:
Class Outer {
int a = 100;
public Outer{
Inner inner = new Inner();
inner.print();
}
Class Inner {
public print(){
System.out.println(”Value of a is ” + Outer.this.a);
}
}
public static void main(String[] args)
{
new Outer();
}
}
how to create an object of the topmost class in php
$data = array(
‘currency’ => $order->getOrderCurrencyCode(),
‘date_added’ => date(’Y-m-d’)
);
$order_query = new stdClass();
$order_query->row = $data;
php array to sql query
I came across a case where i was getting a post in which i get column names of my table in keys, so i used the following code
$data = array(’column_1′ => 1, ’column_2′ => 45, ’column_3′ => 25 );
$sql = http_build_query($data, ”, ‘, ‘);
$query = “UPDATE table_name SET ” . $sql . ” WHERE id = ‘ 24 ‘ ” ;
Note: This cant be used if you values are coming in string
Passing url in GET parameter of API
Its become very difficult to pass url as a parameter to the api. And it becomes more pain when we have to pass it in GET of that of the api url.
e.g. http://apiurl.com?&name=jimit&url=http://myurl.com&id=241
Now in this the id parameter of myurl goes as GET parameter of apiurl. To overcome such situation we can use HTML URL Encoding
http://apiurl.com?&name=jimit&url=http://myurl.com%26id=241
you can find the complete list of HTML URL Encoding here.
PHP converting all Errors to Exception
<?php
function exceptions_error_handler($severity, $message,$filename, $lineno) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
set_error_handler(’exceptions_error_handler’);
?>
delete mysql cache while testing query performance
To test query execution time – you will need to delete the internal caches of mysql to figure out the exact time the query needs to execute .
This can be done by the following command after each query execution : -
Flush Tables;
Using column_name in RegExp in MySQL
Wrong:
SELECT a.company, a.name, b.title, b.description, b.t_id
FROM a, b
WHERE ( b.title
REGEXP "[[:<:]]a.company[[:>:]]" OR b.description )
Correct:
SELECT a.company, a.name, b.title, b.description, b.t_id
FROM a, b
WHERE
(
b.title REGEXP concat('[[:<:]]', a.company, '[[:>:]]') )
Reason: In the wrong query a.company is in quote (’ ‘) so it will be consider as string. So this will be overcomed by concat function of mysql.
PhpMyAdmin Session Time-Out
In Linux for increasing session time-out period edit /etc/phpmyadmin/config.inc.php as follows:
Add/Update following line
$cfg['LoginCookieValidity'] = your_time;
I did that for a Week as follows:
$cfg['LoginCookieValidity'] = 60*60*7*24*1;
Regular Expressions in MYSQL (REGEXP)
In mysql I need to get the stores name starting from ‘a’. For that I can use LIKE
e.g. SELECT * FROM stores WHERE store_name LIKE ‘a%’;
But what if i want to get stores name starting from numeric (0-9). Here comes REGEXP. My query would be like this.
e.g.
SELECT * FROM stores WHERE store_name REGEXP ‘^[0-9]‘ ;
OR
SELECT * FROM stores WHERE store_name REGEXP ‘^[a]‘ ;
Where ^ operator represents the starting of line or text. See more info here.
Regular Expressions in Notepad++ for replacing string
I wanted to replace text in between tags . Let the tag be
“<div class=”name”> abcdef </div>”
now I wish to replace every occurrence of the “<div class=”name”> abcdef </div>”
Now we can just replace it with “kodeplay” .
The above give example is a very simple expression used . You can use your own regular expressions as per your needs
jQuery: selecting elements with multiple classes
Here is a way to select element with multiple classes in jquery.
$(’table.cl1.cl2′).addClass(’abc’);
And to select the element which has one class
but not the other. This, does that:
$(’table.cl1:not(table.cl2)’).addClass(’xyz’);
Second one is pretty interesting which works like if clause.
how to detect all ajax requests using the zend framework
Zend_Controller_Request_Http has a rudimentary method for detecting AJAX requests: isXmlHttpRequest(). This method looks for an HTTP request header X-Requested-With with the value 'XMLHttpRequest'; if found, it returns TRUE. $this->getRequest()->isXmlHttpRequest() it is important to check that your ajax requests contain the request header - X-Requested-With
php array to http url
hi guys,
I came across a beautiful function of php which will convert any php array to the GET parameter for url.
E.g.
$data = array( ‘foo’ => ‘bar’, ‘jimy’ => ‘modi’ );
$url = http_build_query($data);
this will give you
foo=bar&jimy=modi
Convert ASCII code to text in javascript
If a javascript string contains ASCII codes as a result of escaping HTML characters, to convert them into text, use the String.fromCharCode(); and replace functions as follows
str.replace(/&#(\d+);/g, function (m, n) { return String.fromCharCode(n); });
String.fromCharCode() is a static function and will be called by passing the string variable and using ‘String’ only. ie not like other string functions eg str.replace()
How to get Latitude and Longitude from IP address
After searching for more than four to five hours i got the link which give latitude, longitude and other information such as address including city and country. So here is a small function which will give you latitude and longitude of the given ip address.
function getLatLng($ip){
//get the contents from the site by file_get_contents.
$sXML = @file_get_contents(’http://ipinfodb.com/ip_query.php?ip=’.$ip.’&timezone=false’);
//make the response in a xml object so we can parse it.
$oXML = @new SimpleXMLElement($sXML);
$array = array(
‘Latitude’ => (string) $oXML->Latitude[0],
‘Longitude’ => (string) $oXML->Longitude[0]
);
return $array;
}
MySQL FullText Searching
Suppose you want to search a keyword in 5 different columns or almost in all the fields of the table, then MySQL
provides us with fulltext indexing and searching method.
Before using this method , you need to add FullText to the columns in which you want to search.
ALTER TABLE member ADD FULLTEXT(firstname, lastname,address);
Then comes your main query :
SELECT firstname, lastname,address FROM member
WHERE MATCH (firstname,lastname,address) AGAINST (’test’);
The Match will look for “exact match” in the above 3 columns and on successfull match it will return that row.
Suppose in member table there is a an entry with firstname = test then the output will be :
firstname lastname address
test abc xyz
Suppose you want to use wildcards then modify your query :
SELECT firstname, lastname,address FROM member
WHERE MATCH (firstname,lastname,address) AGAINST (’*test*’);
Custom Events in jquery
we can fire custom events in jquery and set an event handler for each event .
This enables loose coupling and code reuse . This can be used to achieve the observer design pattern .
$(’#txtAddress’).keyup(function() {
$(document).trigger(’ADDRESS_CHANGE’);
});
$(’#txtCity’).keyup(function() {
$(document).trigger(’CITY_CHANGE’);
});
to now bind the event :
$(document).bind(’ADDRESS_CHANGE’, function(e) {
UpdateName();
UpdateOtherText(e);
});
Hack Away
How to use MySQL FOUND_ROWS()?
MySQL has a function called FOUND_ROWS which is faster than any other function for counting rows which is returned by the latest query, it is used same as MySQL “LASTINSERT_ID()”.
For example: if we are developing a pagination script and we want the total number of results returned by the Query, at the same case in pagination we use LIMIT for paging the record using the above function it will not return the limit results it will return the total available results.
How to use? suppose we have 20 records in our table and we are fetching only 10 records in a page, then the $total will return total 20 not 10.
$sql = “SELECT SQL_CALC_FOUND_ROWS * FROM tablename LIMIT 1, 10 “;
$results = mysql_query($sql);
$total = mysql_query(’SELECT FOUND_ROWS() as total’);
Css Hack
I spent about 35 minutes on this one and still havent found a logic to it .
But this hack should be remembered .
consider the markup : <div id = a ><input/><div id = “a_child” ></div> </div>
if you need to give a bottom border to the div with id = a and expect it to come below the div with id = “a_child” , then the following css needs to be in place :
#a{ height:auto;overflow:hidden;}
Thanks to vineet and jimit to get out of this one ..
word wrap for an editable div
To make a div or a paragraph editable set the attribute - contenteditable = true
give a fixed width to the div : - width:100px ;
after 100px the word should wrap down , for this add the css property :
word-wrap:break-word;
Happy Hacking
Simple way of converting a jquery object to javascript object
Sometimes while using jquery we need to get the javascript object of a dom element to call javascript functions on them.
For eg suppose we want to find the scrollHeight of a div. In case this div is given an id then it can be very easily done using
var divObj = document.getElementById(”myid”);
var sH = divObj.scrollHeight;
but what if we want to find the scrollHeight of tbody element inside a table inside the div#myid
in jquery we traverse it using $(”#myid>table>tbody”)
var sH = $(”#myid>table>tbody”)[0].scrollHeight;
This will return us the 1st element of the array. If there is only one such tbody, it will give us the required Object to call the function
Getting first day of the month in mysql
Here is a small trick to get first day of the month
SELECT DATE_SUB(now(),INTERVAL (DAY(now())-1) DAY)
This will give you the first day of the current month. You can also get first day of the month for a given date just pass the date instead of now()
SELECT DATE_SUB('2010-08-10',INTERVAL (DAY('2010-08-10')-1) DAY)
TD border for empty cell in IE
IE does not allow to create a border around an empty cell hence a wise trick to apply here is in the script part write the following code .
$(document).ready(function(){
$(”td:empty”).html(” “);
}
The code replaces all empty cell data with blank spaces( ) and creating a border around empty data
condition to determine if a javascript variable has been defined or not
In php to determine if a certain variable is set we use the function,
isset($variable)
it returns a boolean value.
To do the same thing in javascript, use the following condition,
if(typeof variable != ‘undefined’){
alert(’This variable is not defined yet’);
}
else {
alert(’The variable is defined’);
}
Fire Bug for every browser
Paste the following code in your [head] section and firebug will run in any browser :
[script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'] [/script]
Replace [] with <> accordingly
C trick
value of a variable which was last initialised can be printed without specifying variable name !!!
#include
#include
void main()
{
int a,b,c;
clrscr();
printf(”Enter No. C:”);
scanf(”%d”,&c);
printf(”%d”); /* printf(”%d”,c) is not required*/
getch();
}
Adding your own custom functions to jquery
hide(),show(),empty()…this are predefined functions of jquery.
So, to add your own function , you just have to write small piece of code :
$.fn.myFunction = function() {
return $(this).addClass(’changed’);
}
And now, use it like this:
$(’.changePlease’).myFunction();
What is (function($){…})(jquery) ??
All jQuery plugins code is wrapped in this anonymous function.So what exactly this function do ??
Well,my little research shows that this allows the use of $ within this function without conflicting with other JavaScript libraries who are using it. Basically, since we are setting $ as a parameter, $ will overwrite any globally defined variables/references of $ in that particular anonymous function.
// Assume “$” is a prototype reference
(function ($) {
// Here “$” is a jQuery reference
})(jQuery)
mysql manual from command line
the mysql manual can be accessed from the command line itself as follows :
help “<search term>”;
explicitly call super class constructor in php
Unlike Java , the constructor of the super class will not be called implicitly in PHP .
To call the parent class constructor from the child class we can use :
parent::construct();
MySQL – The GROUP_CONCAT() function
GROUP_CONCAT() function is used to concatenate column values into a single string.
Example:
Table ‘abc’ has following columns:
id customer_id
3 14
3 15
3 16
4 18
4 18
You can use this query:
SELECT id,GROUP_CONCAT(customer_id) FROM abc WHERE id = 3 GROUP BY id;
output:
id customer_id
3 14,15,16
It is useful when you want PHP array without looping inside PHP:
How to destroy or remove Tiny MCE control from jquery dialog on ajax request?
To use tiny mce in a jquery dialog and clear the contents of tinymce on close of the overlay use the following function :
$(”id-for-dialog”).bind( “dialogclose or dialogbeforeclose”, function(event, ui) {
tinyMCE.execCommand( ‘mceRemoveControl’, true, ‘id-for-editor’ );
});
This will enable loading of new content into the tinymce editor whenever the jquery dialog reopens .
sending additional data to server along with jquery’s .serializeArray object
Many times we use jquery’s .serializeArray function to send form field values by $.post or $.ajax methods. Suppose we want to send some other data besides serialized form data, it can be done by pushing additional objects into the array returned by .serializeArray as follows
var data = $(”#my-form”).serializeArray();
data.push({ ‘name’:'category_id’ , ‘value’:this.categoryId });
data.push({ ‘name’:'entity_id’, ‘value’:this.entityId });
the elements returned by serializeArray are objects with properties ‘name’ and ‘value’ .. Once the post request is sent these can be accessed on the server side as $_POST['category_id'] and $_POST['entity_id'] just like the other parameters.
This method is better over hidden input field method particularly when dynamic values are needed to be set to the hidden form fields using javascript.
toggleText for jQuery
Unfortunately JQuery doesn’t have function to toggle text of a given element
. But here is a trick by which you can add toggleText function to your jQuery.
jQuery.fn.toggleText = function(a, b) {
return this.each(function() {
jQuery(this).text(jQuery(this).text() == a ? b : a);
});
};
code:
$(element).toggleText('Preview','Back');
Convert ‘null’ to 0 in mysql
To convert a null value to zero returned by a mysql query use the function COALESCE(value,…)
Mysql Query :
SELECT COALESCE(column_that_might_be_null,0) as column_with_null_converted_to_zero FROM table_with_column_that_might_be_null;
A simple trick for adding html code using js
If you want to add a relatively large chunk of html code to the DOM using javascript, and if you find it annoying to write the markup as a string in js, here is a simple trick!
write the mark up normally in the html and use inline display:none to hide it
[html]
….
[html]
now in js (using jquery)
//for inserting dynamic html, insert all the required values in the dummy div first and then assign the inner content to a variable
$(”.htmltoadd>p”).html(’Hello World’);
var myhtml = $(”.htmltoadd”).html();
$(”#required-container”).html(myhtml’);
Adding date and time in PHP
I came across a situation where i want to end an event exactly after two days and before an hour of third day ( i.e. 11:00 pm on third day). After searching on google and checking the date function in php manual i came to this solution
$new_date = ( strtotime(’-1 hour’,strtotime ( ‘+3 day’ , strtotime (date ( ‘Y-m-d’ ) ) ) ));
This will return a unix timestamp which will give you 11:00 pm of third day.
eg. if todays date is 27/05/2010 07:08:15 then it will give you 29/05/2010 23:00:00
Background Opacity to be set in CSS
Ever wondered how you could change the opacity of the background or adjust the alpha quantity for it here is a trick to do so :
e.g.If you want to set a background for body then
in the CSS this is what should follow
body
{background rgba(82,82,82,0.7)}
here ‘rgb’ is for the red,green,blue values respectively and ‘a’ is the alpha/opacity for the background
How to attach callback functions
To attach a callback function in js :
function test(callback){
//some code for test function
if(callback && typeof callback == ‘function’){
callback.call();
}
}
test(doendtest);
The endtest function will execute after the test function .
Using conditions in mysql queries
If we want to use “if then” conditions in our code, in some cases, it can be done in mysql queries itself. For eg .
SELECT IFNULL(a,b) ) as val
In the above statement, the value of val will be equal to “a” if “a” is not null or it will be “b” if “a” is null.
another peculiar eg is “(SELECT IFNULL(special_price,p.price) ) as current_price” where the value of special_price is coming from another query in the same sql string (multiple queries).
passing a string as get param in curl response
while using curl in application for requesting the remote URL, be careful it doesn’t contain any white space, if it contains the white space it will show you a 400 error!.. To solve of this, replace blank space in the url with “+” . Hope this trick is useful .
Happy Coding !
how to bind a function to different UI elements on multiple events
suppose there are 2 buttons with id’s of “test” and “test4″
we want to bind the function with name as “getmember” on click of “test” and mouseout of “test4″ then
$(’#test’)['click'](getmember);
$(’#test4′)['mouseout'](getmember);
Hope this is useful
Switch off autocomplete for all inputs and select boxes
For a lot of forms we need to switch off autocomplete by the browser . This should be done for payment details forms .
This can be easily done by a jquery one liner .
$(’input,select’).attr(”autocomplete”,”off”);
mysql storage engines
myisam is the default storage engine . it is optimised for speed .innodb is optimised for data integrity . I am not sure which one to use when
(feel free to comment on this ) . To change from myisam to innodb -
ALTER TABLE tbwithMyISAM CHANGE TYPE=InnoDB
using jquery’s ui draggable with jquery’s .live method
To use jquery ui draggable on dom elements that will be added to the doc later, the initialization can be done on its mouseover event by using .live() method of jquery
as in
$(”#newdiv”).live(’mouseover’,function(){
$(this).draggable({
stop: function(){
//do something
}
});
});
eclipse shortcut
to view the defination of a method , just press the ctrl key and click on the method name .
Determine element is visible or not
if($(’element:visible’).length < 1){
alert(’Element is In Visible’);
}
else{
alert(’Element is Visible’);
}
Retriving multiple values from a single field of your database
if your having a field in your table which holds multiple values and you want to display the same.then use “spliti”
example:
company_dept is the field name.
$sql=”SELECT *from table_name”;
$ex=mysql_query($sql)
$result=mysql_fetch_array($ex);
$cmp_dept=$result['company_dept'];//when you echo this will display all the values
suppose you want single value then
$dept=spliti(”,”, $cmp_dept, 5);//this will split a string into array
$cnt=count($dept);//this will count the number of elements in the array
for output:print_r($dept)
or echo $dept[0];
spliti is case insensitive whereas split is not.
for more info visit:http://www.php.net/manual/en/function.spliti.php
Inserting multiple values from a listbox into the database
if you have a listbox called “department” and want to insert multiple values from the listbox into the database,then:
when the user submits the form,store the value in a variable
$company_dept=$_POST['department'];
query:INSERT into table_name values(’”.join(”,”,$company_dept).”‘)
validate email in javascript
var str = $(”#email”).val();
if((str.indexOf(”.”) > 2) && (str.indexOf(”@”) > 0) && ((str.indexOf(”.”) + 1) < str.length-1)){
alert(”valid”);
}
else{
alert(”Invalid”);
}
Eclipse shortcut
To comment out a line of html code in eclipse IDE , use the following shortcut
ctrl + /
Email check in php
function isValidEmail($email){ return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-] +(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email); }
Make your css dynamic
To implement constants in css , let your php script output as css by passing the following headers :
header(’content-type:text/css’);
header(”Expires: “.gmdate(”D, d M Y H:i:s”, (time()+900)) . ” GMT”);
Using Column alias in where clause
select (basicsal + hra) as salary from employee where salary > 5000
It will give error (Unkown column salary in where clause.
Instead you can use :
select (basicsal + hra) as salary from employee having salary > 5000
Wordpress – different single.php for different categories
if you have a category called photos and another category called videos , you need to format the single.php differently for each category . this is easy and you can just write the following code in single.php :
if ( in_category(’2′) ) {
include(TEMPLATEPATH . ‘/single-kodetricks.php’);
}
else
include(TEMPLATEPATH . ‘/single-blog.php’);
To display 2 decimal after , Javascript
to display 2 decimal after any number use toFixed() function of javascript
eg. var num = 25;
alert(num.toFixed(2));
it will give 25.00 instead of only 25
Website speed
we can minimise all the js and place it in a single file at the end of the project .
this will reduce the number of http requests and save response time
Post A Trick
How does "Kodetricks" work?
We at kodeplay like to share knowledge. With Kodetricks, even you can join us. All you need to do is post a programming related trick if you have one or rate a trick if you like someone else's.
