...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
December 30, 2011

How to use ajax in zend framework?

Question by sarunathan

I tried a simple ajax aplication using jquery, where i had my php file in an separate folder in my root and it is working.

Is there any other way to use ajax in a zend framework?

Answer by Starx

There are some ways you can do it

  1. Use ZendX_JQuery. They have helper called ajax_link, with which you can use make ajax call directly from a link.

  2. Embed a js file, in your file and use ajax there. Use something like:

    $this -> headLink() -> appendScript(‘path/to/your/script’);

    You might have to import the JQuery file like this, if you have not enabled this, using the ZendX_JQuery helper.

  3. Directly feed script content like <script>...</script> like you would raw html

However, JQuery helper might take a bit to fully understand. If you are already familier with JQuery, and know how to use it properly. Go with option number 2.

🙂

Read more

Remove/Add hover after toggle Jquery

Question by hyperrjas

I have this css:

.disable {
          properties
          }

.comment_action:hover {
                       properties
                       }

I have this jQuery:

//comment button index disable
$("#mydiv").toggle(function() {
 $(this).find(".comment_action").addClass('disable');   
},
function(){
 $(this).find(".comment_action").removeClass('disable');
});

The problem for me is that when I doing click the .comment_action:hover is not disappear or removed. I want that If I doing click on the class .comment_action:hover dissapear and if I doing click again the .comment_action:hover appear.

Answer by lawrence.alan

You would need an !important added to properties you want to override in the :hover psuedo-selector…

Because :hover takes precedence, even if .disabled is applied.

Also your javascript should be calling find with .comment_action instead of comment_action

See working example: http://jsfiddle.net/TN4rh/11/

Answer by Starx

Better solution would be toggle the class. What you are trying to do can be done in one line.

$("#mydiv").click(function() {
    $(this).find(".comment_action").toggleClass('disable');       
});

Demo

🙂

Read more
December 29, 2011

how to know how many pages a particular user visited in a particular session

Question by Anup Kumar

i am working on a e-commerce website, i want to monitor how many pages a users visited in a particular session. there are only registered users of the site.
can any one tell me how to record the URL of the user of a particular session,
i am using php and mysql

Answer by Starx

There are more than one way to do this. Here is one quick walkthrough:

  1. Create a table with two fields (‘session_id’, ‘url’);

  2. Whenever the site loads, read the sessionid using session_id(), and use this value to store the url of the page in a table for every pages the people visit.

  3. Once a page loads, read the URL, through $_SERVER['REQUEST_URI']; and then use it the value of session_id() and store the records.

After you implement this simple technique. you can see how many people see the pages, using a simple query

SELECT count(*) FROM <YOURSESSIONTABLE> GROUP BY `<session_id_field>`

P.S. This is one of the basic example, and should be changed to fit your requirements

Read more

How to deselect tabs in jquery

Question by sasirekha

$(document).ready(function() {
    $('#tabs > ul').tabs('select', 1);
    $('#tabs').tabs({
        selected: 1
    });
    $("#tabs").tabs({
        disabled: [0, 2, 3]
    });
    return false;
});

To move to another tab, CSS style is not followed. How do I deselect the current tab?

Answer by Starx

Use the following to select a different tab or move to another tab.

$( "#tabs" ).tabs( "option", "selected", 2 );

However, to deselect the current tab, you have to select another tab, that’s the only way the tabs work. If you want to clear the style of current selected tabs then use

$("#tabs .ui-tabs-selected").removeClass("ui-state-active").removeClass("ui-tabs-selected");});
Read more

how to play wav stream in safari vai javascript

Question by Jeffrey Hsu

I’ve tried Audio / embed / Object, but fail at all of them.

play wave file is ok, but cannot play stream.

<audio><source src="sample.wav" /></audio> OK

<audio><source src="http://mydomain/stream" /></audio> fail

<object data="sample.wav"></object> OK

<object data="http://mydomain/stream"></object> fail

jPlayer also cannot work!

I found a clue:
If when I play it in firefox before, then safari works. It seems firefox download it so the safari can play it in quicktime’s cache.
code:
<embed src="http://10.224.91.28:8080/cas/auth.do?cmd=getaudiobycaptchaid&id=Q71UNBGRFOI00A8NDNBV76BTNE&clientid=9e1f73ca9d0ff1e07ca87f7660d1b911" height="45" width="170" type="audio/x-wav"/>

