...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
June 17, 2012

PHP loop within a loop, option selected?

Question by David

Using PHP I echo out table rows in a loop like this:

<?php
/* SQL STUFF */

  while ($row = mysql_fetch_array($select_courseelements)) {
   echo "<tr>n";
    echo "<td>".$row['scpe_name']."</td>n";
    echo "<td>".$row['scpe_days']."</td>n";
   echo "</tr>n";
  }

Now I would like to include a <select> element with 5 predefined <option> values inside a <td> running with the loop. The option values will be 1 to 5.

There is also a column inside the $row loop that holds a value of 1 to 5 ($row['scpe_grades_status']).

Each time this value is equal to the one in the <select> I want it to change it to selected='selected'.

Would this be possible?

My <select> will look something like this when it’s beeing run in the loop:

echo "<td>n";
echo "<select id='elements_grade'>n";
        echo "<option value='1'>Registrerad</option>n";
        echo "<option value='2'>Ej påbörjad</option>n";
        echo "<option value='3'>Pågående</option>n";
        echo "<option value='4'>Godkänd</option>n";
        echo "<option value='5'>Deltagit</option>n";
        echo "<option value='6'>Ej deltagit</option>n";
echo "</select>n";
echo "</td>n";

Answer by piers

$array = array('Registrerad' => 1, 'Ej påbörjad' => 2, 'Pågående' => 3, 'Godkänd' => 4, 'Deltagit' => 5, 'Ej deltagit' => 6);

foreach ($array as $key=>$value) {
    if ($value == $row['scpe_grades_status'])
        echo '<option value="'.$value.'" selected>'.$key.'</option>';
    else
        echo '<option value="'.$value.'">'.$key.'</option>';
}

Something like that?

Answer by Starx

Sure, build the values from a loop. and you can compare the values from that part.

for($i = 1; $i<=5; $i++) {
   echo "<option value='$i'";
   echo ($row['scpe_grades_status'] == $i) ? " selected='selected'": "";
   echo ">...."</option>"
}
Read more
June 14, 2012

echo font color output

Question by xan

I wrote a php code that display error in red color. But somehow, this doesn’t seem to work out. Here’s my code:

<?php
...    
if(!$name || !$email || !$contact || !$itemid){
                        //if not display an error message
                        echo "<span style="color: red;" /><center>Fields marked with <strong>&#40; &#42; &#421</strong> are mandatory!</center></span>";
                        }else{...


?>

Answer by swapnesh

Do this something like that —

echo '<span style="color: red;" /><center>Fields marked with <strong>&#40; &#42; &#421</strong> are mandatory!</center></span>';

Your "" quotes are conflicting

Answer by Starx

The problem is un-escaped quotes on your PHP expression.

echo "<span style="color: red;" />...
                //^ Right here        

Because, Your PHP echo statement also started with the same quote i.e ".

Here are the different ways you can solve this:

  1. Use mixed quotes

    echo "<span style='color: red;' />...
          // Single quote in the HTML part
    
  2. Escape the quotes

    echo "<span style="color: red;" />...
         // Escape the quotes so that it gets treated as string rather than a modifier
    
Read more
June 13, 2012

PHP Function error handling and returning when foreach loop goes on a variable

Question by user1179459

*problem/confusion on how to handle this type problem in the php object oriented coding *

I have customer class which i need to suspend services for customers, however when the customer has pending work types for a service, i need to return a false for the calling function to do the error handle (i cant do it here becos it could be a email,output, or html)

however i am confused how to handle this as if use following code it will return false only on the last condition on the foreach loop i guess, any idea on how to handle this in the coding point of view

 /**
   * return false on failier 
   * Customer suspend all services for this customer
   * 
   */
  public function suspendServices(){

    $pending=false; 

    foreach ($this->services() as $service) {

    $pending = $service->hasPendingWorktypes();

    if($pending === true) {
        return false;
    }   
    $service->state()->changeTo(8);  

    }//end of foreach services 

  }//end of function

Answer by Starx

Exceptions is perfect for this job. The business method calling for the services can then onwards handle the part efficiently for the correct outcome.

public function suspendServices(){

    $pending=false; 

    foreach ($this->services() as $service) {

    $pending = $service->hasPendingWorktypes();

    if($pending === true) {
        throw new PendingExcpetion(); //Throw the exception
    }   
    $service->state()->changeTo(8);  

    }//end of foreach services 
}
Read more

Difference between int and int received by ParseInt in java

Question by blunderboy

int i = 0;
int k = Integer.parseInt("12");
int j = k;
System.out.println(i+1 + " " + j+1);

Strangely the output received is

1 121

I can not figure out this basic difference. Please help me.

Answer by Jigar Joshi

Use brackets as follows

System.out.println((i+1) + " " + (j+1));

From the docs

The + operator is syntactically left-associative, no matter whether it
is later determined by type analysis to represent string concatenation
or addition. In some cases care is required to get the desired result.
For example, the expression:

a + b + c is always regarded as meaning: (a + b) + c

Extending this to your scenario

i+1 + " " + j+1

it becomes

(((i + 1) + " ") + j)+1

Since i is an int so (i + 1) = 1 , simple addition

" " is a String hence ((i + 1) + " ") = 1 WITH SPACE (String concatenation)

Similarly when j and last 1 is added, its being added to a String hence String concatenation takes place, which justifies the output that you are getting.

See

Answer by Starx

When you use " " The expression after that gets evaluated as string.

Using brackets ( and ) around an expression can solve the problem in hand.

System.out.println(i+1 + " " + (j+1));
Read more
June 12, 2012

absolute path source php

Question by Felix Perdana

This is maybe just a trivial question, but I don’t really know what is the best practice to include, says javascript, img, or css using absolute path

What I am really using right now is using the code like this

<?php
$prefix = '//';
$rootFolder = $prefix . $_SERVER['HTTP_HOST'];
?>

so then when i want to include something like jquery, I would just type the code like this

<script type="text/javascript" src="<?php echo $rootFolder ?>/jquery-1.7.1.min.js"></script>

is this good enough? Or should I modify the prefix to “http://” or maybe there is some better way using another superglobal variable and such?

thanks in advance 🙂

Answer by Starx

This question cannot be answered in a correct way, because absolute and relative paths, both have their own importance on a website.

For search engines, they dont like websites with absolute links to the same websites. The modern browsers nowadays already read the relative path with the websites current URL prefixed, unless “/” is used infront of an URL. So, it should not harm when you try to use a relative path as much as possible.

Another case is, If you application is extendable by multiple modules. Generally taking, an admin module and one user module. If these module share a common resource folder for JS, CSS and others then its useful and easy to create a relative paths.

Since, your question is concerned about accessing a resource from the root folder, you should be fine as it is i.e using relative paths.

Read more
June 11, 2012

How to prevent excessive function calls in JQuery

Question by tsvallender

I have an element which autosaves its contents via an AJAX call. Currently, whenever the contents change the autosave function is called. However, I’d like to limit this a bit to reduce the number of server requests. What would be the best way of editing the following code so save() is called no more than once every n seconds?

$("#editorInstance").contentChange(function() {
    save();
});

Answer by blockhead

If you don’t mind another library, underscore has a throttle method which can handle this:

throttle _.throttle(function, wait)

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

Answer by Starx

You can delay the execution of the function, using setTimeOut()

var init;
$("#editorInstance").contentChange(function() {
    init = setTimeOut(save, 60000); //After a minutes
});

//Do you forget to clear the timeout too
function save() {
     clearTimeOut(init);
     //Remaining function
}

Or, you might want to disable the editor, when it is being saved.

$("#editorInstance").contentChange(function() {
    $(this).attr('disabled', true);
    save();
    $(this).removeAttr('disabled');
});
Read more

jQuery: prop vs attr… clarification

Question by BrianFreud

Possible Duplicate:
.prop() vs .attr()

I’m trying to narrow down what should be set using prop, vs what should be set via attr when creating a new element. In tests with 1.7.2, I find that prop is approx 2.5 times faster, so it seems preferable.

The only list of things to be set using attr that I could find gives these for attr:
accesskey, align, background, bgcolor, class, contenteditable, contextmenu, data-XXXX, draggable, height, hidden, id, item, itemprop, spellcheck, style, subject, tabindex, title, valign, width

But 1) is this complete (ie, anything not in that list – such as min, max, step, etc – should use prop), and 2) in testing, some of those seem to work fine when set using prop.

