...

Hi! I’m Starx

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

display a javascript message before proceeding

Question by Joe Mo

I have this code that is to fetch a particular item in the database after the user presses a button. If the item is found I would like to display a confirm message via javascript and I don’t know how to show it.

After obtaining the item from the database

if(null!=mysqli_fetch_array($res)))
{
    echo ""; // how can I call the javascript code here ?
}

and the following confirm box

  <script type="text/javascript">
    function onConfirm()
    {
        return confirm("Display this item ?");        
    }
  </script>

Answer by Adam

Use jquery and ajax to get the value from the database:

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
$.get("ajax.php", function(data){

if(data != "0"){
if(confirm("Display this item ?"))
{

//do something

}
}

});

ajax.php:

//other db code here

if(null!=mysqli_fetch_array($res)))
{
echo "1"; 
}
else{
echo "0";
}

Answer by Starx

There are number of ways you can solve this. A good way is to:

  • Send an ajax request to a page
  • The page does the mysql stuff and returns(echo in case of PHP) the message
  • On the callback function use simple way such as alert() to show the message.
Read more

JavaScript For Loop work hows?

Question by Relax

I am using JavaScript for loop, my code is here

content = "";           
for (var i = 0; i < 13; i++) {
  var alt=glevel[i].getAttribute("name");
  if(jQuery.inArray(alt, clickArray) > -1) {
    if ($.browser.msie  && parseInt($.browser.version, 10) === 8 || $.browser.msie  && parseInt($.browser.version, 10) === 7) {
      content += "<li id='"+alt+"' style='cursor:pointer;filter:alpha(opacity=50);'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> n";
    } else {
      content += "<li id='"+alt+"' style='cursor:pointer;opacity:0.3;'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> n";
    }
    //$('#'+clickArray[alt]+"").css("opacity","0.5");
  } else{
    content += "<li id='"+alt+"' style='cursor:pointer'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'></font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'></p></li> n";
  }
  $("#step_2").html(content);
}

output of this code is something like that :-

image1 image2 image3 image4 
image5 image6 
image7 image8 image9 image10 
image11 image12 image13

update:- it looks like that because of my table width and height

It works very fine, it display the real product images what i have.

now i want to display something like this :-

image1 image2 image3 image4     
image5 image6 image7     
image8 image9 image10     
image11 image12 image13

means in the first row 4 images, while 2nd,3rd, and 4th row have 3 images

Answer by Imp

for (var i = 0; i < 13; i++) {
    content += "...";

    if (i == 3)                       // after the fourth line,
       content += '<br/><br/>';       // add an empty line
    if (i > 3 && (i - 4) % 3 == 2)    // then, after every three lines
       content += '<br/><br/>';       // add an empty line
}

Answer by Starx

What about this?

for (var i = 0; i < 13; i++){
    content += "<li>...</li>";
    if(i==3 || i==6 || i==9) { content += "<br />"; }
}
Read more

Using a variable inside an included file from function

Question by Djave

I’d like to have a header.php file throughout my site. I currently have the following:

header.php

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="<?php if(isset($depth)){echo $depth;};?>css/style.css">

functions.php

function include_layout_template($template="", $depth="")
{
    global $depth;
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}

index.php

<?php include_layout_template('header.php', "../"); ?>

But $depth dissappears, I can’t even echo $depth; its just blank. How can I get the depth variable for use in header.php?

Answer by Sergey

You have to rename depth variable in function call

