How to Add Magento JQuery/Ajax Add-To-Cart

December 26, 2009 · 18 Comments
Filed under: Featured, JavaScript, JQuery, Magento Cart 

So, Ajax being the thing and all, I was hunting for a way to add an item to the cart using an Ajax call in Magento.  Recently, I noticed there was a module that apparently does this, but either I hadn’t seen that or it didn’t exist yet when I wrote this, so I hacked my way through it.

PHP isn’t my primary language – I come from the ASP, ASP.Net, C# world, but Magento was compelling enough that I’ve taken the leap.  I’m sure there are lots of things I could be doing better/differently here so if you’ve got some suggestions, I’m all ears!

Add to Cart Page

So first I needed an “Add to Cart” page (called – addToCart.php) that could be called from the client.  This page returns a result in JSON format.  The actual page also returns related items so we can try to cross sell the user, but I’ve removed that in this sample to make it simpler.

<?php

include_once '../app/Mage.php';

Mage::app();

try{
// usage /scripts/addToCart.php?product_id=838&amp;amp;amp;amp;amp;amp;amp;amp;amp;qty=1
// product_id OR sku is required

// get query string
if (!isset($_GET['sku'])) { $sku = ''; } else { $sku = $_GET['sku']; }
if (!isset($_GET['product_id'])) { $product_id = ''; } else { $product_id = $_GET['product_id']; }
if (!isset($_GET['qty'])) { $qty = '1'; } else { $qty = $_GET['qty']; }

if ($sku != ""){
$product_id = Mage::getModel('catalog/product')->getIdBySku("$sku");
if ($product_id == '') {
$session->addError("Product Not Added
The SKU you entered ($sku) was not found.");
}
}

$request = Mage::app()->getRequest();

$product = Mage::getModel('catalog/product')->load($product_id);

$session = Mage::getSingleton('core/session', array('name'=>'frontend'));
$cart = Mage::helper('checkout/cart')->getCart();

$cart->addProduct($product, $qty);

$session->setLastAddedProductId($product->getId());
$session->setCartWasUpdated(true);

$cart->save();

$result = "{'result':'success'}";

echo $result;

} catch (Exception $e) {
$result = "{'result':'error'";
$result .= ", 'message': '".$e->getMessage()."'}";
echo $result;
}

Buy Now Button

Then I need a “Buy Now” button that doesn’t do a post to the server that I can attach my jQuery code to.  I’ve added the sku as an attribute to the anchor because I have this in a page that has more than one product on the page and I need to know which product has been selected.




<a href="#" sku="<?php echo $this->__($product->sku) ?>"><img src="/media/upload/image/product-details/buy-now.jpg" border=0 alt="<?php echo $this->__('Buy Now') ?>"></a>

Client Script

Finally, I need the client script that gets attached to the button and calls the server “addToCart.php” page.

/* Cart */
jQuery(document).ready(function($) {
$.ui.dialog.defaults.bgiframe = true;

$(".add-to-cart").click(function(e){
var buyNow = $(e.currentTarget);
var listingItem = $(buyNow).closest(".listing-item");
var colorSelector = $("#colorSelector", listingItem);
var product_id = colorSelector.val();

if (product_id == ""){
showDialog("Please select a color.", "Missing Information");
return false;
}

var stockStatus = $("option:selected", colorSelector).attr("stockstatus");
if (stockStatus == "out of stock"){
showDialog("Sorry, that colour is currently unavailable.", "Out of Stock")
return false;
}

var qty = $("#quantity", listingItem).val();

if (qty == ""){
qty = "1";
}

$(this).siblings(".ajax-loader").show();
var obj = this;

var params = "product_id=" + product_id + "&amp;amp;amp;amp;amp;qty=" + qty;

var result = $.getJSON("/scripts/addToCart.php", params, function(data, textStatus){
$(obj).siblings(".ajax-loader").hide();

if (textStatus == "error"){
showDialog("There was an error adding this item to your cart.  Please call customer service for assistance.", "Error");
return;
}

if (data.result == "error"){
showDialog("Sorry, an error occurred while adding the item to your cart.  The error was: '" + data.message + "'");
return;
}

// SHOW FEEDBACK, ERRORS AND RELATED ITEMS
} // end add to cart

function showDialog(msg, title){
$("#dialog").dialog( 'destroy' );
$("#dialog").html(msg);

$("#dialog").dialog({
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
// , closeOnEscape: true
// , show: 'slide'
});

$('#dialog').dialog('option', 'title', title);
$("#dialog").dialog('open');
}
});

Few things probably need some explanation:
1. I’ve attached the function to ALL add to cart buttons using the “add-to-cart” class.  (There are multiple products on the page.)
2. Each product has a color selector that has the product_id as the value in the drop down.  There’s also an additional attribute called “stockstatus” that will let me know if the color is out of stock.  My customer didn’t want to hide the out of stock colors, but I obviously can’t let anyone order them.
3. I put a little animated gif (the “ajax loader”) on the page and that gets displayed when the ajax call is being made.
4. If there is an error, I display it using the jQuery UI library and a little showdialog helper function.
5. There’s a feedback panel that shows related items, but I’ve removed that in this code just to make it easier to follow.
So there it is.  Hope this helps someone.  And if there are better ways to do this, I’d love to hear them!
[Update:  I removed the reference to common.php in the code above because it’s not needed.  It had some common user functions in it that aren’t necessary for this sample]

registration form validation using ajax with php

November 2, 2009 · Leave a Comment
Filed under: Featured, JavaScript 
  
 false, 'msg' => "Please specify a username");
        } else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
            $resp = array('ok' => false, "msg" => "Your username can only contain alphanumerics and period, dash and underscore (.-_)");
        } else if (in_array($username, $taken_usernames)) {
            $resp = array("ok" => false, "msg" => "The selected username is not available");
        } else {
            $resp = array("ok" => true, "msg" => "This username is free");
        }

        return $resp;
    }
