...

Hi! I’m Starx

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

$.post callback return strange data

Miguela Anthony’s Question:

I think this might be the cause of why my code is not working.. The ‘if(name.val().length > 3)’ is never can execute so I put an alert to test the returned data, this is what it look like :

enter image description here

my js

$(document).ready(function(){

    var form = $("#customForm");
    var name = $("#name");
    var nameInfo = $("#nameInfo");
    var email = $("#email");
    var emailInfo = $("#emailInfo");
    var pass1 = $("#pass1");
    var passInfo = $("#pass1Info");
    var pass2 = $("#pass2");
    var pass2Info = $("#pass2Info");
    var state = false;

name.keyup(validateName);

function validateName(){
    if(name.val().length <= 3){
        name.removeClass("valid");
        nameInfo.removeClass("valid");
        name.addClass("error");
        nameInfo.addClass("error");
        nameInfo.text("Minimum 4 characters!");
        state = false;

    }else{

        if(name.val().length > 3){
        var username=name.val();
            $.post('validate.php',{names: username},function(data){
                alert(data);
                if(data!=0){
                    name.removeClass("valid");
                    nameInfo.removeClass("valid");
                    name.addClass("error");
                    nameInfo.addClass("error");
                    nameInfo.text("The username is already taken!");
                    state = false;
                }else{
                    name.removeClass("error");
                    nameInfo.removeClass("error");
                    name.addClass("valid");
                    nameInfo.addClass("valid");
                    nameInfo.text("username available");
                    state = true;
                }
            });

        }
    }    
}
return state;

//end
});

my PHP code :

<?php 
$name = $_POST['names'];
$email = $_POST['emails'];

if($name !=""){
    mysql_connect("localhost","root","") or die("Fail to connect to database");
    mysql_select_db("reglog");

    $uname = mysql_query("SELECT username FROM users WHERE username='$name'");
    $count = mysql_num_rows($uname);

    if($count !=0){
        echo 1;
    }else{
        echo 0;
    }
}

if($email !=""){
    mysql_connect("localhost","root","") or die("Fail to connect to database");
    mysql_select_db("reglog");

    $useremail = mysql_query("SELECT email FROM users WHERE email='$email'");
    $countemail = mysql_num_rows($useremail);

    if($countemail !=0){
        echo 1; 
    }else{
        echo 0;
    }
}

?>

It is throwing an warning. Make a habit of checking if a index is available in an array, thus removing possibilities of such error.

$email = isset($_POST['emails']) ? $_POST['emails'] : '';

or do not display any errors to suppress such warning (not recommended).

And as mentioned by Kai, you haven’t passed any variables as emails.

$.post('validate.php',{ names: username, 'emails' : email }, ... }
Read more
September 10, 2013

Check whether array has keys that don't match a list

Donny P’s Question:

What is the easiest way to check if an has array keys that don’t match a particular list?

$a = array(
  [ignore_me] => "blah blah blah",
  [name] => "Don"
);

does_array_have_non_ignored_entries($a); // returns true

I can think of a ton of ways to write this function, didn’t know if PHP has a quick solution. Best one I have is this:

$length = count($a);
$ignored_entry = (in_array($a, 'ignore_me') ? 1 : 0;
if ($length - $ignored_entry > 0) {...}

How about this?

$count = isset($a['ignore_me']) ? count($a) -1 : count($a);

Substract 1, if that key is found, else use the full length.

Read more

MySQL Select columns which has two matches in other table

Adura’s Question:

I am sorry if this question was already solved, but I did not know how to word my problem properly or what I should search for.

So I have 2 tables:

groups

id | name

memberships

id | user_id | group_id

What I am trying to do is find all groups which the user with id 1 is a member of and also user with id 2 is a member of.
Obviously that does not work:

SELECT groups.id FROM groups, memberships WHERE groups.id = memberships.group_id AND memberships.user_id = 1 AND memberships.user_id = 2;

I hope you understand my issue, I am having trouble finding the right words for the problem. Feel free to ask.

Edit: Both users should be a member of the group.

If I understood well, you need groups where both users are members?

Something like:

SELECT g1.id 
FROM groups g1, memberships m1, groups g2, memberships m2
WHERE m1.group_id = g1.id AND m1.user_id = 1
AND m2.group_id = g2.id AND m2.user_id = 2
AND g1.group_id = g2.group_id;

Try this:

SELECT * 
FROM   groups g 
       INNER JOIN memberships m 
               ON m.group_id = g.id 
WHERE  m.user_id = '1' 
        OR m.user_id = '2' 
Read more

Get the next/previous ID on button click

Reynier’s Question:

I have this HTML:

<form action="" id="product_create" method="post">
    <ul>
        <li id="tab1" data-display="categories-picker"><a href="#">Seleccionar categoría</a></li>
        <li id="tab2" data-display="product-create-step-2"><a href="#">Datos</a></li>
        <li id="tab3" data-display="product-create-step-3" style="display: none"><a href="#">Variaciones</a></li>
        <li id="tab4" data-display="product-create-step-4"><a href="#">Detalles del Producto</a></li>
        <li id="tab5" data-display="product-create-step-5"><a href="#">Condiciones de Venta</a></li>
    </ul>

    <fieldset id="categories-picker">
        ....
    </fieldset>

    <fieldset id="product-create-step-2" style="display: none">
        ....
    </fieldset>

    <fieldset id="product-create-step-3" style="display: none">
        ....
    </fieldset>

    <fieldset id="product-create-step-4" style="display: none">
        ....
    </fieldset>

    <fieldset id="product-create-step-5" style="display: none">
        ....
    </fieldset>

    <button type="button" name="finish-wizard" id="finish-wizard" style="display:none">Finish</button>
</form>

<button type="button" name="previous" id="previous-step" disabled="disabled">« Previous</button>
<button type="button" name="next" id="next-step">Next »</button>

In order to toggle or hide previous/show next I need to get the ID of the previous/next fieldset element when I click on $(input[name="next"]) or $(input[name="previous"]) but I made this code:

var first = $('fieldset').eq(0).attr('id');
var step = 1;

$('#next-step').click(function() {
    if (step >= 1) {
        $("#previous-step").removeAttr("disabled");
    }

    var current = $('fieldset').eq(step).next('fieldset');
    var previous = $('fieldset').eq(step).prev('fieldset');
    current.show();
    previous.hide();
    step++;
});

$('#previous-step').click(function() {
    var current = $('fieldset').eq(step).next('fieldset');
    var previous = $('fieldset').eq(step).prev('fieldset');
    current.hide();
    previous.show();
    step--;
});

But it’s not working fine, can any give me a help?

This is probably simpler, duplicate the functionality with .prev() instead of .next() to get the code for the prev button.

$('fieldset.step').hide().eq(0).show();

$('#next-step').click(function() {

    var current = $('fieldset.step:visible'),
        next = current.next('fieldset.step');
    if (next.length === 0) {
        next = current.nextUntil('fieldset.step').next('fieldset.step');
    }
    current.hide();
    next.show();
    if (next.nextUntil('fieldset.step').next('fieldset.step').add(next.next('fieldset.step')).length === 0) {
        $("#next-step").prop("disabled",true);
    }
    $("#previous-step").prop("disabled",false);
});

$('#previous-step').click(function() {

    var current = $('fieldset.step:visible'),
        prev = current.prev('fieldset.step');
    if (prev.length === 0) {
        prev = current.prevUntil('fieldset.step').prev('fieldset.step');
    }
    current.hide();
    prev.show();
    if (prev.prevUntil('fieldset.step').prev('fieldset.step').add(prev.prev('fieldset.step')).length === 0) {
        $("#previous-step").prop("disabled",true);
    }
    $("#next-step").prop("disabled",false);
});

don’t forget to give the fieldsets that need to be cycled through a .step class. The id’s are no longer needed.

Fiddle

Since you are tracking the elements with their indexes, you can simply select the next and previous element using simple technique like

var previous = $('fieldset').eq(step-1); // To select previous

var next = $('fieldset').eq(step+1); // To select next 

But I think you are trying to create this effect: http://jsfiddle.net/c48bs/

Read more

Labels do not want to center using php

User2747140’s Question:

I am new to php and apologise for the trivial question I’m asking. I can’t seem to get my labels to center align. As you can see from the attachment, only the text box get’s centered. Please could you point me in the right direction?

Here’s the code. As you can see, I use the center at the start and the end of my form.

echo"   <center>    <fieldset>
        <div class="form-horizontal">
             <h7 class="label"><font color="#FF0000" size="+1"><strong>* </strong></font>: Required Fields</h7> <br><br>
            <div class="form-row">
            <div class="form-label">First Name <font color="#FF0000" size="+1">*</font><em></em></div>
                <div class="form-controls">
                   <input id="First Name" type="text" name="FirstName" value="$firstname">       
                </div>
                </div>

                <div class="form-row">
                <div class="form-label">Last Name <font color="#FF0000" size="+1">*</font></div>
                <div class="form-controls">
                    <input id="Last Name" type="text" name="LastName" value="$LastName">      
                </div>
                </div>

                <div class="form-row">
                <div class="form-label">ID Number <font color="#FF0000" size="+1">*</font></div>
                <div class="form-controls">
                  <input name="IDNumber" type="text" id="ID Number" value="$IdentityNumber" maxlength="13">       
                </div>
                </div>

                <div class="form-row">
                <div class="form-label">Email Address</em></div>
                <div class="form-controls">
                   <input id="Email Address" type="text" name="EmailAddress" value="$ParentEmailAddress">             
                </div>
                </div>


                <div class="form-row">
                <div class="form-label">Mobile Number <font color="#FF0000" size="+1">*</font></div>
                <div class="form-controls">
                     <input name="MobileNumber" type="text" id="Mobile Number" value="$ParentMobileNo" maxlength="10">         
                </div>
                </div>

                <div class="form-row">
                <div class="form-label">Date of Registration <font color="#FF0000" size="+1">*</font></div>
                <div class="form-controls">
                    <input id="Date of Registration" type="text" name="DateofRegistration" value="$DateOfRegistration">      
                </div>
                </div>


                <div class="form-row">
                <div class="form-label">Learners Full Name <font color="#FF0000" size="+1">*</font></div>
                <div class="form-controls">
                   <input id="Learners Full Name" type="text" name="LearnersFullName" value="$LearnerFullName">       
                </div>
                </div>

                <div class="form-row">
                <div class="form-label">Learners Date of Birth <font color="#FF0000" size="+1">*</font></div>
                <div class="form-controls">
                   <input id="Learners Date of Birth" type="date" name="LearnersDateofBirth" value="$LearnerDOB">    
                </div>
                </div>

                <div class="form-row">
                <div class="form-label">School Nominated <font color="#FF0000" size="+1">*</font></div>
                <div class="form-controls">
                <select id="School Nominated" type="text" name="SchoolNominated">
                    </center>";

I have tried adding a picture to show you the form. Please go to this link to view it (http://i.stack.imgur.com/lIAFG. png)

Use CSS, not PHP to center text. The following will center all the labels.

label { text-align: center; }
Read more

how to get php variable in javascript

User2746093’s Question:

I want to get value of $security_code which is in captchaCode.php file, in captcha.php file through javascript.I can not include this file in captcha.php file . Here is the code of Captcha_code.php and this code not comes inside any function of this file:

$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));

