Monday 10 December 2012

JavaScript function to Validate Email


function validateEmail(address){
var flag=true;
if(address==""){
//** field is blank
flag=false;
} else{
var objRegExp  = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,3}(\.[a-z]{2}){0,2})$/i;
var emaildomain=new Array("com","net","org","edu","in","mil","gov","arpa","biz","aero","name","coop","info","pro","museum");
var suffix =address.substring(address.lastIndexOf('.')+1);
if(emaildomain.indexOf(suffix) != -1){
flag=true;
} else{ flag=false; }

if(objRegExp.test(address) == false) {
flag=false;
}
if (address.indexOf('@.',0) != -1) {
flag=false;
}
if (address.indexOf('.@',0) != -1) {
flag=false;
}
if (address.indexOf('..',0) != -1) {
flag=false;
}
}
return flag;
}   

Tuesday 4 December 2012

Differences between PHP4 and PHP5

Here's a quick overview of what has changed between PH4 and PHP5. PHP5 for the most part is backwards compatible with PHP4, but there are a couple key changes that might break your PHP4 script in a PHP5 environment.

Passed by Reference

This is an important change. In PHP4, everything was passed by value, including objects. This has changed in PHP5 -- all objects are now passed by reference.

Class Constants and Static Methods/Properties

You can now create class constants that act much the same was as define()'ed constants, but are contained within a class definition and accessed with the :: operator.
Static methods and properties are also available. When you declare a class member as static, then it makes that member accessible (through the :: operator) without an instance. (Note this means within methods, the $this variable is not available)In PHP5, all constructors are named __construct(). That is, the word construct prefixed by two underscores. Other then this name change, a constructor works the same way.
Also, the newly added __destruct() (destruct prefixed by two underscores) allows you to write code that will be executed when the object is destroyed.
PHP5 introduces interfaces to help you design common APIs. An interface defines the methods a class must implement. Note that all the methods defined in an interface must be public. An interface is not designed as a blueprint for classes, but just a way to standardize a common API.
The one big advantage to using interfaces is that a class can implement any number of them. You can still only extend on parent class, but you can implement an unlimited number of interfaces.
The one big advantage to using interfaces is that a class can implement any number of them. You can still only extend on parent class, but you can implement an unlimited number of interfaces.
There is a new error level defined as E_STRICT (value 2048). It is not included in E_ALL, if you wish to use this new level you must specify it explicitly. E_STRICT will notify you when you use depreciated code. I suggest you enable this level so you can always stay on top of things.

Visibility

Class methods and properties now have visibility. PHP has 3 levels of visibility:

Public is the most visible, making methods accessible to everyone and properties readable and writable by everyone.

Protected makes members accessible to the class itself and any subclasses as well as any parent classes.

Private makes members only available to the class itself.

Unified Constructors and Destructor

PHP5 introduces a new unified constructor/destructor names. In PHP4, a constructor was simply a method that had the same name as the class itself. This caused some headaches since if you changed the name of the class, you would have to go through and change every occurrence of that name.

Abstract Classes

PHP5 lets you declare a class as abstract. An abstract class cannot itself be instantiated, it is purely used to define a model where other classes extend. You must declare a class abstract if it contains any abstract methods. Any methods marked as abstract must be defined within any classes that extend the class. Note that you can also include full method definitions within an abstract class along with any abstract methods.

Interfaces

PHP5 introduces interfaces to help you design common APIs. An interface defines the methods a class must implement. Note that all the methods defined in an interface must be public. An interface is not designed as a blueprint for classes, but just a way to standardize a common API.

E_STRICT Error Level

There is a new error level defined as E_STRICT (value 2048). It is not included in E_ALL, if you wish to use this new level you must specify it explicitly. E_STRICT will notify you when you use depreciated code. I suggest you enable this level so you can always stay on top of things.

Friday 19 October 2012

How to parse json data with jquery

Json
JSON stands for JavaScript Object Notation. JSON is lightweight text-data interchange format. now here we are going to parse json response in javascript using jquery ajax.

