...

Hi! I’m Starx

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

Syntax error on trying to update empty column row values

Question by Woistmeinhandy

I am trying to add a keyword to empty column / row values in my database but I can’t get it to work. I am getting a syntax error.

Here is the code:

$sql[$handle]['sql'] = 
'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' 
FROM '.$table.'')';

Answer by Starx

You have escaped a quote extra on the end.

$sql[$handle]['sql'] = 
'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' 
FROM '.$table.'')';
//              ^ Right here

Next, you have an extra bracket ) at the end [Credit: Registered User]

$sql[$handle]['sql'] = 
'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' 
FROM '.$table.')';
//             ^ Right here

Solution: Remove them and you should get something like this to work:

$sql[$handle]['sql'] = 'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' FROM '.$table;
Read more

Understanding the output of this javascript code

Question by iamrohitbanga

Having programmed in C/C++, Java I am finding difficulty understanding the output of the following program.

http://jsfiddle.net/iamrohitbanga/nubgw/

var foo = function() {}
foo.prototype.out = function() {
    console.log(this.num);
}
var bar = function() {};

var f = new foo();
f.num = 1;
var b = new bar();
b.num = 2;

console.log(this);           // 1
f.out();                     // 2
foo.prototype.out.call(b);   // 3
foo.prototype.out.call(bar); // 4

I see the following output

Window
1
2
undefined

I have been coding in javascript for a while now and can understanding some of the concepts but not everything is clear to me.

I have a rough understanding.
I feel in the global space this points to the window and hence the first line of output is clear.
For the second line I think since the function out is being invoked on f the value of this in out is f.
For the third one my feeling is that by calling the function with input as b, the value of -this is set to b.
For the fourth one bar is a global object which has no member named ‘num’ in its dictionary.

Is my understanding correct?
Can someone explain the role of ‘this’ and ‘prototype’ in the context of this program? I find the syntax of prototype slightly obscure.
Also in chrome when I press F12 while in gmail window and paste the program in there. The third line of output is undefined and not 2. But in jsfiddle it is two. which seems somewhat creepy. Why is it different?

Answer by Starx

this represents the scope from where the code is executing. In your case, it is the global scope window.

Prototypes in JavaScript are simply an object with properties and methods. You can add members to it and also inherit from it. You can read this article for further information.

Lets break down your code are see this one by one.

  1. f.out();

    This refers too the following object

    var f = new foo();
    f.num = 1; //Here you define a property `num` as 1
    

    Then when you call f.out() the prototyped function will simple log the num

  2. foo.prototype.out.call(b);

    Here you directly access the function and pass an object to the function. Thus when the method is executed, this represents the object that is pass instead, so ends up logging its value.

  3. foo.prototype.out.call(bar);

    On this part, the object bar is an empty object var bar = function() {};, thus the function cannot read its num property, so it outputs as undefined

Read more
September 22, 2012

mask output of the input field

Question by telexper

is there any way to mask the output of the input field once passed to the next page

Enter Card : 123456789011

after the data has been passed onto the next page
when displayed it should look like this

Card info: ********9011

the first 8 digits was converted to asterisk and
the last 4 digits of the card is visible.

Answer by Rhyono

If you’ve already ensured that the card number is a valid length:

card = "123456789011";
output = "********" + card.substring(card.length-4);

is all you’ll need. Output will now be as you wanted, and although Starx’s answer is dynamic: it’s also overkill.

Answer by Starx

Something like this

var card = "123456789011";
var str = "";

//Create the "*" for exactly 4 digits short
for(var i=1; i <= card.length-4; i++) {
   str += "*";
}
//Join the asterisk and last 4 characters
ecard = str + card.substr(card.length-4);

console.log(ecard);

Demo

Read more
September 21, 2012

Ajax Give Response but not Executing the PHP Service

Question by Hatem

Am doing Ajax request to a file which sends a mail. It give me the correct response which is “Message Sent” but the mail not sent. When I try to execute that file from the browser with the same GET Headers , it send the mail.

So what’s the problem here ?

The ajax request working well and triggered using (success) keyword in jquery to make sure that it succeed.

Help me !

For ajax side :