?>

      Ajax - PHP example

      
Input text: Output text:
hello.... i want to do the validations in registration form. but my validation is when the user enters the value in textbox that value automatically cheks that value is already in database or not. for example..........username textbox is there..now i am entering value first three letter "kal" then comes beside the textbox "username 'kal' is available for you". and next i am entering nextletter "kalp" then comes beside the textbox "kalp is available". plz help me.....any chances to do this task.

Ajax Auto Complete Textbox

November 2, 2009 · Leave a Comment
Filed under: Featured, JavaScript 

Ajax Auto Complete Textbox using ASP.Net AjaxControlToolKit

To improve the user experience a lot of Ajax enabled functionlities are there, but AutoComplete dropdown for the textbox in the ASP.net is the best amont them. However if the Auto Complete is not responsive, the users will feel that it is troublesome rather than the useful. We planned for light weight solution. Ended up with this WebService based approach than a Webpage to fetch the data along with heavy Heavy HTTP response.

WebService And Auto Complete
Data is transferred from application server to JavaScript using a WebService. Hence the data transfer between server and client is very minimal. Add some animations to improve usablity and it is very easy with AutoCompleteExtender.

Once downloaded, create a new website and select the Default.Aspx and then switch to design mode in the Web Form for designing the page.

1)Add a web service named AutoComplete.asmx

2)Import AjaxControlToolkit

3)Add a new function named as GetProducts with the required parameters(prefixText,count)

4)now get a datareader to fill up the Array list.

5)Fill up the AutoCompleteExtender with the web service and web method we created just now.

For Complete working source code with step by step procedure please refer here (Ajax AutoComplete Textbox with Database).

Note:This article needs Ajax Control kit. It needs to be downloaded separately.

Ajax powered city state Dropdown

October 30, 2009 · Leave a Comment
Filed under: Featured, JavaScript 

In this post I am going to show you, how  you can use ajax to populate a dropdown, on the basis of value selected in some other dropdown. As the web is growing bigger and every site adds much better functionality to its forms. This sort of ajax populated dropdowns are pretty common and are handy to use. You can see the demo of this example below, choose a state it will populate the corresponding list of cities in the city dropdown.

Excited to see the code ? So let us now move to the code which is powering the above demoed ajax dropdowns. This script has three parts, HTML, Javascript (embeded Ajax functionality), PHP (serverside script to return the fresh data).

Note: For this example I am using a simple array in PHP script to return list of cities, but while implementing the script you can change the data source to database or something. All you have to make sure is that you return something to which can be handled by Javascript function.

Here is the HTML and Javascript code.