ajax.php
Here in this file we will write json_encode function to convert php array in json string.


<?php
//** Types of json format
 

//** 1)
$obj['firstname'] = "John";
$obj['lastname'] = "Smith";
$obj['email'] = "john.smith@johnsmith.com";
$response = json_encode($obj);
//** o/p  {“firstname”:"John",”lastname”:”Smith","email":"john.smith@johnsmith.com"}

//** above is a single Literal or one dimensional array format


//** 2) another way
$obj=array('0'=>array('firstname' => "John",'email'=> "john@johnsmith.com", 'address'=>array('city'=>'bangalore','state'=>'karnataka')),
'1'=>array('firstname' => "Smith",'email'=> "smith@johnsmith.com", 'address'=>array('city'=>'delhi','state'=>'delhi'))
);

$response = json_encode($obj);


//** json_encode() Returns the JSON representation of a value


/* o/p -
 [{"firstname":"John","email":"john@johnsmith.com","address":{"city":"bangalore","state":"karnataka"}},{"firstname":"Smith","email":"smith@johnsmith.com","address":{"city":"delhi","state":"delhi"}}]

*/
//** above is multi dimensional array and will reside inside [ ] square brackets
//** Json format must be in “ “ double quote only, both keys and values , “City”:”Bangalore”


print $response ;  //** this $response  will be fetched by calling Ajax function at json.php page

exit();
?>


json.php:

Here we will write Ajax query to fetch json response from ajax.php file. we are using jquery ajax

<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

$.ajax({
url: "axon_test.php",
data: { get_param: 'value' },
cache: false,
dataType: "json",   
    success: function (responseText) {      
  var json = responseText;
   $(json).each(function(i,val){
$.each(val,function(k,v){
          console.log(k+" : "+ v);  //** o/p firstname : John
if(k=="address"){
var obj=v;
console.log(obj.city); //**  o/p Bangalore
}
});
  });

    } //** success ends
}); //** Ajax end

});  //** document ends

 

Important as we are using dataType “json” in Ajax call, so jquery will convert the Json response (json formatted string) into javascript object automatically, we don’t need to use parseJSON(); function.
for single dimensional response responseText = “ [Object] “.
for multi dimensional response responseText  =” [object object]”.
then loop through  responseText and  access individual values.

by using jquery ajax function we don’t need to use eval() also, and work on all browser



//*** without using ajax , we can parse json notation using parseJSON() function

$(document).ready(function() {

var temp='[{"firstname":"sam","ID":"1"},{"firstname":"jQuery","ID":"2"}]';
var temp1=$.parseJSON(temp);
console.log(temp1);
//** o/p  [Object { firstname="sam",  ID="1"}, Object { firstname="jQuery",  ID="2"}]
console.log(temp1.firstname);
//** o/p jquery   “  sam “
});

</script>

Thursday 16 August 2012

To get title of option by Javascript

To get the value of Title of select option by JavaScript , following is the example.

<select id="myinfo" name="myinfo"  onchange="getTitle();">
<option value="">Select</option>
<option value="1" title="aa">First value</option>
<option value="2" title="bb">Second value</option> 
<option value="3" title="cc">Third value</option> 
</select>

<script>
function getTitle(){

        var mylist = document.getElementById(' myinfo ');

var myindex = mylist.selectedIndex;  
               //** 0,1,2,3....are index option, starting from 0
              //** myindex will contain numeric value of Index of selected text
var mytitle= mylist.options[myindex].title;
   
         alert(mytitle);
}
</script>

suppose if we select " Second Value " in myinfo then "bb" will get alerted by the above function.

Thursday 15 March 2012

What is REST

REST is a term coined by Roy Fielding in his Ph.D. to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer.


Why is it called Representational State Transfer?

