...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
February 27, 2013

Lighten an area using css

Question by Asmastas Maz

http://asifslab.com
I want to lighten the area behind and near the logo on which the logo is located. The purpose for this is because the border of the logo is mixed with the background. Please help

Answer by Starx

You can add a background with rgba property to give a fake light background.

Try this

#logo {
   background-color: rgba(255,255,255, 0.5);
   /* Then other css */
}

In your case, modify your .head to this

.head {
  padding-left: 5%;
  background-color: rgba(255,255,255,0.5);
}
Read more

Data some is errased when update button is pressed

Question by user1868306

Please, I am having a problem when updating data in the database through a form. When ever I press the Update button to submit any changes made to a record, all the data in the mysql fields corresponding to drop list controls is errased. I do not know what is causing this problem. Here is the code:

<?php

    //include database connection
    include 'db_connect.php';

    // get value of object id that was sent from address bar
    $c_id = $_GET['c_id'];

    //check any user action
    $action = isset( $_POST['action'] ) ? $_POST['action'] : "";

    if($action == "update"){ //if the user hit the submit button

    //write our update query
    //$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection

    $query = "UPDATE collections
    SET
    ctitle = '".$mysqli->real_escape_string($_POST['ctitle'])."',
    csubject = '".$mysqli->real_escape_string($_POST['csubject'])."',
    creference = '".$mysqli->real_escape_string($_POST['creference'])."',
    cyear  = '".$mysqli->real_escape_string($_POST['cyear'])."',
    cobjecttype = '".$mysqli->real_escape_string($_POST['cobjecttype'])."',
    cmaterial = '".$mysqli->real_escape_string($_POST['cmaterial'])."',
    ctechnic = '".$mysqli->real_escape_string($_POST['ctechnic'])."',
    cwidth = '".$mysqli->real_escape_string($_POST['cwidth'])."',
    cheight = '".$mysqli->real_escape_string($_POST['cheight'])."',
    cperiod = '".$mysqli->real_escape_string($_POST['cperiod'])."',
    cmarkings = '".$mysqli->real_escape_string($_POST['cmarkings'])."',
    cdescription = '".$mysqli->real_escape_string($_POST['cdescription'])."',
    csource = '".$mysqli->real_escape_string($_POST['csource'])."',
    cartist = '".$mysqli->real_escape_string($_POST['cartist'])."'
    where c_id='".$mysqli->real_escape_string($_REQUEST['c_id'])."'";

    //execute the query
    if( $mysqli->query($query) ) {

    //if updating the record was successful
    echo "The record was updated.";

    }else{

    //if unable to update new record
    echo "Database Error: Unable to update record.";

    }

    }

    //select the specific database record to update
    $query = "SELECT c_id, ctitle, csubject, creference, cyear, cobjecttype, cmaterial, ctechnic, cwidth, cheight, cperiod, cmarkings, cdescription, csource, cartist, cfilename
    FROM collections
    WHERE c_id='".$mysqli->real_escape_string($_REQUEST['c_id'])."'

    limit 0,1";

    //execute the query
    $result = $mysqli->query( $query );

    //get the result
    $row = $result->fetch_assoc();

    //assign the result to certain variable so our html form will be filled up with values
    $c_id = $row['c_id'];
    $ctitle = $row['ctitle'];
    $csubject = $row['csubject'];
    $creference = $row['creference'];
    $cyear = $row['cyear'];
    $cobjecttype = $row['cobjecttype'];
    $cmaterial = $row['cmaterial'];
    $ctechnic = $row['ctechnic'];
    $cwidth = $row['cwidth'];
    $cheight = $row['cheight'];
    $cperiod = $row['cperiod'];
    $cmarkings = $row['cmarkings'];
    $cdescription = $row['cdescription'];
    $csource = $row['csource'];
    $cartist = $row['cartist'];
    $cfilename = $row['cfilename'];

    ?>

    <!--we have our html form here where new object information will be entered-->
    <table align=left>
        <tr>
    <td> <?php echo '<img src="./images/'.$cfilename.'" width="300" height="400" />';  ?> </td>
        </tr>
    <table>

    <form action='#' method='post' border='0'> 
    <table>
    <tr>
    <td>TITLE</td>
    <td><input type='text' name='ctitle' value='<?php echo $ctitle;  ?>' /></td>
    </tr>
    <tr>
    <td>SUBJECT</td>
    <td><input type='text' name='csubject' value='<?php echo $csubject;  ?>' /></td>
    </tr>
    <tr>
    <td>REFERENCE No.</td>
    <td><input type='text' name='creference'  value='<?php echo $creference;  ?>' /></td>
    </tr>
    <tr>
    <td>YEAR</td>
    <td><input type='text' name='cyear'  value='<?php echo $cyear;  ?>' /></td>
    <tr><td>OBJECT TYPE</td>
    <td>
        <select name="cobjecttype" id="cobjecttype" tabindex="">
            <option value="">---Select object type---</option>
            <option value="ceramic">Ceramic</option>
            <option value="clock">Clock</option>
            <option value="gold">Gold and silverware</option>
            <option value="mask">Mask</option>
            <option value="painting">Painting</option>
            <option value="sculpture">Sculpture</option>
            <option value="tapestry">Tapestry</option>
        </select>
        </td></tr>
        <tr><td>MATERIAL USED</td>
    <td>
        <select name="cmaterial" id="cmaterial" tabindex="" >
            <option value="">---Select Material---</option>
            <option value="brass">Brass</option>
            <option value="oil">Oil</option>
            <option value="wood">Wood</option>
            <option value="carved">Canvas/Cotton/Fabric/Linen/Wool</option>
      </select>
        </td></tr>
    <tr><td>TECHNIC</td>
    <td>
        <select name="ctechnic" id="ctechnic" tabindex="7" >
            <option value="">---Select Technic---</option>
            <option value="cast">Cast</option>
            <option value="carved">Carved</option>
            <option value="etched">Etched</option>                      
      </select>  
        </td></tr>
    <tr>
    <td>WIDTH</td>
    <td width="100"><input name="cwidth" type="text" id="cwidth" value="<?php echo $cwidth; ?>" size="10"></td>
    </tr>
    <tr>
    <td>HEIGHT</td>
    <td width="100"><input name="cheight" type="text" id="cheight" value="<?php echo $cheight; ?>" size="10"></td>
    </tr>
    <tr>
    <td>PERIOD</td>
    <td width="100"><input name="cperiod" type="text" id="cperiod" value="<?php echo $cperiod; ?>" size="30"></td>
    </tr>
    <tr>
    <td>MARKINGS</td>
    <td width="100"><input name="cmarkings" type="text" id="cmarkings" value="<?php echo $cmarkings; ?>" size="30"></td>
    </tr>
    <tr>
    <td>DESCRIPTION</td>
    <td width="400"><textarea name="cdescription" rows="2" cols="50" id="cdescription" value="<?php echo $cdescription; ?>"></textarea></td></tr>
    <tr>
    <td>SOURCE</td>
    <td width="100"><input name="csource" type="text" id="csource" value="<?php echo $csource; ?>" size="30"></td>
    </tr>
    <tr>
    <td>ARTIST</td>
    <td width="100"><input name="cartist" type="text" id="cartist" value="<?php echo $cartist; ?>" size="30"></td>
    </tr>
    <td></td>
    <td>

    <!-- so that we could identify what record is to be updated -->
    <input type='hidden' name='c_id' value='<?php echo $c_id ?>' />

    <!-- we will set the action to update -->
    <input type='hidden' name='action' value='update' />
    <input type='submit' value='Save' />
    <a href='gallery.php'>Back to display page</a>
    </td>
    </tr>
    </table>
    </form>