function SendEmail(To, Subject, Message) 
{
 var URL = 'mail-service.php?to=' + To + '&subject=' + Subject + '&msg=' + Message;

$.ajax({
    url: URL,
    type: 'GET',
    success: function (res) {
        alert("Message Sent to : " + To);
    }
});
  }

for PHP side :

<?php
$url = "http://mydomain.com/mail/mail.php?to=".$_GET['to']."&subject=".$_GET['subject']."&msg=".urlencode($_GET['msg']);

$link = fopen($url,"r");

while($res = fread($link,100))
{
    echo $res;
}

fclose($link);
 ?>

Answer by Starx

You misunderstood the function, The success function of the AJAX request executes once the request is successful, it does not care about what the page requested to did or did not.

To ensure you receive correct messages, you have to setup your PHP processing file, to return the response.

In your script

success: function (res) {
    alert(res); //Display the response text
}

And make sure your PHP file, return the response text as output.

while($res = fread($link,100))
{
    echo $res; //Make sure this is like "Message sent" or "Message sending failed"
}
Read more

Style will not apply without using a ','

Question by Norman

I just noticed, using the css code below ignores the .input.cmp bit :

.create input.cmp, input.email, input.pswd, input.pswda{}

while using the code below (with a , before) works fine.

.create ,input.cmp, input.email, input.pswd, input.pswda{}

How is this happening? Is this the right way to do it? Or am I doing something wrong here.

I previously used to use an ID instead of class and things worked fine without the first ‘,’

Answer by Starx

This seems to be like a misunderstanding and logical error .

  1. .create input.cmp, selects input.cmp inside .create
  2. .create ,input.cmp, are two different selectors .create and input.cmp

Here is an simple example:

.create input.cmp selects the input element ONLY in the following HTML

<div class="create">
   <input type="text" class="img" />
</div>

Where as, .create ,input.cmp selects both div and input elements.

Read more

PHP backend / frontend security

Question by William Yang

Hello all,