The Web is comprised of resources. A resource is any item of interest. For example, the Boeing Aircraft Corp may define a 747 resource. Clients may access that resource with this URL:
http://www.boeing.com/aircraft/747
A representation of the resource is returned (e.g., Boeing747.html). The representation places the client application in a state. The result of the client traversing a hyperlink in Boeing747.html is another resource is accessed. The new representation places the client application into yet another state. Thus, the client application changes (transfers) state with each resource representation --> Representational State Transfer!
Here is Roy Fielding's explanation of the meaning of Representational State Transfer:
"Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use."

REST is not a standard. You will not see the W3C putting out a REST specification. You will not see IBM or Microsoft or Sun selling a REST developer's toolkit. Why? Because REST is just an architectural style. You can't bottle up that style. You can only understand it, and design your Web services in that style. (Analogous to the client-server architectural style. There is no client-server standard.)
Here are the characteristics of REST
  • Client-Server: a pull-based interaction style: consuming components pull representations.
  • Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.
  • Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
  • Uniform interface: all resources are accessed with a generic interface (e.g., HTTP GET, POST, PUT, DELETE).
  • Named resources - the system is comprised of resources which are named using a URL.
  • Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
  • Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.

Principles of REST Web Service Design

1. The key to creating Web Services in a REST network (i.e., the Web) is to identify all of the conceptual entities that you wish to expose as services. Above we saw some examples of resources: parts list, detailed part data, purchase order.
2. Create a URL to each resource. The resources should be nouns, not verbs. For example, do not use this:
http://www.parts-depot.com/parts/getPart?id=00345
Note the verb, getPart. Instead, use a noun:
http://www.parts-depot.com/parts/00345
3. Categorize your resources according to whether clients can just receive a representation of the resource, or whether clients can modify (add to) the resource. For the former, make those resources accessible using an HTTP GET. For the later, make those resources accessible using HTTP POST, PUT, and/or DELETE.
4. All resources accessible via HTTP GET should be side-effect free. That is, the resource should just return a representation of the resource. Invoking the resource should not result in modifying the resource.
5. No man/woman is an island. Likewise, no representation should be an island. In other words, put hyperlinks within resource representations to enable clients to drill down for more information, and/or to obtain related information.
6. Design to reveal data gradually. Don't reveal everything in a single response document. Provide hyperlinks to obtain more details.
7. Specify the format of response data using a schema (DTD, W3C Schema, RelaxNG, or Schematron). For those services that require a POST or PUT to it, also provide a schema to specify the format of the response.
8. Describe how your services are to be invoked using either a WSDL document, or simply an HTML document.

Monday 12 March 2012

Creating Widgets for WordPress 2.8 and above


In this example we are going to create a widget called "Sample_Widget" and tell PHP that it is going to extend (inherit from) the WP_Widget class. It is the WP_Widget class which makes your widget function, have settings and allow multiple instances so you don't have to.
You will need to rename every occurrence of "Sample_Widget" with the name of your widget.
The first method, Sample_Widget() in the example, is the class constructor which contains the code that is run every time the widget is loaded – either when activated, used on a page, updated and so on.
The second method, form(), contains the settings page on the WordPress widgets administration screen (Appearance -> Widgets). This method is always called form and never changes. Within this function you add all the controls that will appear when the widget options are expanded. See below for an example.
The third method, update(), is called when the user click on "save" from the settings page on the widgets administration screen. This automatically handles saving to the database of options. You can use this function to validate information prior to being saved. See the example below for basic operation.
Finally the widget() function contains the code that will be rendered to the sidebar when the widget is added. This is what your visitors will see when viewing your page.


Let's have a look at a very simple example "Hello World" widget.

Create SampleWidget.php inside /Wp_content/Plugins  folder


<?php
/*
Plugin Name: Sample WordPress Widget
Plugin URI: http://azuliadesings.com/
Version: 1.0
Description: How to create a WordPress Widget
Author: Tim Trott
Author URI: http://azuliadesings.com/
*/

class Sample_Widget extends WP_Widget
{
  function Sample_Widget()
  {
    /* * The first method, Sample_Widget() in the example, is the class constructor which contains the code that is run every time the widget is loaded – either when activated, used on a page, updated and so on.*/
    $widget_ops = array('classname' => 'Sample_Widget', 'description' => 'My Sample Widget Description');
    $this->WP_Widget('Sample_Widget', 'My Sample Widget', $widget_ops);
  }