<html>
  <head>
    <title>Demo of City/State via Ajax</title>
    <script type="text/javascript">
      //define the absolute path to your php script here
      var site_root='';

      //function to create ajax object
      function pullAjax(){
        var a;
        try{
          a=new XMLHttpRequest()
        }
        catch(b)
        {
          try
          {
            a=new ActiveXObject("Msxml2.XMLHTTP")
          }catch(b)
          {
            try
            {
              a=new ActiveXObject("Microsoft.XMLHTTP")
            }
            catch(b)
            {
              alert("Your browser broke!");return false
            }
          }
        }
        return a;
      }
      //this function does the ajax call, and appends cities into the second dropdown
      function populate_cities(x)
      {
        obj=pullAjax();
        var cities_list=document.getElementById('city');
        obj.onreadystatechange=function()
        {
          if(obj.readyState==4)
          {
            //returns comma separated list of cities after successful ajax request
            var tmp=obj.responseText;
            //split function returns array of city
            cities=tmp.split(',');
            //if second dropdown already has some data, CLEAR it
            if(cities_list.length>1)
              clean_cities(cities_list);
            //for loop to append the cities 
            var i=0;
            for(i=0;i<cities.length;i++)
              append_city(cities[i]);
          }
        };
        obj.open("GET",site_root+"cities_data.php?state="+x.value,true);
        obj.send(null);
      }
      //this gets call in the for loop and creates the options for the dropdown
      function append_city(city_value)
      {
        var cities_list=document.getElementById('city');
        cities_list.options[cities_list.options.length]=new Option(city_value,city_value,false,false);
      }
      //CLEARs the dropdown
      function clean_cities()
      {
        var cities_list=document.getElementById('city');
        cities_list.options.length=1;
      }
      //autoloads the city list, when the page first loads
      function autoload()
      {
        populate_cities(document.getElementById('state'));
      }

    </script>
  </head>
  <body onload="autoload();">
    <p>Choose a State:&nbsp;<select id="state"  onchange="populate_cities(this);">
        <option>California</option>
        <option>Alaska</option>
        <option>New York</option>
        <option>New Jersey</option>
      </select></p>
    Choose a City:&nbsp;<select id="city">
      <option>Choose City...</option>
    </select>
  </body>
</html>

Here is the PHP code snippet. Data source for this PHP script is an array, but it can be changed (as mentioned above) depending upon the need.

<?php

$state=trim($_GET['state']);
//if state is end empty, return blank
if($state=='')
  return '';

$data=array(
    'California'  =>  array('San Francisco','South Gate ','South El Monte','Santa Clara','Roseville','Albany'),
    'Alaska'  =>  array('Eagle','Deering','Nome','Russian Mission','St. Paul','Whittier','Valdez','Sand Point'),
    'New York'  =>  array('Albany','Buffalo','Troy','Geneva','Beacon','Johnstown','Hudson','Cortland','Lockport','New York City'),
    'New Jersey'  =>  array('Jersey City','Newark','Elizabeth','Old Bridge','Howell','Atlantic City','Ewing','Fort Lee','Burlington'),
);
//return comma seperated list of cities
echo implode(',',$data[$state]);
?>

Now let me delve you into its concept and help you to understand how this whole script works.

When you select a state from the first dropdown, an event “onchange” is fired and the function populate_cities is called. This function is responsible of creating request object (using function pullAjax() ) which makes the Ajax call possible.

Ajax call sends the state name as GET parameter to PHP file cities_data.php . The state parameter is sent via javascript which is selected from our first dropdown.

The above Ajax file returns a comma separated list of cities corresponding to the state received as the parameter. In an ideal scenario you might want to query database using state field as the parameter in where clause of your selct query. A generic query which be something like:

Select * from countries where state=’$state’;

This comma separated list of cities is received as response by the same Javascript function. In Javascript function we are using split() function to convert CSV into an array. This array is then iterated and with and append_city function creates options for the second dropdown which seems to be populated then.

We have two supporting functions as well in the script called clean_cities() and autoload(). clean_cities() function is used to clear the cities dropdown, because when the new cities are being populated, the old cities must not be present there as they are from different state. autoload() function is another utility function which populates the cities in the second dropdown by sending an Ajax request, as soon the page finishes loading. That is why autoload() gets called on the onload event.

The code is self-explanatory, you can get the guidance from the inline comments given within the code. If you still face problems running this example, leave a comment, will try to reply you back.

This is a basic example to show you how you can make things smoother and more interactive using Ajax in your coding practice. You can add few more validations using PHP and Javascript to make this script robust and fail proof.

Hope it saves your day !

Stay Digified !!

Sachin Khosla

QTP support for Silverlight, AJAX, GWT, Dojo, YUI now available

October 13, 2009 · Leave a Comment
Filed under: Dojo Toolkit, Featured, JavaScript 

There has been no out-of-the-box support for most of the Web2.0 technologies by any of the tools providers out there. SilverlightLooks like HP has decided to go full force into it and capture all the more commercial functional testing tools market that was already dominated by them.  **HP is now planning to release a Web2.0 pack. The highlights of which will be:

  1. Making Web-Extensibility easier to use : Good to know HP acknowledge this fact. I have not seen much happening around this area, though it has been good 2+ yrs (the release of v9.5) since they made extensibility available. It will be a framework by the name Extensibility Accelerator (EA). AJAX
  2. Tighter support for Web2.0 apps : Till now, QTP had a Flex addin (by Adobe), now QTP is going to support Silverlight and AJAX apps.
  3. Better Object recognition and record/replay capabilities for Web 2.0 apps

Read the full article here

** Update: HP has already released the patch on top of QTP 10.0  This patch provides support for Silverlight 2-3 (under .NET addin),  and various toolkits – like AJAX, Google Web Toolkit (GWT), Dojo Toolkit, and Yahoo User Interface- under Web Extensibility. Once you have the Extensibility Accelerator installed, it can be seen under Tools menu option on QTP’s IDE.