While taking my time in the bath I though of something interesting. In PHP, how do you tell if the users’ forms submitted is valid and not fraud (i.e. some other form on some other site with action=”http://mysite.com/sendData.php”)? Because really, anyone can create a form that will try send and match $_POST variables in the real backend. How can I make sure that that script is legit (from my site and only my site) so I don’t have some sort of cloning-site data-steal thing going on?

I have some ideas but not sure where to start

  • Generate a one-time key and store in hidden input field
  • Attempt (however possible) to grab the url on which the form is located (probably not possible)
  • Using some really complicated PHP goodies to determine where the data is sent (possible)

Any ideas? Thanks all!

Answer by Nathan Sire

Most of these attempts from hackers will be used by curl. It’s easy to change the referring agent with curl. You can even set cookies with curl. But spoofing md5 hashed keys with a private salt and storing it in session data will stop most average hackers and bots. Keeping the keys stored in a database will add authentication.

Answer by Starx

There are few simple ways like:

  • Checking $_SERVER['HTTP_REFERER'] to ensure your host was the referring script
  • Adding hashing keys in the forms and checking them with the server session variable stored.

But all the above can be manipulated and spoofed in some way. So, you can use CSRF Validations. Here is a very good article on this.

Other additional techniques I have encountered are:

  • Adding time limits to forms and ensure they are submitted with in that time.
  • On every interaction with the form, send AJAX request to validate and reactive the form’s timelimit.
Read more
September 18, 2012

How to stack up a list of divs so there's no vertical gap?

Question by Prabhu

If I have a list (ul/li) of divs (with variable height), is there a way to stack them so that there are no gaps between a div and the div below it? Like the pinterest UI…

    <ul>
         <li>
           <div>...</div>
         </li>
         <li>
           <div>...</div>
         </li>
         ...
    </ul>    

    ul
    {
       list-style-type:none; 
       vertical-align:top;
    }

    li
    {
       list-style:none;    
       vertical-align:top;  
       display:inline-block;   
    }

This is similar to the question here How to make div stack first vertically then horizontally? except that I still want to order it like this:

1 2 3
4 5

Answer by Starx

Following CSS is enough to create that effect

ul, li  { margin: 0; padding: 0 }
ul li { float: left; }
ul li div { background: #f00; color: #fff; }

Demo

Read more

Avoid displaying javascript confirmation when no checkbox is set

Question by peter burg

Like the title says, I have a problem with checkbox validation.
So, I have this line in my php file which displays users.

<a href='#' onclick='if(confirm("Are you sure?"))checkbox.submit()' class='bt_red'><span class='bt_red_lft'></span><strong>Delete items</strong><span class='bt_red_r'></span></a>

in my delete_items.php file I wrote the following :

$checkbox = $_REQUEST['checkbox'];
if(!isset($checkbox)) {
//diplay an error message :"No user selected"
} else {
if(isset($checkbox)) {
// deleting users script
}
}

In the 2 cases, when clicking on the “delete items” , I get the javascript confirmation message, which I don’t want to display when no checkbox is set (the if(!isset($checkbox)) statement).

thank you for help.

Answer by sra

You would want to make the javascript code inside your links onclick statement aware of how many checkboxes have been clicked. This is rather easy. If you use Jquery you can just query them like this:

$("input[type=checkbox]:checked").size();

This just evaluates to how many checkboxes are checked anywhere on your page, so you would have to narrow down the query with a parent element or class or something.

When you have the number of checked checkboxes, its just a matter of some AND and OR like this:

$("input[type=checkbox]:checked").size() > 0 && (confirm("do you really want to do this?"));

The first expression evaluates to true if there are checked checkboxes, so the second expression gets evaluated, otherwise not.

hope this helps

edit: you could also use if instead of or. maybe that’s a little bit more familiar

Answer by Starx

First, there is lot of ambiguous lines in your code. Same thing can be done like this

if(!isset($_REQUEST['checkbox'])) {
  //diplay an error message :"No user selected"
} else  {
  //delete user's script
}

If you dont want the confirm message if no checkbox is set, then you can do this:

<?php if(isset($_REQUEST['checkbox'])) {
        echo '<a href="#" onclick="if(confirm("Are you sure?"))checkbox.submit()" class="bt_red">';
     } else {
        echo '<a href="#" class="bt_red">';
     }
?>
    <span class='bt_red_lft'></span>
    <strong>Delete items</strong>
    <span class='bt_red_r'></span>
</a>
Read more

How do I align a <div> to the center of a <div>?

Question by Gregory Little

I’m using HTML/CSS to make a website and on my home page I have some <div> tags that are inside <div> tags. I can’t seem to get the inner <div> tags to align to the center of the outer <div> tags. Here is the HTML code i am using (the one with the stars next to it is the one that I want to align);

    <div id="container">
<div align="center" id="box" style="background-color:black;width:375px;height:400px;border:0px solid #003300;">
<h1 id="heading"></h1>
<h2 id="otherheading"></h2>
**<div align="center" id="box" style="background-color:white;width:275px;height:225px;border:0px solid #003300;">**
<ul class="list-tick">
    <li></li>
    <hr>
    <li></li>
    <hr>
    <li></li>
    <hr>
    <li></li>
    <hr>
    <li></li>
</ul>
</div>

And this is my CSS:

#container {
  margin: auto;
  width: 1125px;
}

#container div {
  float: left;
  height: 400px;
  width: 375px;
}

Any help will be greatly appreciated. If you have further questions about the problem, I will try and explain in more detail.

Answer by Starx

Remove the floats, and add these

#container div {
  margin: 0 auto; /* Center Horizontally */
  height: 400px;
  width: 375px;
}
Read more

Failed to reload content via Ajax

Question by Dr.Kameleon

OK, so basically this is my issue :

  • I’ve got a dynamic page with a table in it
  • When the user clicks to delete an entry, the entry is deleted from the db and the table is reloaded (via a controller) using Ajax
  • However, even when the content is re-fetched, it keeps showing the PREVIOUS version of my contents (as if the page was somehow cached?). If I reload the whole page, it shows up alright…

What could be going on?

Answer by Bardo

Are you using Chrome?

I’ve found similar behaviours when using ajax calls on Chrome.

If you are using jQuery to do the ajax call you can use the attribute cache: false for the method ajax to avoid this behaviour.

Answer by Starx

Its actually a caching related problem. So, to ensure this, just emulate fresh URI like

$.post("yourupdatepage.php?r="+(Math.random() * (1000 - 1) + 1), 
  ...
);
Read more
...

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