  function form($instance)
  {
/* *The second method, form(), contains the settings page on the WordPress widgets administration screen (Appearance -> Widgets). This method is always called form and never changes. Within this function you add all the controls that will appear when the widget options are expanded. */
    $instance = wp_parse_args((array) $instance, array( 'title' => '' ));
    $title = $instance['title'];
?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
  } 
  function update($new_instance, $old_instance)
  {
/* The third method, update(), is called when the user click on "save" from the settings page on the widgets administration screen. This automatically handles saving to the database of options. You can use this function to validate information prior to being saved. See the example below for basic operation.
*/
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  } 
  function widget($args, $instance)
  {
/*the widget() function contains the code that will be rendered to the sidebar when the widget is added. This is what your visitors will see when viewing your page.
*/
    extract($args, EXTR_SKIP); 
    echo $before_widget;
    $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']); 
    if (!empty($title))
      echo $before_title . $title . $after_title;; 
    // ** Do Your Widgety Stuff Here...
    echo "<h1>Hello World</h1>"; 
    echo $after_widget;
  }
}
add_action( 'widgets_init', create_function('', 'return register_widget("Sample_Widget");') ); 
?>


How To Create WordPress Widgets

Wordpress plugins are pieces of addon code that extend the functionality of Wordpress, either behind-the-scenes or extra visual code. Widgets allow these code segments to be quickly and easily added to predefined sidebars on most themes. Before WordPress version 2.0, these extra visual plugins had to be hand coded into the theme template, so knowledge of PHP was required. In version 2.0 they introduced "Widgets" which wrap around a plugin and allow a non code editing method for incorporating into a theme using sidebars and a drag and drop interface. This tutorial covers creating a Widget, creating a plugin widget, adding sidebars to a theme, and upgrading a non-widget plugin.

Creating a Simple WordPress Plugin

<?php

/*

Plugin Name: Hello World

Plugin URI: http://example.com/

Description: Sample Hello World Plugin

Author: Deep

Version: 1

Author URI: http://example.com/

*/


function sampleHelloWorld() {

  echo "<h2>Hello World</h2>";

}

?>


The lines inside /* and */ are used by WordPress to find out about the plugin. We have one function called sampleHelloWorld which does exactly that.

Now, traditionally we would have had to open up the sidebar of the theme you are using, find the location of where you want the Hello World displayed, and hard code the function in. Upload to the server and test. If for some reason there is a problem with your plugin (or a third party plugin) then your site would almost certainly stop working. Changing the location from the left to the right sidebar means editing both files accordingly. This isn't very good.

Widgets

Widgets take away the need for editing the sidebar files of a theme and allow for a drag and drop interface in the admin panel. Let's have a look at how we can widget enable our plugin.

Open up the Hello World plugin file again and add these lines.

<?php

function widget_myHelloWorld() {

?>

  <h2 class="widgettitle">My Widget Title</h2>

  <?php sampleHelloWorld(); ?>

<?php

}

function myHelloWorld_init(){

  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');

}

add_action("plugins_loaded", "myHelloWorld_init");

//**Add action just tells WordPress to call myHelloWorld_init when the plugin is loaded.

?>

To make Widget Theme compatible

While this widget will function fine, we can make some improvements to enable greater theme compatibility – not everyone uses the same themes as you test on.WordPress will pass parameters to your widget, which contain information about the sidebar and the CSS classes. We should process these parameters and output the correct tags, or you risk breaking some themes.The first thing we need to do is change our sampleHelloWorld function so that it will accept parameters, then to process these parameters into variables. This is done using the extract function.

function widget_myHelloWorld($args) {

     //** $args had been added as parameter

  extract($args);

?>

  <h2 class="widgettitle">My Widget Title</h2>

  <?php sampleHelloWorld(); ?>

<?php

}


again we change hello world function.