The patch is released in two flavors:

  1. Web 2.0 Feature Pack with PreRequisites – In case you do not have MS Studio 2008 SP1 and .NET framework
  2. Web 2.0 Feature Pack without PreRequisites – In case you already have the above two softwares installed.

Fly To Basket – Ajax Script

October 11, 2009 · Leave a Comment
Filed under: Featured, JavaScript 

Configuration

This is the HTML for products on the page

<div id="slidingProduct1">
  <img src="images/product.gif"/>
  Calendar<br />
  50.00
</div>
<a href="#" onclick="addToBasket(1);return false;"><img src="images/basket.gif"/></a>

There are two important things you have to notice here:
  • The id of the div have to be slidingProduct , example: slidingProduct1 for the product with ID “1″ in your database. . This is the div that will “fly” to the basket.
  • Call the function addToBasket( ) to add products to the basket. Example: addProduct(1) to add product with ID=1 to the basket
addProduct.php This is a PHP file which is called by Ajax when a product is added to the basket(It’s not required to use PHP. You can create it in ASP, JSP or other server side language). This file receives a variable named “productId”. Then, this file should update the content of the shopping basket in a database. Finally, it outputs a string in the following format:
product ID|||Product description|||product price

I.e.: product ID, 3 pipes, product description, 3 pipes and finally the price of the product
removeProduct.php

This PHP file is used to remove products from the shopping basket. Input to this file is a GET variable named

productIdToRemove

What you have to do inside this PHP file is to subtract one item of this product from the basket(i.e. in the Database). Then output the string “OK” if the update was executed successfully.
Javascript variables

At the top of the fly-to-basket.js file, you will find 3 variables which you can modify:

var flyingSpeed = 25;
var url_addProductToBasket = 'addProduct.php';
var txt_totalPrice = 'Total: ';

flyingSpeed is used to control how fast your products flies to the basket.

url_addProductToBasket is where you put the url to your server side files(i.e. addProduct.php).

txt_totalPrice is a text label shown at the bottom of the shopping basket in front of the total price.
showAjaxBasketContent function

Inside fly-to-basket.js you will find a function with the name showAjaxBasketContent. This function updates the text in the right column, i.e.the shopping cart. I have added some comments to code in this function in case you need to modify it.
Showing existing basket items

When someone navigates on your page, you have to write out the existing basket items from your database. The demo isn’t connected to a database, so when you refresh the page, the basket at the right side will be empty. This is the HTML code for the shopping basket in the right column:

<table id="shopping_cart_items">
  <tr>
    <th>Items</th>
    <th>Description</th>
    <th>Price</th>
    <th></th>
  </tr>
  <!-- Here, you can output existing basket items from your database
  One row for each item. The id of the TR tag should be shoping_cart_items_product + productId,
  example: shoping_cart_items_product1 for the id 1 -->

</table>

If there’s allready items in the basket, you have to add rows to this table, example:

<tr id="shoping_cart_items_product1">
  <td>1</td>
  <td>Calendar</td>
  <td>50.00</td>
  <td><a href="#" onclick="removeProductFromBasket(1);return false;"></a></td>
</tr>

Demo: http://www.dhtmlgoodies.com/scripts/fly-to-basket/fly-to-basket.html

Download: http://www.dhtmlgoodies.com/scripts/fly-to-basket/fly-to-basket.zip

Source: http://www.dhtmlgoodies.com/index.html?whichScript=fly-to-basket

How to Ajax ModalPopup Extender in Asp.Net GridView Control

October 3, 2009 · Leave a Comment
Filed under: ASP.NET, ASP.NET 2.0, Featured, JavaScript 
Introduction
This article helps you more to explore the ModalPopup Extender integrated with Asp.Net GridView control. By reading this article, you will understand the way to show dynamic data in the ModalPopup, edit the data in the ModalPopup extender and save it into database by making a postback.
What we are going to do?

The basic idea of this article is to fetch data from the database, bind it with Asp.Net GridView control, and then we are going to show the values in the server controls placed in the ModalPopup extender and perform an edit/update function from the ModalPopup extender itself. To achieve this, we are going to use WebService which will return the required data as XML, this XML data is captured in the client-side by JavaScript’s XMLDOM object, then we are going to process the XML to fill the controls in the ModalPopup extender. These data can be changed and on postback, these data will be saved in the database. You can place any server controls in the ModalPopup extender.

Sample Scenario

For demonstration, we are going to use customer information from a table called Customers. The primary key column is customer code and its field name is ‘Cus_Code’. The other columns in the customer table is customer name [Cus_Name], Gender [Cus_Gender], City[Cus_City], State [Cus_State] and Customer Type [Cus_Type]. We are going to use TextBox, DropDownList and HiddenField controls in the ModalPopup extender to manipulate these data.