And here is my javascript function, through this function i want to get the value of $security:

function refresh_captcha()
{
    var img = document.getElementById('captcha_img');
    img.src = '<?php echo "/captcha_images.php"?>';
    jQuery("#captcha_img").attr("src",img.src);
    jQuery("#security_code").val("<?php echo $security_code;?>");
}

Actually this code is for getting new encrypted value when captcha is refreshed without refreshing the page.

Send an ajax request to a page to output only the code like:

File: outputcode.php (demo only)

$captcha = new CaptchaCode();
$security_code = str_encrypt($captcha->generateCode(6));
echo $security_code;
exit;

Next, grab that value using AJAX, like for example in jQuery

$("#refresh_code").on('click', function() {
   $.get("outputcode.php", function(data) {
      //data will now hold the new code
   });
});

Hope this gives you an idea.

Read more

The need for JS functions which are self executing?

Bhb’s Question:

What is the use of functions which self execute?

(function(w,d) {...})(window, document);

And why do they pass window/document which are global functions?

Why do they pass window/document which are global functions?

So that inside that function scope window and document will be available as w and d.

One of the common practice of this is included with jQuery plugin development as:

(function($) {
   //...
})(jQuery); 

Since $ can be used in prototype too, this can create anamolities when mixing two libraries, but inside above function, $ will only represent jQuery but not prototype.