These two lines will allow us to reference some variables and output correct html structure for the theme being used. The most important variables are before_widget, after_widget, before_title and after_title. Previously we have surrounded the widget title with a hard coded H2 tag with a css class widgettitle, but many themes do not support these tags. They may use a div, or a h1 or a span, so we need our widget to be flexible.

function widget_myHelloWorld($args) {

  extract($args);

  echo $before_widget;

  echo $before_title;?>My Widget Title<?php echo $after_title;

  sampleHelloWorld();

  echo $after_widget;

}


//** These changes will allow our plugin to use the same tags as the theme author informs us we need to use, and will allow your widget to look the same as the other widgets in the sidebar.

Complete Plugin:

<?php

/*

Plugin Name: Hello World

Plugin URI: http://azuliadesigns.com/

Description: Sample Hello World Plugin

Author: Tim Trott

Version: 1

Author URI: http://azuliadesigns.com/

*/


function sampleHelloWorld()

{

  echo "<h2>Hello World</h2>";

}

function widget_myHelloWorld($args) {

  extract($args);

  echo $before_widget;

  echo $before_title;?>My Widget Title<?php echo $after_title;

  sampleHelloWorld();

  echo $after_widget;

}

function myHelloWorld_init() {

  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');

}

add_action("plugins_loaded", "myHelloWorld_init");

?>

If Theme Does Not Have Widget Enable SideBars. If your theme does not have widget enabled sidebars, this will help make it widget enabled. I am using a very basic sidebar theme, most sidebars are a little more complex than this.

<div id="sidebar">

<ul>

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>

<?php wp_list_pages('title_li=<h2>Pages</h2>' ); ?><br/>

        <li><h2>Archives</h2>

        <ul>

        <?php wp_get_archives('type=monthly'); ?>

        </ul>

       </li>

<?php wp_list_categories('show_count=1&amp;title_li=<h2>Categories</h2>'); ?>

<?php endif; ?>

</ul>

</div>


The first of these lines does an if else statement, if we have a sidebar function call it otherwise we do the existing hard coded sidebar.The second line (endif) tells the if statement where the hard coded sidebar ends. Anything between the first and second lines will be shown if widgets are disabled or no widgets are assigned to the sidebar.Before you can add a widget to this sidebar, we need to make WordPress aware of it by registering it.Open, or create, functions.php in your theme folder, and find (or add) a line like this.

<?php

if ( function_exists('register_sidebars') )

    register_sidebars(1);

?>


Where the parameter to register_sidebars is the number of sidebars defined in your theme. You can have any number of sidebars. Now you will be able to add widgets to your sidebar.

Should you wish to configure the elements that will appear before and after a widget, or the tags that a widget title will appear in, you can setup the options array and pass it to the register_sidebar function.

register_sidebar(array(

'before_widget' => '<li>',

'after_widget' => '</li>',

'before_title' => '<div class="sidebar_title">',

'after_title' => '</div>',

));


//** This will cause the widget to be contained within <li></li> tags and the widget title will be in a div with the css class sidebar_title.

materials supplied by

By  http://azuliadesigns.com/create-wordpress-widgets/

Wednesday 8 February 2012

Cross domain ajax call in javascript

Suppose we had to domain one is client side(http:\\localhost\ My-website) another is server (http:\\example.com\myajax.php). so when ever we call an Ajax request from localhost to another domain an error  “Access Denied” occurs. The reason behind this error is there are few limitations with the browsers security model like we cannot make cross domain XmlHttpRequest and also if we use frames they should be from same domain. So as i am trying to make use of a cross domain url with XmlHttpHandler it is failing.
to overcome this we use a trick.
at localhost\My-website create a file called myhtml.php and insert following code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function somefunction(mydata){
document.write(mydata);
}
</script>
<script src="http://example.com/myajax.php?mydata=sssd"></script>
</head>
<body>
<form id="form1" runat="server">
 <div>
</div>
</form>
</body>
</html> 
Here when the page loads it will call the src and loads output from myajax.php into this page
At server example.com the php page should be as follows