function include_layout_template($template="", $my_depth="")
{
   global $depth;
   //if need $depth = $mydepth

Answer by Starx

Your $depth variable is disappearing, because it is passed as parameter first but then defined to use the global parameter.

I will explain with an example:

$global = "../../"; //the variable outside
function include_layout_template($template="", $depth="")
{
    global $depth; //This will NEVER be the parameter passed to the function
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
include_layout_template("header.php", "../");

To solve, simply modify the function parameter other than the depth itself.

function include_layout_template($template="", $cDepth="") { }
Read more

Is there anything missing in my code while exporting to excel from php

Question by sujal

My function

 function xlstest(){
            $headers='SN'."t".'Reservation ID'."t".'Hotel Name'."t".'Customer Name';
            $data='1'."t".'234'."t".'My hotel name'."t".'Jonny';
            $filename='testing';
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=".$filename.".xls");
            header("Pragma: no-cache");
            header("Expires: 0");
            echo "$headersn$data";
        }

while calling this function in admin panel it will export to excel but file doesn’t have above headers and data but it shows all the text that is present in admin panel
enter image description here

Do anyone know why is this happening?

Answer by sujal

My problem is solved. Actually I have called this function just below the <link rel="stylesheet" href=""/> and

<script type="text/javascript" src=".... .."></script>

once i moved above these css and scripts.. my problem is solved strange…….

Answer by Starx

Your are not using api at all. Please read the documentation and try to use the api.

And about the codes you are using, separate the field using t(with spaces back and front).
Also, instead of octet-stream use excels header file.

header('Content-type: application/ms-excel');

Usage:

function xlstest(){
    $headers='SN'." t ".'Reservation ID'." t ".'Hotel Name'." t ".'Customer Name';
    $data='1'." t ".'234'." t ".'My hotel name'." t ".'Jonny';
    $filename='testing';
    header("Content-type: application/ms-excel");
    header("Content-Disposition: attachment; filename=".$filename.".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo "$headersn$data";
}

Update:

To export a CSV file you can do do the following. Its almost same, but the delimiter is a comma instead and, the content-type is application/vnd.ms-excel.

function csvtest(){
    $headers='SN'.",".'Reservation ID'.",".'Hotel Name'.",".'Customer Name';
    $data='1'.",".'234'.",".'My hotel name'.",".'Jonny';
    $filename='testing';
    header("Content-type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=".$filename.".csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo "$headersn$data";
}
Read more

how to design grouped input text fields in one rounded corner box in jQuery Mobile

Question by EMMNS

can anyone tell me how can I put multiple text input fields in one grouped rounded corner box?

also with text place holder.

please see the attached image

input rounded corner box

I was trying from my side the code bellow:

<div data-role="content" data-inset="true" data-theme="b">
    <div data-role="fieldcontain">
    <form id="frmLogin" action="#" method="POST" data-transition="slide">
      <fieldset data-role="controlgroup" class="ui-corner-all ui-controlgroup ui-controlgroup-vertical">

        <div class="ui-field-contain">
          <label id="txtLoginName" for="loginName"></label>
          <input type="text" name="loginName" id="loginName" value=""  class="required"/>
        </div>
        <div class="ui-field-contain">
          <label id="txtLoginPassword" for="loginPassword"></label>
          <input type="password" name="password" id="loginPassword" value="" class="required"/>
        </div>

        <div class="ui-grid-a">
          <div class="ui-block-a">
            &nbsp;
          </div>
          <div class="ui-block-b">
            <a id="btnLoginSubmit" href="#" data-role="button" data-transition="slide" data-inline="true"></a>
          </div>
        </div>

      </fieldset>
    </form>
    </div>
  </div>

thanks in advance

Answer by Starx

I dont have your CSS to work with. So, here is a simple alternative.

CSS:

div {
    border: 2px #ddd solid;
    border-radius: 20px;
    width: 300px;
    padding: 20px;
}
div input {
    border: none;
    width: 260px;
    padding: 20px;
}
div input:not(:last-child) {
    border-bottom: 1px #ddd solid;
}

HTML:

<div>
    <input type="text"  value="email"/>
    <input type="password" value="password" />
</div>

Demo

Read more

Div containing dynamically generated list that appears when input is entered

Question by Jordan

Essentially I’m trying to create the HTML/CSS for an auto-complete. I want it to look/behave roughly like the one here: http://www.skyscanner.com/ (type into From or To fields)

I’m not worrying about actually making the auto-complete work, I just want to create the HTML/CSS that it would use to show the list of text items generated by the auto-complete.

This is the basic layout I’m hoping to make:

enter image description here

Input box 1 and Input box 2 are what I currently have. When the user clicks in one of these input boxes, I want the corresponding auto-complete box (which at this point will show fake data) to appear.

Unfortunately I can’t think of how I would do something like this. Can anyone get me started or point me in the right direction?

Answer by D. Strout

The basic idea is to have a parent element that is positioned relatively to the page, but without moving it. Since this element is positioned (not static), you can position the suggest box absolutely relative to the parent element, under the text box. Since it is positioned absolutely, it does not affect document flow, a.k.a. it appears over other elements that are below the text box. Something like this should work:

HTML:

<span class="tbSuggestParent">
<input type="text" class="tbSuggest">
<span class="suggestions"><!-- Suggestions go here --></span>
</span>

CSS:

.tbSuggestParent {
    position: relative;
    display: inline-block;
}

.tbSuggest {
    width: 200px;
    height: 30px;
    font-family: Arial;
    font-size: 14pt;
    border: 2px solid black;
    border-radius: 2px;
}

.suggestions {
    position: absolute;
    width: 170px;
    height: 300px;
    top: 36px;
    left: 15px;
    border: 1px solid black;
    border-radius: 2px;
    display: inline-block;
    background-color: white;
}

This includes rounded borders as your image seems to show, using border-radius. If that property is not available in a given browser, it should just use regular borders.

Demo (includes text underneath): http://www.dstrout.net/pub/suggest.htm

Answer by Starx

Here is a simple way

  • Wrap your elements in a div. Why? It avoids you from using a lot of unnecessary styles

Set the div to be positioned as relative, then the autocomplete box will be automatically aligned to the input the box and the container.

Here is the markup I Suggest.

<div class="field">
     <input type="text" />
     <ul class ="autocomplete">
          <li>Option 1</li>
          <li>Option 2</li>
          <li>Option 3</li>
          <li>Option 4</li>
          <li>Option 5</li>
     </ul>
</div>

Demo

Read more
May 13, 2012

Make counter in sql query

Question by Viktors Golubevs

I am using codeigniter and have working query which take user 3 images. I want to make a count an give every image a number 1,2,3,4,5,6,7 … and want that query output

-number (count),
-id,
-image,
-date

my sql query :

function bar_images_first($user_id)
{   
    $sql = "SELECT id, image, UNIX_TIMESTAMP(date) as date FROM images WHERE user_id = 3 LIMIT 3";
    $query = $this->db->query($sql, $user_id);
    return $query->result_array();
}

Is it possible to do counter in query?

Answer by Starx

It is possible by setting a SQL parameter as

SET @cnt := 0;
SELECT
    @cnt := @cnt + 1,
    id,
    image,
    UNIX_TIMESTAMP(date) as date 
FROM images WHERE user_id = 3 LIMIT 3";

But such multiple statements cannot be executed from the PHP’s mysql_query() method. But, mysqli function like mysqli_multi_query() does allow to execute multiple queries too, so if possible use mysqli method rather than the AR methods.

However, you can run multiple sets of query one by one.

$query = array(
    "SET @cnt := 0;",
    "SELECT
        @cnt := @cnt + 1,
        id,
        image,
        UNIX_TIMESTAMP(date) as date 
    FROM images WHERE user_id = 3 LIMIT 3"
);

foreach($query as $qry) {
     $result= $this->db->query($qry);
     //.........
}
Read more

how to block the page width javascript

Question by yobin

...
<head>
    <script type="text/javascript" src="a.js"></script>
</head>
<body>
    <button id="test">click me</button>
    <script type="text/javascript">
        show();
        document.getElementById('test').onclick=function(){
            show();
        }
    </script>
</body>
</html>

the code above:

I put the a.js in the <head> tag, in a.js there’s a b.js created by

document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));  function show(){...} 

in b.js;

now I want to invoke show() which in the b.js,but it goes error,because b.js hasn’t loaded;

I want to add some codes to block the page loading.

while(){} ?


actually,I learned b.js should be loaded when function show is invoked;

but what about click event?in addition,I must put the show() in the page.

now,I put another js(base.js) into head tag,the above code will be like this:

...
<head>
<script type="text/javascript" src="base.js"></script>
<script type="text/javascript" src="a.js"></script>
</head>
<body>
    <button id="test"></button>
    <script type="text/javascript">
        //invoke button click event from base.js and b.js
    </script>
</body>
...

for example,there are two click events bind to base.js and b.js(loaded ansync by a.js),when users click the button in the page,the event binded in base.js will be invoked immediately,but then…error…

I must put the invoker in the body tag.

Answer by Starx

Instead of blocking the page load, why dont you run the code on the onload event of the window?

window.onload = function() {
    show();
};
Read more
May 12, 2012

Jquery Is this the correct way?

Question by JCN

<script type="text/javascript">
        if (SOMECONDITION) {
            $("#scriptD").attr("src", "../../Scripts/A.js");
        } else {
            $("#scriptD").attr("src", "../../Scripts/B.js");
        }

</script>

<script id="scriptD" src="" type="text/javascript"></script>

I am trying to insert a .js file dynamically ( on the condition basis). But this is not working . Can anybody tell me whats the problem here?

Answer by Starx

One way to do what you are trying is using $.getScript()

if (SOMECONDITION) {
    $.getScript("a.js");
} else {
    $.getScritp("b.js");
}

And besides, you way will work, if you place the script after the <script> element

<script id="scriptD" src="" type="text/javascript"></script>
<script type="text/javascript">

    if (SOMECONDITION) {
        $("#scriptD").attr("src", "../../Scripts/A.js");
    } else {
        $("#scriptD").attr("src", "../../Scripts/B.js");
    }

</script>

This is because the script will not be able to find scriptD on the DOM, when it is called before an element.

Read more

jquery selector multiple classes on set of <div>'s (contains one class, not the other)

Question by Dave Jay

This may be easier than what I’ve tried. I have a set of <div>‘s such as <div id="site-abc" .. "site-def"> and each has similar HTML content. The DIV’s have multiple classes like "ui-tabs-panel class2 ui-tabs-hide". One does not have ui-tabs-hide. That’s what I need a selector for, and then from that I need to find unique text within that DIV that’s within bingo!.

What’s the right jQuery selector code for the following steps: A) find right <div> with class="ui-tabs-panel" but NOT CONTAINING "ui-tabs-hide"; B) take that selector result and find ('th.target2') and get the .text()?

var tabs = $('#editors.not(.ui-tabs-hide'); 
var my_text = tabs.find('th.target2').text();

<div class="grid-editor">
    <div id="editors" class="ui-tabs">
        <div id="site-abc" class="ui-tabs-panel class2 ui-tabs-hide"> 
            //duplicates HTML like "site-ghi" including <th>bingo!</th>
        </div>
        <div id="site-def" class="ui-tabs-panel class2 ui-tabs-hide">
            //duplicates HTML like "site-ghi" including <th>bingo!</th>
        </div>
        <div id="site-ghi" class="ui-tabs-panel class2”>
            <table class=”my-table”>
                <thead>
                    <tr>

                        <th class="target1">abc1</th>
                        <th class="target2">bingo</th>
                    </tr>
                </thead>
        </div>
    </div>
</div>

Answer by Starx

You almost got it. Use :not selector to omit the one you don’t need.

var divs = $('.ui-tabs-panel:not(.ui-tabs-hide)'); 

I am not sure if this is related to the problem, but there is mistake in your selector statement as well.

var tabs = $('#editors.not(.ui-tabs-hide');
                                      //^ No Closing bracket 
Read more
...

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