Testing the above list, I’ve had no issues setting the following with prop:
id, class, align, contenteditable, draggable, hidden, spellcheck, tabindex, title

So 3) Is there some reason, for that list of “stuff to set with attr that still work when set with prop”, why it should still be set with attr? If not, then 250% faster performance when creating a basic
div id=”foo” class=”bar” draggable=”true” title=”zipzap”
seems good to me… 🙂

Answer by BrianFreud

I cannot find any complete list online. Everyone who gives any kind of a list just copies the partial one given in the jQuery 1.6 blog post. Regarding #3, Starx sortof addressed this in his comment to an answer here. http://timmywillison.com/ goes into better detail with a decent discussion. MDN and the W3C specs also mentions that there are various interfaces from attributes where they can be set as if they were properties ( https://developer.mozilla.org/en/DOM/element ), though MDN doesn’t actually list which ones those are. MDN does mention that using the property interfaces as setters is more brittle than using getAttribute:

“While these interfaces are generally shared by most HTML and XML elements, there are more specialized interfaces for particular objects listed in the DOM HTML Specification. Note, however, that these HTML interfaces are “only for [HTML 4.01] and [XHTML 1.0] documents and are not guaranteed to work with any future version of XHTML.” The HTML 5 draft does state it aims for backwards compatibility with these HTML interfaces but says of them that “some features that were formerly deprecated, poorly supported, rarely used or considered unnecessary have been removed.” One can avoid the potential conflict by moving entirely to DOM XML attribute methods such as getAttribute().”

However, it seems safe to assume for now that any HTML5 doctype page rendered in Firefox and Chrome is already in an environment where ‘deprecated, poorly supported’, etc interfaces have already been removed.

Thus I’ve tested every attribute, as well as the non-attribute properties mentioned in the jQuery blogs, against every every HTML element type, using boolean, string, and int values.

Using 1.7.2 and 1.8pre, whether you call .prop() or attr(), jQuery will internally always actually use .prop for:

async, autofocus, autoplay, checked, controls, defer, disabled, hidden, loop,
multiple, open, readonly, required, scoped, selected

For HTML elements (not considering window, document, etc here), jQuery will not set any of the following attributes unless you use .attr():

accept-charset, accesskey, bgcolor, buffered, codebase, contextmenu, datetime,
default, dirname, dropzone, form, http-equiv, icon, ismap, itemprop, kind, 
language, list, location, manifest, nodeName, nodeType, novalidate, pubdate, 
radiogroup, seamless, selectedIndex, sizes, srclang, style, tagName

And finally, jQuery will set the following list of attributes with either .prop() or .attr(). In the first list above, jQuery always uses .prop(), regardless of whether you use .attr() or .prop(). For the attributes in this list, jQuery uses whatever you use. If you use .prop(), jQuery uses .prop(), and vica versa. In either case, the result is the same. So ignoring any potential semantic considerations, just with regards to prop() being ~2.5 times faster than .attr(), the jQuery 1.6.1 blog post suggests that .attr() be used, but .prop() can be used instead, with significant increase in performance:

accept, action, align, alt, autocomplete, border, challenge, charset, cite, 
class, code, color, cols, colspan, contenteditable, coords, data, defaultValue, 
dir, draggable, enctype, for, headers, height, hidden, high, href, hreflang, 
id, keytype, label, lang, low, max, maxlength, media, method, min, name, 
optimum, pattern, ping, placeholder, poster, preload, readonly, rel, required, 
reversed, rows, rowspan, sandbox, scope, shape, size, span, spellcheck, src, 
srcdoc, start, step, summary, tabindex, target, title, type, usemap, value, 
width, wrap

Answer by Starx

Try to understand this on simple terms.

.attr() gives the attribute of an element. That attribute when it was loaded on the page.