Can someone help to identify what the problem is?

Answer by Starx

Such problem occur when you dont validate your POST data correctly. In your code, you are updating your records directly, by using mysql_real_escape_string($variable). But although this might fix some security issues will not validated every data if it is present or not.

Validate your variables to be present and hold data before updating to the query.

Read more

How to add style for every first list element, first children with jQuery

Question by djlukas777

I have this markup:

<ul>
  <li> // this
    <ul>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
    </ul>
  </li>
  <li> // this
    <ul>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
    </ul>
  </li>
</ul>

In my style i have this:

.main_menu ul > li {
   // some style
}

and that gives me some style for only first li in that tree, not for children li of it.
So, my question is how to set this with jQuery, when i’m trying with $('.main_menu ul > li'); it doesn’t work. I guess i need some kind of this write:

$('.main_menu ul').each().first().child();

but it’s not correctly, can you help me?

Answer by Starx

Pseudo selector called :first-child can select the first child of a element. This is a CSS selector and jQuery also supports it. So you can use it either by CSS or jQuery.

ul li:first-child {
   /* Your style */
}

or jQuery

$("ul li:first-child").css('style-name', 'property value');
Read more

How to update the data in one region through ajax?

Question by user2046638

i want to upload the data in one region of four links, when I clicked the link1 it will load the data in specific region, and when I clicked the link 2 it will load the page on the same region where first link open, how can I do that?

    <div class="container">
    <div class="span-5">
        <ul>
            <li><?php echo $this->Manager->link('Ecommerce',array('controller'=>'associations','action'=>"view_report"),array('id'=> 'home','class'=>'nav'));?></li>
            <li><a href="#" id="home" class="nav">Home</a></li>
            <li><a href="#" id="about" class="nav">About</a></li>
            <li><a href="#" id="contact" class="nav">Contact Us</a></li>
        </ul>
    </div>