Read more

Is it a good practice to use php code inside javascript?

Nabeel Sheikh’s Question:

I heard lot of experts saying entering php code inside javascript is not a good practice. I wanted to know if it’s true. If yes, then will it effect the performance? or is there any other reasons?

For example:

<?php
$num=1;
?>

<script>
var x = "<?php echo $num;?>";
</script>

NO it will not effect the performance, but it affects manageability and security.

In your case, can your javascript function without knowing the value of num? or Are you just developing the JS script from PHP? Latter is the use you should avoid.

Lets take an example where num was used to know the number of items in shopping cart. Now thats a very vital piece of information, but since its JS, it can easily be manipulated. In such case, you should store such sensitive information on the server and not on the client.

Read more

Extract string from a tag using php

User1432345’s Question:

How to extract the link domain name using php.

Eg,

Search engine <a href="http://www.google.com">Google Search</a> and <a href="www.yahoo.co.in">Yahoo Search</a>

I need from this –

Search engine google and yahoo

You can remove all the HTML tags using strip_tags() (as stated in comments)

$text = 'Search engine <a href="http://www.google.com">Google</a> and <a href="www.yahoo.co.in">Yahoo</a>';
echo strip_tags($text); //This will give only the text
Read more

Using Anonymous functions in php 5.2

Raj’s Question:

I know Anonymous functions are supported only in php5.3 and above.

But due to some difficult circumstances , I have to use the code below in php 5.2

Can anybody please help me to convert this to work in php 5.2

====================================================

       $fn = function($points) use ($pdf) {
        $op = 'f';
        $h = $pdf->h;
        $k = $pdf->k;
       $points_string = '';
       for($i=0; $i < 8; $i+=2){
       $points_string .= sprintf('%.2F %.2F', $points[$i]*$k,($h-$points[$i+1])*$k);
            $points_string .= $i ? ' l ' : ' m ';
       }
       $pdf->_out($points_string . $op);
    };

====================================================

The full code is available at

http://barcode-coder.com/download/php-barcode-2.0.3.zip

I have now tried for hours with create_function but somehow can get this to work.

Please help me to adapt this to php5.2

Also how to duplicate the functionality of use in php5.2

ie how to pass a var like $pdf to create_function

Just sent the variable as parameter:

function fn($points, $pdf) {
        $op = 'f';
        $h = $pdf->h;
        $k = $pdf->k;
       $points_string = '';
       for($i=0; $i < 8; $i+=2){
       $points_string .= sprintf('%.2F %.2F', $points[$i]*$k,($h-$points[$i+1])*$k);
            $points_string .= $i ? ' l ' : ' m ';
       }
       $pdf->_out($points_string . $op);
};
Read more
...

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