.prop(), gives the property of the element,

  • this can be the state of an element, like in the case of checkboxes, it can either be checked or unchecked.
  • Or, it can be modified attribute of an element, since the default state.

This question has all the differences you need to know. Generally, when working with DOM manipulation part, you need property rather than attributes. The answer by T.J. really clears the concept.

Read more
June 4, 2012

Force lightbox to open in parent page php JavaScript

Question by user1434701

Yet another newbie asking for help.

I have a Main_index.php page. Multiple divs are loaded into this page and each div has a “More” information button. Each div is a template style and is completed with mysql data.

<div class="more"><a href="advert_details.php?advert_id=<?php print $advert_id?>"id="more<?php print $advert_id?>"><?php echo MORE ?></a></div>

Each “More” button brings up a new page “advert_details.php”, inside a lightbox. This is again a template style and loads details from mysql. The lightbox code is in the Main_index.php.

<script language="JavaScript" type="text/javascript">
$(document).ready(function()
        {
        $('a').filter(function() {
        return this.id.match(/more[0-9]/);
    }).fancybox({
        'overlayColor' : '#000',
        'overlayOpacity' : 0.1,
        'width' : 640,
        'height' : 940,
        'type' : 'iframe'
    });
});
</script>

If one of the “advert_details.php” pages is found by a search engine, when you click on the search result, the lightbox opens in a blank page.

Is there anything I can add, to force the “advert_details.php” page to open in the “main_index.php” page, making use of the lightbox JavaScript and showing the main site page?

I hope that I have explained this well, if not, please ask for more details.

Thanks

Peter

Answer by Starx

You can set a URL parameter which will be checked to include the advert_details.php in the main page.

Something like

if(isset($_GET['showDetails'])) {
   include "advert_details.php";
}
Read more

PHP get element using a known attribute

Question by Ilya Karnaukhov

So lets say I have:

<?php
    $template = '<img src="{image}" editable="all image_all" />';
    $template .= '<div>';
    $template .= '<img src="{image}" editable="yes" />';
    $template .= '</div>';
?>

Now what I would like is to make the script go through all the elements containing the {image} src and checking to see if any of them have the

editable="all" 

attribute.

If so: get the second editable attribute e.g.

image_all

And include that into the src.

Answer by Starx

This task can be simplified with the use of a library suggested on comments, Simple HTML DOM Parser:

It is as easy as this:

$images = array(); //an array for your images with {image} in src
$html = "...";
foreach($html->find('img') as $element)
    if($element->src == '{image}') {
        //add to the collection
        $images[] = $element;
    }
    //Also you can compare for the editable attribute same way as above.
}
Read more

Auto play and stop html5 audio with jquery

Question by Łukasz Borawski

i have a little problem.

I have a facebook like box window on overlay. This box hide when user click like – obviously. I wanna to use audio element when this window is visible and stop audio when this window will be hide.
So this is my html and jquery. Please help me.

<audio id="audio_player" loop="loop">
    <source src="fileadmin/templates/main/crowd.mp3" type='audio/mpeg; codecs="mp3"'>
    <source src="fileadmin/templates/main/crowd.ogg" type='audio/ogg; codecs="vorbis"'>
</audio>

$(document).ready(function(){
function audio_player (){
    if (
        $('fb_like_box').css('display','block')){
            $('audio').each(function() {
                var song = $(this);
                    song.play();
                });
    }
    else if (
        $('fb_like_box').css('display','none')) {
            $('audio').each(function() {
                var song = $(this);
                    song.pause();
                });
    }
    else {}
}
});

Answer by Starx

Your code syntactically wrong.

First of all, the following syntax is for assigning value.

$('#fb_like_box').css('display','block')

It assigns the property block to element $('#fb_like_box');

If you want to check it, as that, you have use something like this:

if($('#fb_like_box').css('display') == 'block') {
    // then do something
}

A good way to do what you are attempting is:

if ($('#fb_like_box').is(':visible')) {

    $('audio').each(function() {
        $(this).play();
    });

} else {

    $('audio').each(function() {
        $(this).pause();
    });

}
Read more
...

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