Answer by Starx

You should use html5audioplayer. It slags a bit, but works in the end….

Read more

mysqli_affected_rows, mysql subtract 2 columns error

Question by Max

I have a column I want to update with results of the difference between 2 mysql columns and count how many rows were affected. In my case it can only be 1. This is the mysql query I am using which is not consistent at all

$connection->query("UPDATE items SET Quantity_Available = Quantity - Quantity_Committed WHERE Item_ID = '$itemid'");
if($count=$connection->affected_rows!=1){echo $count;die('makassi');}

If I replace the Quantity_Committed with a numeric value, I get what I want i.e the code continues. However if I leave it as it is, I get the proper $count figure(1) but it also fails by echoing ‘makassi’ which it shouldn’t.

Is this an improper way of subtracting 2 mysql columns or is this a bug in the php mysqli api??
This is really baffling to me!! Help please

Answer by Starx

This is a bad practice what you are trying to do. If a column in the database is derived from another column already in the column. Then such is create redundancy is the database. All a database should be normalized as much as possible. Please read here about data normalization.

Whatever you are trying to do can be achieved in a much better way. Like

Filtering the records

SELECT * FROM items WHERE Quantity - Quantity_Column > 5

Or, retrieving the quantity available.

SELECT (Quantify - Quantity_Column) as `Quality_Available` from items
Read more
December 23, 2011

AJAX Streamlining techniques?

Question by Vigrond

My question is a bit abstract.

We’re all familiar with AJAX preloaders/spinners that come up when an AJAX request is being made. My question is how do you avoid these?

Take for example, a sortable list. When a user drags and drops items to resort them, an AJAX call is made to update the order.

Before, I would pop up a fullscreen AJAX spinner to prevent the user from doing anything until the AJAX call was complete.

My question is, how would I go about avoiding the AJAX spinner and “streamlining” ajax requests to ensure if a user initiates 20 ajax requests in 2 seconds, that they will be executed in order?

I don’t really need code examples, just accepted or popular techniques/ideas. Or if I’m going completely off track here.

Thank you

Answer by kitgui.com

So far good answers in terms of using an array or queue to ensure they are loaded and returned one at a time. I would eliminate the spinner all together similar to how gmail does and only message the user only when necessary. There is no point in bothering the user about all these spinner deals. They just look like little robot a-holes anyways. Here is some code to do I whipped up.

Since I got a nod on this I will explain its features.

  1. Stops queue if error occurs
  2. Continues queue as success occurs
  3. Has event handlers for success / error with context

I write plugins so is this an idea worthy of a plugin? I don’t think so but hey you never know.

var queue = [],
doRequest = function(params) {
    params.running = true;
    $.ajax({
        url: params.url,
        dataType: 'json',
        success: function(d) {
            params.success.call(params,d);
            queue.unshift(); // Quit counting your change and move along.
            if (queue.length > 0) {
                doRequest(queue[0]); // Hey buddy, your next.
            }
        },
        error: function(a,b,c) {
            params.error.call(params,a,b,c);
            alert('"oops"'); // Rick Perry
        }
    });
},
queueRequest = function(params) {
    queue.push(params); // Sir, you'll need to go to the BACK of the line.
    if (!queue[0].running) {
        doRequest(queue[0]);
    }
};

// so to use this little snippit, you just call "queueRequest" like so (over and over)
queueRequest({
    url: 'someajax.abc',
    success: function(d) {
        // let the user know their stuff was saved etc.
        // "this" will be the context of the "params"
    },
    error: function(a,b,c) {
        // let the user know something went wrong etc.
        // "this" will be the context of the "params"
    } 
});

And you’re done.

Answer by Starx

Isn’t this exactly why, there is an async option in jquery?

Use async: true to queue up the request.

Spinners are kept to avoid sending same request over and over again. Like take a case, where there is an option to enable and disable a feature… if a user click at the same button again, you are sending same request over and over again. Only use spinners in these cases.

Popping up a big box, to avoid access to the whole page… is just a stupid idea (no offence).

