June 29, 2013

Ajax response error

TNK’s Question:

I need to make a mysql query according to the value of dropdown list. Here I use ajax to send dropdown value to the server. I think this part is working for me. But problem is I can not get it to php. Note: both are in the same page.

This is my Jquery code :

    var filterValue = $(this).val();

        type: 'post',
        dataType: 'html',
        data: {filter: filterValue},
        error:function (xhr, ajaxOptions, thrownError){
            //On error, we alert user
        complete: function(){
            //alert('update success'); 

This is HTML form

    <form method="post" action="">
        <select id="filter-value" name="filter">
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>              

This is my PHP code that I am trying on the top of the page :

if (isset($_POST['filter'])) {
    $filter = $_POST['filter']; 
    echo $filter; 
} else {
    echo 'bad';

But this php code is always going to else part and print ‘bad’

Can anybody tell me where I am going wrong?

Thank you.

You have missed to specify the URL of the script. Be ensure that you are querying the correct file from the AJAX.

    type: 'post',
    url: 'yourpage.php', // This one 

Unsort in array

Alex’s Question:

Good day.

I would be like get 3 keys from $arr where value $arN[0] will be more than other…



$arr[]=array(6299927 => $ar1);
$arr[]=array(1252760 => $ar2);
$arr[]=array(3432444 => $ar3);
$arr[]=array(3435543 => $ar4);
$arr[]=array(7645466 => $ar5);
$arr[]=array(4574534 => $ar6);

Next function sorting array $a descending:

function cmp($a, $b)
    if ($a == $b) {
        return 0;
    return ($a < $b) ? 1 : -1;

$a = array(3, 2, 5, 6, 1);

usort($, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $valuen";
outpoot: 0:6 1:5 2:4 3:2 4:1

But how change this function for my example(for my big array)?

Tell me please how make this?

How write right?

Very confusing but I think you are looking for something like this. It will give you the index of the array whose first item is greater than the first item in the next array.

foreach($arr as $key => $array) {
    if($array[0] > $arr[$key+1][0]) {
       echo $key;
June 27, 2013

PHP: header alternative?

Ralph’s Question:

I wanted to know if the echoing the following would be a good alternative to using header(“Location: index.html”) without having to use output_buffering

echo "<script type='text/javascript>window.location = 'index.html';</script>";

There are times I would like to redirect possibly in a body, would the above work fine or is it worth turning on the output_buffering option and just user header()?

header() defines the page the user is viewing. Using output buffering forces to ignore the previous output buffer, so it is not considered an efficient way to redirect. So, here are my suggestions:

  1. If your only target is to redirect, then make sure you output nothing before header statement executes. In this case header is appropriate.

  2. If you need to show your page and based on user interactivity need to redirect to the different page, use the JavaScript Redirection.

June 25, 2013

Java: silly newbie issue about path used in import statement

Ggkmath’s Question:

I’m working through the example here:


In my file, I’ve got:

package com.mycompanyname.mydirectory;

import com.mycompanyname.OneOfMyClasses;
import com.itextpdf.text.Document;

 public class MyClass {

Everything is working fine. What I don’t understand is that since I just copied the import statement directly from the link above for the iText portion — why does com.itextpdf.text.Document work?

I mean, if I look in directory com.mycompanyname I can see OneOfMyClasses.java there.

But in the com directly, there is no itextpdf directory (although maybe my user doesn’t have permission to see it(?)).

Hoping someone can help me understand what I’m missing here. Doesn’t the import point to a specific directory that I should be able to see the class? Is there a different com directory somewhere that iText is using, and com.itextpdf.text points to there? (if so, where’s the directory located)?

I installed the jar file for iText in the lib folder as per usual, and made sure it was included in the classpath.

Those classes are inside a JAR file that is added to the classpath:

Create a new Java project “de.vogella.itext.write” with the package “de.vogella.itext.write”. Create a folder “lib” and put the iText library (jar file) into this folder. Add the jar to your classpath.

import statements will look inside whatever directory trees are in the classpath, which includes the current directory at compilation time (tipically the src/ directory in your project) as well as any directory specified through environment variable or JVM startup parameter. See this about the classpath.


You do need the imports whenever you use classes across packages. Every public class/interface you define is in a package. If whatever you are referencing belongs to another package, you need to import it.

JARs are zip files that contain directories and files inside. It’s the same as plain directories and files, only packed.

That class is most probably imported in a JAR library. Inside such JAR file, the class files are kept in exact package/folder structure as you use when importing them.

June 24, 2013

PHP: sending email with my website domain

Abdullah Salma’s Question:

When I used mail() function and sent an email to my self from my website. I recived the email from myusername@pickens.dreamhost.com I want to change the sender into noreply@mydomain.com

but is there a way ?

You can change the sender by using headers while sending your email. Such basic things are well illustrated on the PHP manual page of mail()

This is an example taken from that manual page

$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "rn" . 
            // ^ This is where you update your header to show the sender
    'Reply-To: webmaster@example.com' . "rn" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

Javascript tooltip only appears on second hover

Ghostmancer’s Question:

I am using jQuery and Twitter Bootstrap, and want to have a tooltip appear when hovering over a link. However, the tooltip doesn’t appear the first time I hover over a link, but if I move the mouse away and back on, it works every time for that link.

I have several of these on the page:

<a href="#" onmouseover="$(this).tooltip();" class="postAuthor" data-original-title="@username">Full Name</a>

I’ve created a jsFiddle to demonstrate: jsFiddle. Any help would be appreciated – thanks in advance!

.tooltip() functions initiates the tooltip effect on the link, not show the tooltip


When the $(this).tooltip() is triggered on the first hover, it instantiate the plugin first. Then finally on the second hover you get the tooltip.


Add this on your code:

$(function() {


Converting a stand alone java file to a file that's part of a project package?

Sam Peterson’s Question:

I still don’t fully understand where I’m required to use the “public static void main(String[] args)” header within the .java files of a project. Do you need to put that header in every .java file of a package?

I have been following along with chapter 3 in my book, dragging and dropping downloaded stand alone book source files into my project’s package, but some of the .java files in my package don’t like that “public static void main(String[] args)” statement, even though my opening and closing curly braces are in the correct place. Here’s an example of one of those files (the ERROR(S) are described in the code’s comments):

    public class Rectangle
   public static void main(String[] args){
   private double length;//ERROR: illegal start of expression
   private double width;

    * Constructor

   public Rectangle(double len, double w)
      length = len;
      width = w;

    * The setLength method accepts an argument
    * that is stored in the length field. 

   public void setLength(double len)
      length = len;

    * The setWidth method accepts an argument
    * that is stored in the width field.

   public void setWidth(double w)
      width = w;

    * The set method accepts two arguments
    * that are stored in the length and width
    * fields.

   public void set(double len, double w)
      length = len;
      width = w;

    * The getLength method returns the value
    * stored in the length field.

   public double getLength()
      return length;

    * The getWidth method returns the value
    * stored in the width field.

   public double getWidth()
      return width;

    * The getArea method returns the value of the
    * length field times the width field.

   public double getArea()
      return length * width;

}//end of: public static void main(String[] args)

}//end of: public class Rectangle  ERROR: class, interface, or enum expected

The ERROR(S) came up after I added the “public static void main(String[] args)” to the existing Rectangle.java file. Any idea of why this occurs?

This occurs because You cannot have more than one main() method in a package. However overriding the main method is definitely allowed. What I mean is as, long the parameter number is differed you can override main() method.

public static void main(String[] args) {

And somewhere else in other or same class, you can add such class

public static void main(String arg1, String arg2) {

The ERROR: illegal start of expression is because you are using access modifier inside the method. Use all the access mofifier and variable declaration inside the class

public class Rectangle {

    private double length;//ERROR: illegal start of expression   
    private double width;

    public static void main(String[] args) {

The ERROR: class, interface, or enum expected is because the class Rectangle is only housing a static method, your all the methods and parameters are inside the static method called main()

Here is your code which will compile without an error.

June 20, 2013

addClass vs attr and creating an ID

Aaron’s Question:

So what I am reading is that when adding a class to an element without any class selectors, use the addClass() method over attr().

For example, using:


is more efficient than


I cannot find anything equivalent to addId(‘myid’) for adding id selectors, does it exist or is attr() the best way to add an id selector?

I get that id is unique, the logic behind my question is addClass() is faster than attr().

So my question is if there’s a more efficient method for creating an id than attr().

Answering directly

No, addId() does not exist and addClass() is not as same as attr()

In HTML, a class attribute can hold more than one value like <div class="tall fat brown">Someone</div> so jQuery’s function addClass() helps to add a value to the class attribute not change it. Similarly the functions toggleClass() and ‘removeClass()` help manipulate them.

But the function attr() will just manipulate the attribute and change it directly.

For example:

<div id="person">someone</div>

And the following jQuery Statements

$("#div").addClass("tall"); // This will create the class attribute and add tall 
$("#div").addClass("fat");  // This will append fat to the existing class and make "tall fat"
$("#div").addClass("brown"); // likewise

.addClass() will just append the class name. If same needs to done by using attr() you have to do

$("#div").attr('class', 'tall');
$("#div").attr('class', 'tall fat');
$("#div").attr('class', 'tall fat brown');

Or, you can modify the attribute using

$("#div").attr('class', function(i, className) {
    return className + " brown";

Where as ids have one value that needs to be modified or altered so a function like addId() would do exactly which attr(‘id’, ‘idvalue’) would do.

Adding div from JSON in jQuery?

Ted’s Question:

I am getting some data from a page in JSON format
‘name’ : ‘maverick’,
Image : ‘Jason’

I now need to take these values and add them to the #main div.

        <div id="main">
        <div class="a"> name: Eithan <img src="img/Eithan.jpg" /> <div>
        <div class="a"> name: Emma <img src="img/Emma.jpg" /> <div>

How do I do that in jQuery for the case there are several objects in the JSON?

You can do this by using $.getJSON() function.

$.getJSON("link/to/json", function(data) {
    $.each(data, function(i, item) {
        $('#main').append('<div class="a"> name: ' + item.name + ' <img src="img/' + item.image + '.jpg" /></div>');

php variable assignment confusion

Robert Rocha’s Question:

While reading a book about php I cam across a piece of code that logically doesn’t make sense to me. The line of code is part of a class function:

private function replaceTags( $pp = false ) {
    //get the tags in the page
    if( $pp == false ) {
        $tags = $this->page->getTags();
    } else {
        $tags = $this->page->getPPTags();
    //go through them all
    foreach( $tags as $tag => $data ) {
        //if the tag is an array, then we need to do more than a simple find and replace!
        if( is_array( $data ) ) {
            if( $data[0] == 'SQL' ) {
                //it is a cached query...replace tags from the database
                $this->replaceDBTags( $tag, $data[1] );
            } elseif( $data[0] == 'DATA' ) {
                //it is some cahched data...replace tags from cached data
                $this->replaceTags( $tag, $data[1] );
        } else {
            //replace the content
            $newContent = str_replace( '{' . $tag . '}', $data, $this->page->setContent( $newContent ) );
            $this->page->setContent( $newContent );

The specific line that doesn’t make sense to me is:

$newContent = str_replace( '{' . $tag . '}', $data, $this->page->setContent( $newContent ) );

How can you pass the variable “$newContent” to “setContent( $newContent )” when it doesn’t have a value yet?

Any explanations?

That statement is executing in a for loop so, $newContent will hold the value in another loop to use.

In the first execution, $newContent will be empty but on the next iteration it will have a value to replace.

foreach( $tags as $tag => $data ) {
    if ....
    } else {
        //replace the content
        $newContent = str_replace( '{' . $tag . '}', $data, $this->page->setContent( $newContent ) );
     // ^
     // Now next time when the loop executes again it will have a 
     // $newContent to process.

        $this->page->setContent( $newContent );

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