myajax.php
<?php
//$string= "somefunction(\"{name: \'johm\', age:\'".$_GET['mydata']."'}\")";

$string= "somefunction(\"{result:\'".$_GET['mydata']."'}\")";
echo $string;
?>
in this page $string have been assigned value as samefunction with parameters.so as soon as myhtml.php loads the myajaxpage some function will be called with parameter.

now do some real Ajax like thing.
above example is the simple one, now a scenario we want to get name and mail id from example.com server to localhost at regular interval. but we can't use ajax here, so in myhtml.php page we call an iframe myiframe.php which resides in same localhost, inside iframe we are going to write the src for example.com.

localhost\myhtml.php 
<body>
<script>
  setInterval("Callmyiframe()",8000); // runs every interval of time
</script>

function  Callmyiframe(){
var uname;
uname="";
document.getElementById('fbauth_src').contentDocument.location.reload(true);
 // ** reload the iframe " fbauth_src " at each function call , this is important as each reload of iframe  will call the src and thus each time function will execute, same as Ajax call

 var iframe = document.getElementById('fbauth_src');  
//** Iframe id  'fbauth_src'
  
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
uname =innerDoc.getElementById('myusername').value; 
 //hidden field in iframe
if(uname!=""){
document.write(uname);
}
}

<iframe id="fbauth_src" src="http://localhost/myiframe.php';?>"></iframe>
</body>

localhost\myiframe.php 

//** code inside the iframe
<input type="hidden" id="myusername"  name="myusername" value="">
<input type="hidden" id="myuseremail" name="myuseremail" value="">
<script>
function myauthfunction(mydata){
var aa;
var temp;
aa=eval(mydata); //** decode the json data
//document.write(aa);
if(aa!=""){
temp=aa.split("+");
document.getElementById('myusername').value=temp[0]; 

   //** will show deep kumar

 document.getElementById('myuseremail').value=temp[1];
}
}
</script>
<script id="fbauth_src" src=" http://example.com/myajax.php?auth=y&myname=deep"></script>
//** each time the iframe gets loaded , src gets called and myauthfunction() gets executed.

http\\example.com\myajax.php
<?php
$myauth=$_REQUEST['auth']; \\ ** will show y
$myname=$_REQUEST['myname']; \\ ** will show deep
\\** write some SQL queries here also
$str=$myname."kumar + deepkumar@yahoo.com";

$string= "myauthfunction(\"{data:\'".$str."'}\")"; \\** Json format
echo $string;
?>



Monday 6 February 2012

To add script Tag inside a script


To add <script> Tag inside a <script> Tab via Jquery. we are going to insert <script> inside test111 Div at run time.

$content_top='<div id=test111> gdgdf </div>';

$adbanners='<script> jQuery(document).ready( function($) {
$("body").prepend("'.$content_top.'");

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://gist.github.com/1265374.js?file=GetGists.js";
document.write.to = {filename: script.src};
document.getElementById("test111").appendChild(script);

});

</script>';

echo $adbanners;

//** Now add a div after <body> and add script to show Banners in WordPress
At WordPress Plugin file's main page add following hook function
add_action('wp_head', 'my_plugin_topbanner1');
then write the function definition inside the same file

//*** Adding Top banner just after <body>  tag
function my_plugin_topbanner1(){
global $post,$wpdb;
$page="";
$banner=array();
$plugin_url = plugins_url()."/adbanner/images/";
        //** plugins_url() WP function shows the current plugin path
$result = get_option('addbanner_pos');
$banner1=$result;
$banner=json_decode($banner1);
if(is_home()){
$page='home';
}
elseif(is_page()){
$page='page';
}
elseif(is_search()){
$page='search';
}
else{
//default post page
$page='post';
}
if(!empty($page)){
$adbanners="";
$styles="";
$result=$banner->$page;
$temp_banner="";
for($i=0;$i<count($result->content_top);$i++){
if($result->content_top[$i]->position=='ct1'){
$wd=$result->content_top[$i]->width;
$ht=$result->content_top[$i]->height;
$ord1=mt_rand();
$styles="<style>#ct1_ss{overflow:hidden;margin:auto;top:1px;width:".$wd."px;height:auto;padding:1px 0 3px 10px;position:relative}</style>";
$adbanners=$styles."<div id='ct1_ss'><script>document.write('<script language=\"JavaScript\" src=\"http://ad.doubleclick.net/adj/rmm.rmmcreative/delltest_".$wd."x".$ht."exp;sz=".$wd."x".$ht.";ord=".$ord1."?\" type=\"text/javascript\"></scr' + 'ipt>');</script></div>";

}


}
}
echo $adbanners;
}