Make GridView control

In your Ajax enabled website’s aspx page, add a GridView control in it and set the DataKeyNames to your primary key (in this case it is Cus_Code), and bind it with your Data source control. Or if you want to bind the GridView control from code-behind, create a private method to fetch data from the database and bind it as follows

private void FillGridViewWithCustomerInfo()
{
string sql = “Select * from customers”;
SqlDataAdapter da = new SqlDataAdapter(sql, “Your connection string”);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
In the Page Load event, call this method to bind the GridView control with the data from the database. Then add a TemplateField column to the GridView. In the ItemTemplate section of this column, drag and drop a HyperLink control, specify the Text property as ‘Edit’. We have to add an client-side onclick event to this hyperlink to show the ModalPopup extender. In the GridView control’s RowDataBound event, add the following code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink HyperLink1 = (HyperLink)e.Row.FindControl(“HyperLink1″);
HyperLink1.Attributes.Add(“onclick”, “ShowMyModalPopup(‘” + GridView1.DataKeys[e.Row.RowIndex].Value + “‘)”);
}
}
The second line of the above code, adds the onclick attributes to the HyperLink1, with ShowMyModalPopup as a JavaScript function which takes the value from the DataKeyNames of the GridView control. A DataKeyNames property is an array that contains the names of the primary key fields for the items displayed in a GridView control.

So far, we made all the basic things ready for the GridView control to display data. Now you run the application, the GridView control will be populated with data from the customer table. When the hyperlink is clicked, the ModalPopup extender should come to action with the corresponding data from the selected row. We are going to do this with the help of Webservice method, which will return specific row data in an XML format. This webservice method will be called by the JavaScript method ShowMyModalPopup, and then we will process the XML and extract the data to display in the controls of the ModalPopup extender.

&amp;lt;script language=”JavaScript” type=”text/javascript”&amp;gt; document.write(‘&amp;lt;a href=”http://a.lakequincy.com/c.ashx?channel=1&amp;amp;format=7&amp;amp;pageid=DCD987EF-88AA-5A30-53D2-3FF976FEB260&amp;amp;publisher=224&amp;amp;&amp;amp;ypos=1157&amp;amp;zone=1&amp;amp;country=IN&amp;amp;userguid=4ea0a588-b3a9-48e4-922d-de374b59731f&amp;amp;placement=4128&amp;amp;creative=3104&amp;amp;” target=”_blank”&amp;gt;&amp;lt;img src=”http://view.atdmt.com/MRT/view/179321085/direct/01/”/&amp;gt;&amp;lt;/a&amp;gt;’); &amp;lt;/script&amp;gt;&amp;lt;noscript&amp;gt;&amp;lt;a href=”http://a.lakequincy.com/c.ashx?channel=1&amp;amp;format=7&amp;amp;pageid=DCD987EF-88AA-5A30-53D2-3FF976FEB260&amp;amp;publisher=224&amp;amp;&amp;amp;ypos=1157&amp;amp;zone=1&amp;amp;country=IN&amp;amp;userguid=4ea0a588-b3a9-48e4-922d-de374b59731f&amp;amp;placement=4128&amp;amp;creative=3104&amp;amp;” target=”_blank”&amp;gt;&amp;lt;img border=”0″ src=”http://view.atdmt.com/MRT/view/179321085/direct/01/” /&amp;gt;&amp;lt;/a&amp;gt;&amp;lt;/noscript&amp;gt;
Make the WebService.asmx

In your application, add a new WebService file and write a method to fetch single row from the customer table and return it in XML format. The webmethod will be as follows

[WebMethod]
public string FetchOneCustomer(string customerid)
{
string sql = “select * from Customers where cus_code=” + customerid;
SqlDataAdapter da = new SqlDataAdapter(sql, “Your connection string”);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.GetXml();
}
The above method will take customer code as argument and fetch the row and it will return the row as XML. So far GridView contol and WebService is ready. Now we can start to work on the ModalPopup extender to display the data for the corresponding selected row from the GridView control.

In order to access the web service from the client-side javascript, we need to add the ScriptService reference in the web service above the class header as follows.

[System.Web.Script.Services.ScriptService]

Design ModalPopup Extender

Drag and drop a ScriptManager, a ModalPopup Extender and a Panel control. Set the PopupControlID and TargetControlID of the ModalPopup Extender as ‘Panel1’. In the Panel control, you put 3 Textboxes to display Customer name, City and State and 2 DropDownList controls to take Gender and Customer Type. Also add a Hidden field to store Customer Code, and 2 Buttons to perform Update and Cancel action. Add a ServiceReference to the ScriptManager and point it to the WebService.asmx. Below we provide the sample code for ScriptManager, ModalPopup Extender and the Panel control

Click here to view Source Code [Show full code..]

So the ModalPopup extender has to appear on the screen along with the data of the corresponding row whenever the user clicks the HyperLink in the GridView control. For this we have write two JavaScript functions, one to show the ModalPopup window with the data and another function to display the data in the control of the ModalPopup extender.

The first JavaScript function is ShowMyModalPopup, which we already set in the HyperLink’s client-side onclick in the GridView’s RowDataBound event. This JavaScript function will be as follows

function ShowMyModalPopup(customerid)
{
var modal = $find(‘ModalPopupExtender1′);
modal.show();
WebService.FetchOneCustomer(customerid,DisplayResult);
}
In the above function, we find the ModalPopup Extender in the web page and show it. The next line of code is calling the webservice method from the JavaScript by passing the customer code and a JavaScript function name to process the result returned by the webmethod. This is the concept of consuming webservice with Asp.Net Ajax. The DisplayResult function takes an argument which is the resultant XML data come from the webservice method, process it with all browser compatibility issues, remove whitespaces in the XML data and set the values to the corresponding server controls in the ModalPopup Extender’s Panel control. Look carefully at the code below to set the values from XML data to Asp.Net server controls in the ModalPopup window.
function DisplayResult(result)
{
var doc;
if (window.ActiveXObject)
{
doc=new ActiveXObject(“Microsoft.XMLDOM”);
doc.async=”false”;
doc.loadXML(result);
}
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(result,”text/xml”);
}

var root=doc.documentElement.childNodes;
var tags;

for(var i=0;i<root.length;i++)
{
if (root[i].nodeType==1)
{
tags=root[i].childNodes;
}
}

for(var i=0;i<tags.length;i++)
{
if (tags[i].nodeType==1)
{
var xmlvalue=tags[i].childNodes[0].nodeValue;

switch (tags[i].nodeName)
{
case “Cus_Code”:
var label=document.getElementById(‘lblCode’);
label.innerHTML=xmlvalue;
document.getElementById(‘hidCusCode’).value=xmlvalue;
break;
case “Cus_Name”:
document.getElementById(‘txtName’).value=xmlvalue;
break;
case “Cus_City”:
document.getElementById(‘txtCity’).value=xmlvalue;
break;
case “Cus_State”:
document.getElementById(‘txtState’).value=xmlvalue;
break;
case “Cus_Type”:
document.getElementById(‘cmbType’).value=xmlvalue;
break;
case “Cus_Sex”:
document.getElementById(‘cmbSex’).value=xmlvalue;
break;
}
}
}
}