Use spinners, to the specific elements.. that is being processed or manipulated somehow. For the request, just use async…

CASE CLOSED 😉

Read more
December 2, 2011

Using jQuery to append URL with anchor #

Question by jeffkee

While retrieving items via AJAX etc., the links are set to do this:

$(this).click(function(){
ajax_function(); // hypothetical ajax call that puts data into a <div> of my choice
return false;
});

In this scenario, I’m wondering what the best way is to utilize jQuery to add things to my URL in this format:

http://www.mydomain.com/products

turns into

http://www.mydamain.com/products#category-12,page-4

Further note- I’m talking about the actual URL of the browser (in the URL bar) not a URL that is part of the DOM.

Answer by jeffkee

After searching some more (with better keywords than before on Google) I found the answers I needed, and I wrote the following functions:

    function get_url_hash(argument) {
    var hash = location.hash.replace('#','');
    if(argument=='' || argument==undefined) {
        return hash;
        alert(blank);
    } else {
        var foundhash = false;
        // specific argument given - let's find the value attached. 
        var hashblock = hash.split(',');
        for(x in hashblock) {
            var hasharray = hashblock[x].split('-');
            if(hasharray[0]==argument) {
                return hasharray[1];
                foundhash = true;
            }
        }
        if(foundhash==false) {
            return false;
        }
    }
}

function modify_url_hash(argument, value) {
    // This function goes through the entire hash,
    // figures out which parts of the hash should be added, updated or removed based on entry, 
    // and then spits out final result. 
    var hash = get_url_hash();
    var foundhash = false; // foundhash is set to false by default. if this hash is NOT found, then we add it at the end! 
    var hashcount = 0; // keep count of total # so as to determine where to put the commas etc. 
    var newhash = '';
    if(hash.length>0) {
        var hashblock = hash.split(',');
        for(x in hashblock) {
            var hasharray = hashblock[x].split('-');
            if(hasharray[0]==argument) {
                hasharray[1] = value;
                foundhash = true;
            }

            if(hasharray[1]!=false && hasharray[1]!='') { // if new value is NOT false, we keep it in.. otherwise don't feed it to newhas so it disappears.
                if(hashcount>0) { newhash = newhash+','; }
                newhash = newhash+hasharray[0]+'-'+hasharray[1];
                hashcount++;
            }

        }
    }

    if(foundhash==false) {
        // this is a new hash block. 
        if(hashcount>0) { newhash = newhash+','; }
        newhash = newhash+argument+'-'+value;
    }
    location.hash = newhash;
}

Answer by Starx

May be something like

oldlink = $('#mylinkselector').attr("href");
newlink = oldlink="#category-12,page-4";
$("#mylinkselector").prop("href",newlink);
Read more

mysql_connect() using http protocol

Question by Saheelram

I am trying to connect to a MySql server (not localhost) from my computer using the code below. It is giving this error:

Warning: mysql_connect() [function.mysql-connect]: [2002] Connection refused (trying to connect via tcp://10.6.3.6:3306) in on line 7

I wonder if we can use the http protocol to connect instead of tcp that is being used by default? I searched quite a bit on how to change the protocol, but most of the answers were describing how to connect to localhost, and not much about how to connect to another server. Please help.

PS: I am able to connect to the server by going to http://10.6.3.6/phpmyadmin/…). So I am sure the server is up.

My Code

<?php

$db_hostname = '10.6.3.6';
$db_database = 'db_user11';
$db_username = 'db_user11';
$db_password = '########';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());

?>

Answer by deceze

First of all, HTTP is layered on top of TCP/IP.
In order to connect to something via HTTP, it needs to run an HTTP server. MySQL does not run an HTTP server and there’s no current/realistic/supported way to tunnel an SQL connection through HTTP. Even if there was, HTTP is not exactly the best protocol for this.

In short: no. You’re trying to solve the wrong problem. You need to configure your MySQL server to allow connections from other machines over the network, give the user you’re trying to connect with appropriate permissions to connect from other machines and make sure the MySQL server is reachable from other machines.

Answer by Starx

Just because the phpmyadmin is hosted on that server, does not neccesarily mean that the database server is in the same IP address. Please ask the domain administrator to give you the details of database server.

Read more
...

Please fill the form - I will response as fast as I can!