//** above function will add html code in Wordpress theme blog as follows
<body>
<div id=ct1_ss><script language=Javascript src=http://ad.addouble...></script>
</div>
</body>
Also that script will Run and Load the External URL and will show Ads Images.

Thursday 19 January 2012

How to write sql query and form in wordpress plugin at admin end

When writing plugins, it's a good idea to keep your data-handling within the plugin's main file (i.e. not sending it to a separate file), and activate functions to handle it accordingly. Basically, you can set your form's action to point to either the plugin's file, or the page that contains the form. else following error will occur.

Fatal error: Call to a member function get_results() on a non-object (jQuery From Plugin & WordPress)
the main plugin file which appear as plugin page , always write sql quries there you need put some flag $_POST['flag'] to distingush quries coming from which section.

<form id="frmfbdata" name="frmfbdata" method="POST" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
 <input type="text" id="username"  name="username" value="">
 <input type="text" id="useremail" name="useremail" value="">
 <input type="text" name="fconnect" id="fconnect" value="y">
 </form>
 
global $wp_table,$wpdb;
$email=$_POST['email'];
$name=$_POST['name'];
if($email!=""){
 $querystr = "SELECT count(*)as cnt FROM $wpdb->options WHERE $wpdb->options.option_name = 'addbanner'";
 $result = $wpdb->get_results($querystr);
 //**Array ( [0] => stdClass Object ( [cnt] => 0 ) )

$recordcount=$result[0]->cnt;
 if($recordcount==0){
  $mydata=array();
  $mydata['email']=$email;
  $mydata['name']=$name;
  $data=json_encode($mydata);
  $query = "INSERT INTO $wpdb->options SET blog_id='0',option_name='addbanner',option_value='".$data."',autoload='no'";
  $wpdb->get_results($query);
 }
}


ajax query to a page works but if sql query is written it shows fatal error
 
function
var name=document.getElementById("username").value;
var email=document.getElementById("useremail").value;
document.getElementById('frmfbdata').submit();
var ajaxurl = "<?php bloginfo('wpurl') ?>/wp-content/plugins/addbanner/myajax.php";
var data = {
email: email,
name: name
};


//** since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php

jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});

}callajax(){

FaceBook Fconnect with SDK

<div id="fb-root"></div>
        <script type="text/javascript">
            var button;
            var userInfo;

            window.fbAsyncInit = function() {
                FB.init({ appId:  'APP_API_ID',
                    status: true,
                    cookie: true,
                    xfbml: true,
                    oauth: true});

               showLoader(true);

               function updateButton(response) {
                    button       =   document.getElementById('fb-auth');
                    userInfo     =   document.getElementById('user-info');

                    if (response.authResponse) {
                        //user is already logged in and connected
                        FB.api('/me', function(info) {
                            login(response, info);
                        });

                        button.onclick = function() {
                            FB.logout(function(response) {
                                logout(response);
                            });
                        };
                    } else {
                        //user is not connected to your app or logged out
                        button.innerHTML = 'Login';
                        button.onclick = function() {
                            showLoader(true);
                            FB.login(function(response) {
                                if (response.authResponse) {
                                    FB.api('/me', function(info) {
                                        login(response, info);
                                    });
                                } else {
                                    //user cancelled login or did not grant authorization
                                    showLoader(false);
                                }
                            }, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
                        }
                    }
                }

                // run once with current status and whenever the status changes
                FB.getLoginStatus(updateButton);
                FB.Event.subscribe('auth.statusChange', updateButton);
            };
            (function() {
                var e = document.createElement('script'); e.async = true;
                e.src = document.location.protocol
                    + '//connect.facebook.net/en_US/all.js';
                document.getElementById('fb-root').appendChild(e);
            }());

            function login(response, info){
                if (response.authResponse) {
                    var accessToken                                 =   response.authResponse.accessToken;

                    userInfo.innerHTML                             = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
                                                                     + "<br /> Your Access Token: " + accessToken;
                    button.innerHTML                               = 'Logout';
                    showLoader(false);
                    document.getElementById('other').style.display = "block";
                }
            }

            function logout(response){
                userInfo.innerHTML                             =   "";
                document.getElementById('debug').innerHTML     =   "";
                document.getElementById('other').style.display =   "none";
                showLoader(false);
            }

            //stream publish method
            function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
                showLoader(true);
                FB.ui(
                {
                    method: 'stream.publish',
                    message: '',
                    attachment: {
                        name: name,
                        caption: '',
                        description: (description),
                        href: hrefLink
                    },
                    action_links: [
                        { text: hrefTitle, href: hrefLink }
                    ],
                    user_prompt_message: userPrompt
                },
                function(response) {
                    showLoader(false);
                });

            }
            function showStream(){
                FB.api('/me', function(response) {
                    //console.log(response.id);
                    streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
                });
            }

            function share(){
                showLoader(true);
                var share = {
                    method: 'stream.share',
                    u: 'http://thinkdiff.net/'
                };

                FB.ui(share, function(response) {
                    showLoader(false);
                    console.log(response);
                });
            }

            function graphStreamPublish(){
                showLoader(true);

                FB.api('/me/feed', 'post',
                    {
                        message     : "I love thinkdiff.net for facebook app development tutorials",
                        link        : 'http://ithinkdiff.net',
                        picture     : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
                        name        : 'iOS Apps & Games',
                        description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'

                },
                function(response) {
                    showLoader(false);

                    if (!response || response.error) {
                        alert('Error occured');
                    } else {
                        alert('Post ID: ' + response.id);
                    }
                });
            }

            function fqlQuery(){
                showLoader(true);

                FB.api('/me', function(response) {
                    showLoader(false);

                    //http://developers.facebook.com/docs/reference/fql/user/
                    var query       =  FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
                    query.wait(function(rows) {
                       document.getElementById('debug').innerHTML =
                         'FQL Information: '+  "<br />" +
                         'Your name: '      +  rows[0].name                                                            + "<br />" +
                         'Your Sex: '       +  (rows[0].sex!= undefined ? rows[0].sex : "")                            + "<br />" +
                         'Your Profile: '   +  "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
                         '<img src="'       +  rows[0].pic_small + '" alt="" />' + "<br />";
                     });
                });
            }

            function setStatus(){
                showLoader(true);

                status1 = document.getElementById('status').value;
                FB.api(
                  {
                    method: 'status.set',
                    status: status1
                  },
                  function(response) {
                    if (response == 0){
                        alert('Your facebook status not updated. Give Status Update Permission.');
                    }
                    else{
                        alert('Your facebook status updated');
                    }
                    showLoader(false);
                  }
                );
            }

            function showLoader(status){
                if (status)
                    document.getElementById('loader').style.display = 'block';
                else
                    document.getElementById('loader').style.display = 'none';
            }

        </script>

        <h3>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</h3>
        <button id="fb-auth">Login</button>
        <div id="loader" style="display:none">
            <img src="ajax-loader.gif" alt="loading" />
        </div>
        <br />
        <div id="user-info"></div>
        <br />
        <div id="debug"></div>

        <div id="other" style="display:none">
            <a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
            <a href="#" onclick="share(); return false;">Share With Your Friends</a> |
            <a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
            <a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>

            <br />
            <textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
            <br />
            <a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>
        </div>

materials supplied by