Close ModalPopup Extender from JavaScript

To close the ModalPopup Extender, specify the CancelControlID to the Cancel Button and specify the OnCancelScript values as HideModalPopup(). The JavaScript code for HideModalPopup function is

function HideModalPopup()
{
var modal = $find(‘ModalPopupExtender1′);
modal.hide();
}

Save everything, run the application. You can see the GridView control with customer data, when you click on the HyperLink, ModalPopup Extender will appear and the controls will be filled the the data from the selected row. If you click on the cancel button, the ModalPopup will get closed.

Edit Data From ModalPopup Extender

To edit data in the ModalPopup Extender and to save it in the database, we need to perform PostBack from a ModalPopup Extender. Follow the steps to make postback from ModalPopup Extender,

Step 1: Add the below code in Page load event

Button1.OnClientClick=String.Format(“fnClickUpdate(‘{0}’,'{1}’)”, Button1.UniqueID, “”);

Step 2: Add the below JavaScript function in the <script> section.

function fnClickUpdate(sender, e)
{
__doPostBack(sender,e);
}
These two steps will help the ModalPopup Extender to perform Postback actions, and the Button1’s server side click event will get fired, which in turn takes the data from the ModalPopup controls and save it into the database.

To implement this we need to put a Hidden field inside the Panel control and specify its ID as hidCusCode. This Hidden field will hold the primary key, that is the unique customer code, which we are going to use to update the records in the database. The value for this hidden field will be set in the DisplayResult JavaScript function.

Double click on the Update Button, it will create an Button1_Click event in your code-behind file. Write the code here to update the database record with the modified data and call FillGridViewWithCustomerInfo method to bind the GridView control with the updated data as follows

protected void Button1_Click(object sender, EventArgs e)
{
string sql = “Update Customers Set Cus_Name=’”+txtName.Text+”’, others_fields=other_controls.Text Where Cus_Code=”+hidCusCode.Value;
SqlConnection conn = new SqlConnection(“Your Connection String”);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();

FillGridViewWithCustomerInfo();
}

Save your application, view it in your browser. You can view GridView Control with customer data, click on the ‘Edit’ link, ModalPopup Extender will appear with data from the selected row, change something and click on the Update Button. Page will get postback and data will be updated in the database and showed in the GridView control.

Basic AJAX Example for Zend Framework | Squico

September 23, 2009 · Leave a Comment
Filed under: Featured, JavaScript 

I recently needed to port some existing php code which used Ajax over to the Zend Framework. While there are several tutorials out there with lots of details, I didn’t find a simple example that would just get me started with how to work Ajax calls into the MVC framework architecture. Eventually, I figured things out by referring to several different tutorials and doing a good amount of Googling. I decided it might be useful to have a very simple example of porting an existing Ajax app to the Zend Framework.

Warning: this app is very simplistic … it is solely designed to show minimum ‘hello world’ type of Ajax functionality, and how to fit that into the Zend Framework. There are plenty of more advanced tutorials out there, but this can get you started and show you how to make an Ajax call and respond to it with a Zend controller action. To simplify things even further, I’m using the prototype Javascript library, which makes life a lot easier by, among other things, providing a cross-browser means of creating and sending Ajax requests.

Versions: I wrote this against Prototype 1.5.1.1 and Zend Framework 1.0.1 (now updated for ZF v. 1.5)

Assumptions: I assume this is running on Apache, as I will include some .htaccess files to deal with url rewriting in the Zend version. I assume you’re familiar with Ajax … if not, there are tons of tutorials out there available via Google. I also assume you have some basic familiarity with the Zend Framework. If not, I recommend Rob Allen’s great introductory tutorial. And if you need to run the tutorial on Oracle instead of Mysql, well, of course, I recommend this blog post;)

If you want the code, download the zip file, which contains both the Zend app (ajax101_zend directory) and the non-Zend app (ajax101 directory). Both directories also contain the version of prototype that I used. Earlier versions of the download also contained Zend Framework v1.0.1, but I removed this at the same time I updated the code to work with ZF v1.5. I wrote the code on Windows, so be aware of that if you have any problems with the files on other platforms …

Okay, on to the code. First, the non-Zend version. I created three files (index.html, boxy.css, and server_script.php) and put them in the same directory on my webserver, along with the prototype.js file. Here’s the index.html, with a couple of Javascript functions to handle the Ajax call and response (we’ll factor those out to a separate file in the Zend version):

————————————————————————————

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
<head>
<title>Ajax 101</title>
<link rel=”stylesheet” href=”boxy.css”>
<script type=”text/javascript” src=”prototype.js”></script>

<script language=’javascript’>

//handle the Ajax response …
function handleResponse(transport)
{
$(’hello’).innerHTML = transport.responseText;
}

//creates a prototype Ajax object, sends a request, and registers the callback function ‘handleResponse’
function callAjax(s)
{
var myAjax = new Ajax.Request(’server_script.php’,
{method: ‘get’, parameters: {state: s},
onComplete: handleResponse});
}

</script>

</head>
<body>
<p>
<span id=’hover_span’ onmouseover=”callAjax(’do’)” onmouseout=”callAjax(’undo’)”> <b>Hover here to trigger Ajax call:</b> </span>
</p>

<span id=’hello’> boring pre-Ajax-call text … </span>

</body>
</html>

————————————————————————————

Here’s the simple stylesheet used:

————————————————————————————

#hover_span
{
font-size: 12pt;
}

#hover_span:hover
{
cursor: crosshair;
background-color: yellow;
}

————————————————————————————

And here is the php server-side script which simply echoes some text back depending on the ’state’ parameter passed in the request:

————————————————————————————

<?php

$state = $_REQUEST[‘state’];

if ($state == ‘do’)
{
echo ‘<h1>exciting text retrieved from server!</h1>’;
}
else if ($state == ‘undo’)
{
echo ‘reset to boring …’;
}
else
{
echo ‘unknown state parameter passed to server!!’;
}

————————————————————————————

So, if you trace through what happens, when you hover over the text at the top of the index.html page, Hover here to trigger Ajax call, the mouseover event fires, sending an Ajax request with a ’state’ parameter of ‘do’ to the server. The server responds with the text exciting text retrieved from server! enclosed in h1 tags. When the mouse leaves the text at the top of the page, the mouseout event fires, sending an Ajax request with a ’state’ parameter of ‘undo’ to the server, which responds with the text reset to boring …

Pretty simple, nothing exciting or difficult … just a super-basic example of doing something with Ajax. Okay, so how do we move that into the Zend Framework?

The first thing that is going to change is the directory structure. As I mentioned, for the simple ‘Ajax 101′ app, I just put all the files in the same directory on my webserver. For Zend, I’m going to need to separate things out, which is a good thing. I’m following a typical Zend Framework directory structure here, so it will look like this:

docroot
–app
—-controllers
—-views
——scripts
–library
–public
—-scripts
—-styles

You may have noticed the lack of a model directory. That’s because in this very simplistic example, there are no models.

Okay, so what next? Well, first we need to install the framework. Download the latest version of the framework (I used v1.5.1 in the latest work I did on this). Once you’ve extracted it, copy the library/Zend directory to your docroot/library directory.

Next we need a bootstrap file for the framework. This will be pretty simple for this example, since we’re not doing much, so we won’t be loading a bunch of Zend classes, setting up database connections, etc. All we’ll really be doing is some basic settings, like error reporting, include paths, and setting up the controller. This is in the index.php file in the docroot:

————————————————————————————

<?php

error_reporting(E_ALL | E_STRICT);
date_default_timezone_set(’America/Chicago’);

set_include_path(’.’ . PATH_SEPARATOR . ‘./library’ . PATH_SEPARATOR . get_include_path());

include “Zend/Loader.php”;

//setup controller
Zend_Loader::loadClass(’Zend_Controller_Front’);
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory(’./app/controllers’);

//run
$frontController->dispatch();

————————————————————————————

Next we’ll set up a simple controller, and put the code that was in the server_script.php file inside a controller action. This is the IndexController.php file in the docroot/app/controllers directory:

————————————————————————————

<?php

class IndexController extends Zend_Controller_Action
{
function init()
{
$this->initView();
$this->view->baseUrl = $this->_request->getBaseUrl();
Zend_Loader::loadClass(’Zend_Debug’);
}

function indexAction()
{
//echo “<p>in IndexController::indexAction()</p>”;
$this->view->title = “Zend Ajax 101″;
}

function getDataAction()
{
$this->_helper->viewRenderer->setNoRender();

$state = $_REQUEST[‘state’];

if ($state == ‘do’)
{
echo ‘<h1>exciting text retrieved from server!</h1>’;
}
else if ($state == ‘undo’)
{
echo ‘reset to boring …’;
}
else
{
echo ‘unknown state parameter passed to server!!’;
}
}
}

————————————————————————————

The only difference between our initial php script and the code in the getDataAction() method is the crucial first line:

$this->_helper->viewRenderer->setNoRender();

This tells Zend that this particular action method is not going to result in the re-rendering of the view.

Next, here’s our index.phtml, which is just slightly altered from the index.html of the non-Zend app, and is saved in the docroot/app/views/scripts/index directory:

————————————————————————————

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
<head>
<title><?php echo $this->title ?></title>
<link rel=”stylesheet” href=”public/styles/boxy.css”>
<script type=”text/javascript” src=”public/scripts/prototype.js”></script>
<script type=”text/javascript” src=”public/scripts/ajax_funcs.js”></script>

</head>
<body>
<p>
<span id=’hover_span’ onmouseover=”callAjax(’do’)” onmouseout=”callAjax(’undo’)”> <b>Hover here to trigger Ajax call:</b> </span>
</p>

<span id=’hello’> boring pre-Ajax-call text … </span>

</body>
</html>

————————————————————————————

You’ll notice that we’ve factored the javascript functions out to a separate file, as I said we would do. Here is that file, docroot/public/scripts/ajax_funcs.js:

————————————————————————————

//handle the Ajax response …
function handleResponse(transport)
{
$(’hello’).innerHTML = transport.responseText;
}

//creates a prototype Ajax object, sends a request, and registers the callback function ‘handleResponse’
function callAjax(s)
{

//remember to put a word separator between elements of the camelcase action name, per the ZF manual:
var myAjax = new Ajax.Request(’index/get-data’,
{method: ‘get’, parameters: {state: s},
onComplete: handleResponse});
}

————————————————————————————

The stylesheet is the same as the previous app, so I won’t repeat it here. Just note that it is saved in docroot/public/styles.

Finally, there are some .htaccess files we’ll need, since we need to handle rewrite rules and exceptions. In the docroot, here’s what you need in your .htaccess:

————————————————————————————

RewriteEngine on
RewriteCond %{REQUEST_URI} !/public.*

RewriteRule .* index.php

php_flag magic_quotes_gpc off
php_flag register_globals off

————————————————————————————

And for the docroot/public directory:

————————————————————————————

RewriteEngine off

————————————————————————————

Okay, that’s it! If all has gone well, you should see the same behavior in the Zend Framework version as you did in the non-Zend one. Hopefully, this will give you a jumping off point for more advanced Ajax work with the Zend Framework.

Mysql Ajax Table Editor | Squico

September 22, 2009 · 2 Comments
Filed under: Featured, JavaScript, MySql, MySql 5.0, MySQL 5.1 

Mysql Ajax Table Editor is a very versatile and customizable mysql editor. It is PHP4 and PHP5 compatible and it has incredible join capabilities. This mysql editor has the ability to join on multiple tables and maintain search functionality and best of all it is written with ajax. This makes the script very dynamic and it can be customized to fit almost every application. Things like dynamic forms and user defined actions make it very powerful.