...

Hi! I’m Starx

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

Sliding image using JavaScript

Question by Diwash Regmi

I am trying to create a image slider, using JavaScript.

HTML

<img src="firstcar.gif" name="slide" width="100" height="56" />

<img src="secondcar.gif" name="slide1" width="100" height="56" />

Script

var image1 = new Image()
image1.src = "firstcar.gif"
var image2 = new Image()
image2.src = "secondcar.gif"
var image3 = new Image()
image3.src = "thirdcar.gif"

//variable that will increment through the images
var step = 1

function slideit() {
    //if browser does not support the image object, exit.
    if (!document.images) return
    document.images.slide.src = eval("image" + step + ".src")
    if (step < 3) step++
    else step = 1
    //call function "slideit()" every 1.5 seconds
    setTimeout("slideit()", 1500)
}
slideit()

I wanted to slide two image in such a way that the upcoming image displays in the second place and slides to the first place and both the image must be inline.

I can’t find the error. Can someone help me fix it?

Answer by Starx

There are lots of image sliders available on the internet. You can google them.

However, the script you are building above does not create sliding effect in any way. It just switches the image and fakes the effect to looks like as if it was sliding.

The working version of the script will look something like this.

var step = 1;

function slideit() {
    //if browser does not support the image object, exit.
    var img = document.getElementById('slide');
    img.src = "image" + step + ".src";
    console.log(img.src);
    if (step < 3) step++;
    else step = 1;
    //call function "slideit()" every 1.5 seconds
    setTimeout(slideit, 1500);
}
window.onload = slideit();

Demo

Read more

Aligning two lines of horizontal links evenly with CSS

Question by Derrick

I have 6 links, all different character lengths on two lines. I need everything to align evenly. Like this:

Home       About Us     Location
Contact    Visit        Schedule

I imagine the way to do this is to make the li a specific width and then apply an appropriate margin to the right side, but for some reason I can’t apply a width. If I have the following html skeleton, how would I edit the CSS to accomplish this? I’ve looked around the web for a solution, but I’ve haven’t found any similar questions because my menu sits on two separate lines.

<div class="footer">
 <ul id="footerlinks">
  <li><a href="link 1">Home</a></li>
  <li><a href="link 2">About Us </a></li>
  <li><a href="link 3">Location</a></li>
<br>
  <li><a href="link4">Contact</a></li>
  <li><a href="link5">Visit</a></li>
  <li><a href="link6">Schedule</a></li>
</ul>

Answer by Starx

Fix the width of <ul> and <li>. And remove the <br /> it makes the markup invalid.

HTML

<ul id="footerlinks">
  <li><a href="link 1">Home</a></li>
  <li><a href="link 2">About Us </a></li>
  <li><a href="link 3">Location</a></li>
  <li><a href="link4">Contact</a></li>
  <li><a href="link5">Visit</a></li>
  <li><a href="link6">Schedule</a></li>
</ul>

CSS

#footerlinks { width: 300px; }
#footerlinks li { width: 100px; display: inline-block; }

Demo

Demo(with white-space fix)

Read more

Jquery: why my 'find()' method not updating?

Question by 3gwebtrain

i have a function to find the length of finding class, but it not working always return the length is ‘0’;

some thing is wrong with my code: can any one advice me the proper way. but i need to use the same structure of the code style to achieve this.

look on to my code :

<div id='list'>
  <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>      
  </ul>
    <p></p>
</div>​

function callMe(params){
    $(params.list).click(function(){
       $(this).addClass('c_on');
        var length = $(params.list).find('.c_on').length;
        $('p').text(length)// return always 0, even i clicked no.of list.        
    })
}

$(document).ready(function(){
    var obj = {
        list : $('ul').find('li')      
    }
   callMe(obj);
})

style :

li.c_on{
border:1px solid green;
}


​Here is the fiddle : http://jsfiddle.net/AeGvf/1/

Answer by mu is too short

You’re using find:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

when you should be using filter:

Reduce the set of matched elements to those that match the selector or pass the function’s test.

Note that find works on the descendants whereas filter works on the elements themselves. You have a list of <li>s that don’t have any descendants so find is searching an empty set. You should do this:

var length = $(params.list).filter('.c_on').length;

Also, your params.list is already a jQuery object so you don’t need to $(params.list), you can use params.list directly:

function callMe(params){
    params.list.click(function(){
        $(this).addClass('c_on');
        var length = params.list.filter('.c_on').length;
        $('p').text(length);
    });
}

Demo: http://jsfiddle.net/ambiguous/uCGaY/

Answer by Starx

Your selection method is bit flawed. Use this one instead:

function callMe(params){
    params.list.click(function(){
       $(this).addClass('c_on');
        var length = $(this).parent().find('.c_on').length;
        $('p').text(length)        
    })
}

Demo

Read more

Get all array keys that is not equal to X

Question by Oyvind Andersson

I have several files uploaded with a form that is processed by a PHP script. There are several “categories” that I need to have handles separate ways. In other words, I need some of the files in the $_FILES array to be stored someplace, and some others stored in other places.

So what I need is all files (array keys) that are not $_FILES[‘filename_form’] to be stored / used separably.

The reason why I need this is because the amount of files being uploaded are dynamic, but always either $_FILES[‘filename_type1’] or $_FILES[‘filename_type2_*] where * is a number that increments when more files are input from the form (dynamically)

Might be a very simple solution, either I’m too tired or maybe I’ve been staring too much at the code, but all I know is I need a solution before tomorrow morning, so it’s time sensitive =P

Appreciate all the help I can get.
Thank you!

Answer by Zombaya

$files = array();
$filenames = array();
foreach($_FILES as $name => $fileInfo)
{
    if($name != 'filename_form')
    {
        $files[$name] = $fileInfo;
        $filenames[] = $name;
    }
}

Answer by Starx

Here is an alternate way

$keys = array_keys($thearray);
$filteredArray = array_filter($keys, 'fiterKeys');

function filterKeys($item) {
    if($item != 'valuetocheck') return true;
    else return false;
}
Read more
May 4, 2012

Select specific row from mysql table

Question by Marlon Brando

Ideally I need a query that is equal to

select * from customer where row_number() = 3

but thats illegal.

I cant use an auto incremented field.

row_number() is the row that needs to be selected.

How do I go about this?

EDIT: Well, I use iSql*plus to practice, and using limit and auto_increment is illegal for some reason. I ended up creating a sequence and a trigger and just uped the id by 1 everytime there was an entry.

Answer by Starx

You cannot select a row like that. You have to specify a field whose values will be 3

Here is a query that will work, if the field you are comparing against is id

select * from customer where `id` = 3
Read more

Foreach loop only looping once?

Question by myladeybugg

I’m having trouble with my foreach loop opening multiple files.

My foreach loop is only running once for the first item number. The foreach loop runs then goes to the “api.php” page but then stops and doesn’t go back to the foreach loop to get the next item number. How do I tell it to go through all of item numbers in my database?

Would I use cURL somehow?

Thanks

Here’s my code:

$itemnumber = array("".$result['item_number']."");

foreach ($itemnumber as $item_number) {

echo "<form method="post" action="api.php" name="ChangeSubmit" id="ChangeSubmit">";
echo "<input type="text" name="item_number" value="{$item_number}" />";

echo "<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("ChangeSubmit");
frm.submit();
}
window.onload = myfunc;
</script></form>";



}

Answer by Starx

You actually have only one item in your array. SO it is looping only once.

Your code $itemnumber = array("".$result['item_number'].""); will translate to

 $itemnumber = array($result['item_number']);

Because, the double double-quotes you provided have no significance in the code too. SO, at last the array will have only one item.

Read more

access associative array

Question by user1017268

I am using Code Igniter and I get following data structure after executing a query at DB

array
'application' => 
    array
    0 => 
        object(stdClass)[19]
        public 'app_id' => string '16' (length=2)
        public 'app_name' => string 'dddddddd' (length=8)
        public 'app_title' => string 'sdfsdf' (length=6)
        public 'app_comments' => string 'sdfsdf' (length=6)
        public 'active_flg' => string 'N' (length=1)

I know one way to access the values is

foreach($application as $key => $value)
    $value->app_id