</div>

the data which I want to open from ecommerce link is int the newfile.ctp like that

 <?php v_start($this);?>

<h1><?php echo __l('View Report');?></h1>

<div class="firsttable">
    <table width="100%" border="0" cellspacing="0" cellpadding="2">
        <thead>
          <tr class="heading">
            <td><?php  echo __l('Financials');?></td>
            <td><?php  echo __l('Payment Methods');?></td>
            <td><?php  echo __l('By Credit Card');?></td>
          </tr>
        </thead>
        <tbody>  

          <tr>
            <td>
                <?php 
                    echo __l("YTD t ");
                    $ytd_total=0;
                    foreach ($YTD as $yearData)
                    {

                        $ytd_total +=$yearData['AssocPaymentDetail']['membership_fee'] - $yearData['AssociationDiscount']['amount'];

                    }
                    echo  $ytd_total."<br />";

                ?>
                <?php

                echo __l("Last 5days ");
                 $fda_total= 0;
                 foreach ($fiveDays as $fiveDaysData)
                    {

                        $fda_total += $fiveDaysData['AssocPaymentDetail']['membership_fee'] - $fiveDaysData['AssociationDiscount']['amount'];

                    }
                    echo $fda_total ."<br />";
                 ?> 
            </td>
            <td><?php  echo __l('creditcard');?>  <?php echo __l($ccSum) ?> </td>
            <td>
                <?php
        //       debug($paymentRecord);
        //      debug($ccIndex);
                    foreach($paymentRecord as $data =>$key){
                        foreach($ccIndex as $index){
                            if($data== $index)
                            {
                                echo "$data ttt";
                                if(is_array($key))
                                    echo array_sum($key);
                                else 
                                    echo "tt $key";


                            }

                            echo "<br/>";
                        }   

                    }

                ?>
            </td>
          </tr>
        </tbody>  
    </table>
</div>

Please help me to do this, thanks in advance

Answer by Starx

You can attach a single request handler to all links with nav as class name and then load the output to a container

$(".nav").on('click', function() {
    $("#loadingdiv").load("linktoload.php"); // or other 

});
Read more

jQuery On() is not working for $(document)

Question by Jason Biondo

I am currently in the process of integrating the dropkick.js plugin into my app, but I have run into a few snags. When I change backbone views the events do not work properly and the .live() event associated in dropkick.js just flat out doesn’t work at all. Nothing fires. I decided to upgrade this to using the .on() function and got it sort of working (even though it still deletes my url for some reason).

This doesn’t work at all:

$(document).on("click", ".dk_toggle", function() {

This only works somewhat:

$(".content").on("click", ".dk_toggle", function() {

Do you know why document doesn’t work at all?

My backbone $el is $(".content").

Answer by Starx

Instead of document, use body. It basically gives the same behavior.

$('body').on("click", ".dk_toggle", function() {
//....
});
Read more

Check type of optional parameter in PHP

Question by Patt

I am checking the type of optional parameters in PHP like this:

/**
 * Get players in the team using limit and
 * offset.
 *
 *
 * @param TeamInterface $participant
 * @param int $limit
 * @param int $offset
 * @throws InvalidArgumentException
 * @return Players of a team
 */
public function getPlayers(TeamInterface $team, $limit = null, $offset = null)
{
    if (func_num_args() === 2 && !is_int($limit) ){
        throw new InvalidArgumentException(sprintf('"Limit" should be of int type, "%s" given respectively.', gettype($limit)));
    }
    if (func_num_args() === 3 && (!is_int($limit) || !is_int($offset))){
        throw new InvalidArgumentException(sprintf('"Limit" and "Offset" should be of int type, "%s" and "%s" given respectively.', gettype($limit), gettype($offset)));
    }
//.....

}

This works but there are 2 main issues with this:

1/ If I need to check the type of 4/5 optional parameters for the same int type, the code become unnecessarily long. Any ideas how to make this piece of code more maintainable? (Maybe use only one if statement to check the same type of both $limit and $offset)

2/ getPlayers($team, 2, null) throws an exception. Is this ok knowing that the function can actually handle a null value here?

Answer by thatthatisis

You could do a for loop with an array of args. Something like:

$args = func_get_args();
for ($i = 1; $i < 4; $i++) {
    if ($args[$i] !== null and !is_int($args[$i])) {
        throw ...
    }
}

Of course, adjust the for conditions based on your number of arguments that need to be checked.

Or…

$args = func_get_args();
// skip first
array_shift($args);
foreach ($args as $arg) {
    if ($arg !== null and !is_int($arg)) {
        throw ...
    }
}

Answer by Starx

Use switch to code specific functions.

switch(gettype($limit)) {
    case "integer":
        //do other processing
    break;
}

You cannot leave your code vulnerable like that. As for a safe solution to overcome the vulnerabilities. Create a safe list like this.

public function getPlayers(TeamInterface $team, $limit = null, $offset = null) {
    $safelist = array("var1" => "TeamInterface", "var2" => "integer", "var3" => "integer");
    $args = function_get_args();
    $status = true;
    foreach($args as $key => $var) {
        if(gettype($var)!=$safelist["var".$key]) {
             $status = false;
             break;
        }
    }
    if(!$status) break;

    //...........
}
Read more
February 26, 2013

JQuery Select multiple paypal buttons

Question by Satch3000

I want to have 2 paypal buttons selected by 1 select box.

I have a minimum form code:

//The Form

<form id="form1" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">


<select name="select1" id="select1">
    <option id="option1" value="1">Button1</option>
    <option id="option2" value="2">Button2</option>
</select>

<input type="image" src="images/purchase_button.png" border="0" name="submit" alt="PayPal — The safer, easier way to pay online." />
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1" />
</form>

then at runtime jquery would do the rest:

$('#select1').change(function () {

if ($('option:selected', this).val() == 1) {

    $('#button1').remove(); //clean up
    $('#button2').remove(); //clean up

    $('#form1').append('<input type="hidden" name="hosted_button_id" value="button1-code-here" id="button1" />');


} else {

    $('#button1').remove(); //clean up
    $('#button2').remove(); //clean up

    $('#form1').append('<input type="hidden" name="hosted_button_id" value="button2-code-here" id="button2" />');

}



});

My problem is that sometimes when I select option 1 button it’s submitting button 2.

Does paypal save cookies when you go to the paypal payment page?

When is this not working smoothly everytime?

Answer by Starx

Your code needs some optimization. Make them and it will work as expected.

First use 1 button, there is no need for extra buttons

$('#select1').change(function () {

    if ($('option:selected', this).val() == 1) {
        $("#button1").val("button-1-code");
    } else {
       $("#button1").val("button-2-code");
    }

});
Read more

Query works in mysqlyog query window but not in php script?

Question by humphrey

I have two tables I am selecting from them 1 I want to get the user information and 2 I want to get all images belonging to the user . but the query does not retrieve the images but in query window I get them . Also in the script if I decide to select from the images table the images are displayed but when I do the joining stuff it does not work. I know there is something am not doing well . please any help will be appreciated
Bellow is the code

$query='SELECT 
tish_clientinfo.lastname, tish_clientinfo.address,
tish_clientinfo.firstname,
tish_images.image_name
  FROM  tish_clientinfo 
  INNER JOIN tish_images 
ON tish_clientinfo.user_id = tish_images.user_id
 WHERE user_id= '. intval($_GET['user_id']);
$result = $con->prepare($query);
$result->execute();

Answer by Starx

May be the server got confused about user_id. Try this

$query='SELECT 
tish_clientinfo.lastname, tish_clientinfo.address,
tish_clientinfo.firstname,
tish_images.image_name
  FROM  tish_clientinfo 
  INNER JOIN tish_images 
ON tish_clientinfo.user_id = tish_images.user_id
 WHERE tish_clientinfo.user_id= '. intval($_GET['user_id']);
Read more

How to access this kind of Json using jquery?

Question by Amit Prajapati

i am beginer in Jquery and javascript can any one help me to how to acces this kind of json data using jquery.if any one have idea to better way to access this data than please help me. this json data are come form remote url.

{
    "1": {
        "id": "1",
        "name": "name1",
        "large_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model1.jpg",
        "thumb_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model1_thumb.jpg"
    },
    "2": {
        "id": "2",
        "name": "name2",
        "large_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model2.jpg",
        "thumb_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model2_thumb.jpg"
    },
    "3": {
        "id": "3",
        "name": "name3",
        "large_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model3.jpg",
        "thumb_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model3_thumb.jpg"
    },
    "4": {
        "id": "4",
        "name": "name4",
        "large_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model4.jpg",
        "thumb_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model4_thumb.jpg"
    },
    "5": {
        "id": "8",
        "name": "Name8",
        "large_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model8.jpg",
        "thumb_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model8_thumb.jpg"
    }
}

Answer by Sheikh Heera

Use $.jsonParse to parse the json string then loop using $.each

$.each(data, function(k, v){
    document.write(v['id'] + ' ' + v['name']+'<br />');
});

Output:

1 name1
2 name2
3 name3
4 name4
8 Name8

In above example k represents the key and v represnts value (each object) and in this case the first key and object is ( "1" is key and {...} is object )

"1": {
    "id": "1",
    "name": "name1",
    "large_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model1.jpg",
    "thumb_name": "http://critiques-demo.she.com/beauty/makeuptool/images/models/model1_thumb.jpg"
}

Using v['id'] you can retrive the 1, v['name'] will return the name1 and so on. If you use $.getJSON then you don’t need to parse it because it’ll be parsed by jQuery and you can use it like

$.getJSON('url', function(data){
    $.each(data, function(k, v){
        document.write(v['id'] + ' ' + v['name']+'<br />');
    });
});

DEMO.

Answer by Starx

You can access the numeric keys as arrays like

console.log(dataJson[1].id);
Read more

How to create iframe about:blank without src but content html javascript

Question by Binh Nguyen

I want to create a iframe without src ( about:blank ) but that iframe content some javascript html

I need to do it because dont want create a hosted webpages on server for this mission, this will make more connection to server which are no good for resource. And also dont want write direct javascript html on webpage because they make the webpage load slow most time when load/running.

how to do it by using javascript (jquery maybe ) to do it

iframe eg :

<iframe src="about:blank" width="300" height="250" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" ></iframe>

and its content:

<div>xxx</div>
<script type="text/javascript">var abc=1 </script>
<script type="text/javascript" src="http://1234.net/js.js"></script>

================
==========UPDATE =====

Thanks for some answered following.
But I need to clear that script will create iframe by javascript also. because need to be create iframes in one page with differ id
Please look at my test:
http://jsfiddle.net/rDkEw/

The problems are:
if use document.body.appendChild the iframe will create on body of webpage , but i need it to keep in side current div which hold the JavaScript

thanks for any help

Answer by Starx

You can do it like this:

iframe = document.getElementById('iframeid');

div_el = document.createElement('div');
div_el.innerHTML = "....";
iframe.contentWindow.docum-ent.body.appendChild(div_el);

A jQuery solution:

$('#iframeid').contents().find('body').append("<div>.....</div>");
Read more
...

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