But I know that I will get only one record each time so I want to access the elements without using foreach.
I have tried to $application->app_id and $application[‘app_id’] but I keep getting error.

Can anybody please help me to understand how to access the data directly??

Answer by Starx

You are using multidimensional mixed type of array, with numeric indexing on the second level. SO, while accessing the values, you have to use them too. Like

echo $array['application'][0]->app_id;
Read more

jquery POST does not return any result in https

Question by mario

I have a jquery script that just runs fine on http://mysite.com

and looks like this:

Javascript:

$('#form_changePass').live('submit', function() {
    //alert('form_changePass cliked');
    $.POST("_ajaxCall.php", $(this).serialize(),
    function(data){
        var json = eval('('+data+')');
        //alert(data);    
        if(json.message=='alert') {
            $('div.info').hide();
            $('div.alert').show().html(json.string);
        }
        if(json.message=='info') {
            $('div.alert').hide();
            $('div.info').show().html(json.string);
        }
    }
    );
    return false;
})

PHP script:

if ($_POST['formType']=="form_changePass") {
.....
.......
   $arr = array( 'message' => 'info', 'string' => $INFO['updatePass']);
   echo json_encode($arr);
}

Now when I move the domain into https the jquery script is not working anymore. I do not get any return value back. Nothing happens.

I also tried to change the POST to getJSON in the javascript and changed the $_POST to $_GET in the php script but it is still not working.

Anybody a idea?

Answer by Starx

.serialize serializes the form data as a string, so send them using a parameter instead.

$('#form_changePass').on('submit', function() {
    //alert('form_changePass cliked');
    $.POST("_ajaxCall.php", { formData: $(this).serialize() },
    function(data){
        var json = eval('('+data+')');
        //alert(data);    
        if(json.message=='alert') {
            $('div.info').hide();
            $('div.alert').show().html(json.string);
        }
        if(json.message=='info') {
            $('div.alert').hide();
            $('div.info').show().html(json.string);
        }
    }
    );
    return false;
})

And stop using .live() methods, they have been deprecated now. Use .on() methods.

Read more

converting unicode u sequence (like u041a) to normal utf-8 text in php

Question by QuadroVal

I have a string like this
“u041au043bu0443u0431 Test”;

It was decoded by json_encode(), the original string was “Клуб Test” in russian.
when I put it to js like

alert(“u041au043bu0443u0431 Test”);

I get correct displaying, like on the screen. So js
in some way poperly decodes it to normal view.
The question is how can I do the same thing in php, is there any built in method?

enter image description here


THE ANSWER IS:
$json_in = '{"testKey":"u041au043bu0443u0431 Test"}';
$json_out = json_decode($json_in, true);
or
Convert  "u041au043bu0443u0431" to  "&#x041a;&#x043b;&#x0443;&#x0431;" 
and perform html_entity_decode($str, null, 'UTF-8');

Answer by globin

You probably want HTML entities to print the characters:

  • &#1234; for decimal code
  • &#x12a; for hex code

Answer by Starx

While converting the data, use JSON_UNESCAPED_UNICODE as the options

echo json_encode($text, JSON_UNESCAPED_UNICODE);
Read more

Add content if element is not empty

Question by Puyol

HTML:

<div id="parent"> 
  <div class="child"></div> 
  <div class="child"><p>Div with content<p></div> 
  <div class="child"><img scr="pic.png" alt="Div with picture" /></div>
</div>

Result I want:

<div id="parent"> 
  <div class="child"></div> 
  <div class="child"><h1>title</h1><p>Div with content<p></div> 
  <div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>

My jQuery code:

$(".child").each(function() {
    if ($(this).html != '')
        $(this).prepend('<h1>title</h1>');
});

Result with my jQuery code:

<div id="parent"> 
  <div class="child"><h1>title</h1></div> 
  <div class="child"><h1>title</h1><p>Div with content<p></div> 
  <div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>

So I just want to add a title to every div of a certain class that’s not empty.

Answer by Evan Mulawski

$(".child:not(:empty)").prepend('<h1>title</h1>');

jQuery empty selector

Answer by Starx

Use length to check instead.

$(".child").each(function() {
    if ($(this).html().length)
        $(this).prepend('<h1>title</h1>');
});
Read more
...

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