...

Hi! I’m Starx

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

user registration and email activation

Question by user1349179

I have the following code for registration–

<?php 
 // Connects to your Database 
 mysql_connect("my serner", "user", "password") or die(mysql_error()); 
 mysql_select_db("ec09580") or die(mysql_error()); 
 //This code runs if the form has been submitted
 if (isset($_POST['submit'])) { 
 //This makes sure they did not leave any fields blank
 if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['username']) && isset($_POST['pass1']) && isset($_POST['pass2']))
           {
            $fname = $_POST['firstname'];
            $lname = $_POST['lastname'];

            $email_id = $_POST['email'];

            $username_r = $_POST['username'];
            $password_1 = $_POST['pass'];
            $password_2 = $_POST['pass2'];

//if (!$_POST['firstname'] | !$_POST['lastname'] | !$_POST['email'] | !$_POST['username']| !$_POST['pass2'] ) {

        //die('You did not complete all of the required fields');
        //}

 // checks if the username is in use
    if (!get_magic_quotes_gpc()) {

        $_POST['username'] = addslashes($_POST['username']);
    }
 $usercheck = $_POST['username'];
 $check = mysql_query("SELECT username FROM User WHERE username = '$usercheck'") 
or die(mysql_error());
 $check2 = mysql_num_rows($check);

 //if the name exists it gives an error
 if ($check2 != 0) {
        die('Sorry, the username '.$_POST['username'].' is already in use.');
    }
 // this makes sure both passwords entered match

    if ($_POST['pass'] != $_POST['pass2']) {
        die('Your passwords did not match. ');
    }
    // here we encrypt the password and add slashes if needed

    $_POST['pass'] = md5($_POST['pass']);

    if (!get_magic_quotes_gpc()) {
        $_POST['pass'] = addslashes($_POST['pass']);
        $_POST['username'] = addslashes($_POST['username']);
    }
}
 // now we insert it into the database
    $insert = "INSERT INTO User set FirstName='$fname', LastName='$lname',  Email='$email_id', username='$username_r', password='$password_1'";
    $add_member = mysql_query($insert);
    ?>
 <h1>Registered</h1>
 <p>Thank you, you have registered - you may now login</a>.</p>
 <?php 
 } 
 else 
 {  
 ?>
 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
 <table border="0">
 <tr><td>Firstname:</td><td>
 <input type="text" name="firstname" maxlength="60">
 </td></tr>
 <tr><td>LastName:</td><td>
 <input type="text" name="lastname" maxlength="60">
 </td></tr>
 <tr><td>Email:</td><td>
 <input type="text" name="email" maxlength="60">
 </td></tr>
 <tr><td>Username:</td><td>
 <input type="text" name="username" maxlength="60">
 </td></tr>
 <tr><td>Password:</td><td>
 <input type="password" name="pass" maxlength="10">
 </td></tr>
 <tr><td>Confirm Password:</td><td>
 <input type="password" name="pass2" maxlength="10">
 </td></tr>
 <tr><th colspan=2><input type="submit" name="submit" 
value="Register"></th></tr> </table>
 </form>
 <?php
 }
 ?> 

And for activation I have the following code–

<?php
if (isset($_GET['x'])) {
    $x = (int) $_GET['x'];
} else {
    $x = 0;
}
if (isset($_GET['y'])) {
    $y = $_GET['y'];
} else {
    $y = 0;
}
if ( ($x> 0) && (strlen($y) == 32)) {
    require_once ('mysql_connect.php');
    $query = "UPDATE User SET active=NULL WHERE (id=$x AND active='" . $y . "') LIMIT 1";  
    $result = mysql_query($query);

    if (mysql_affected_rows() == 1) {
        echo "<h3>Your account is now active. You may now log in.</h3>";
    } else {
        echo '<p><font color="red" size="+1">Your account could not be activated. Please re-check the link or contact the system administrator.</font></p>';
    }
    mysql_close();
} else {
    echo '<b>Activation link not valid!</b>';
}
?>

I keep on getting this error-

Notice: Undefined variable: fname in /var/www/users/ec09580/project_test/r_test.php on line 87 
Notice: Undefined variable: lname in /var/www/users/ec09580/project_test/r_test.php on line 87 
Notice: Undefined variable: email_id in /var/www/users/ec09580/project_test/r_test.php on line 87 
Notice: Undefined variable: username_r in /var/www/users/ec09580/project_test/r_test.php on line 87 
Notice: Undefined variable: password_1 in /var/www/users/ec09580/project_test/r_test.php on line 87 

I am confused waht to do. Can anyone please help me? Thankyou.

Answer by Starx

Notice: Undefined …

Errors of this type are thrown, when the instance you are using is not instantiated yet.


The variables you are using in the query is not instantiated on all the execution flow. So, receive that error.

This can be eliminated by using isset() to check if the variable has been set before or not.

For example:

$fname = isset($fname) ? $fname : '';
Read more
April 21, 2012

Fade In CSS class

Question by Connor

I’m wondering how I can fade in a css class with jquery. The effect I’m looking for is sort of like what you see here: https://squareup.com/

What I’ve tried so far is this:

$(document).ready(function() {
    $('.mini-nav li').hover(function () {
    $('.hover').fadeIn(slow);
};
});

I thought about the .addClass() method, but I’m not sure where to add it (or if that is the best thing to do).

EDIT: Here is a fiddle of something I’ve tried: http://jsfiddle.net/J93NR/1/

Answer by Lie Ryan

you don’t need jquery for this, a pure CSS solution is much simpler (fiddle):

<div class="outer"><div class="inner"></div></div>

.outer {
    background: url(...);
}
.inner {
    background: url(...);
    opacity: 1;
    transition: opacity 0.3s;
}
.inner:hover {
    opacity: 0;
}

http://jsfiddle.net/ZAgnY/

Answer by Starx

If you are using jQuery UI, there is an option to animate using the class using switchclass()

Update:

$("element").addClass("classname").fadeIn("slow");
Read more
April 20, 2012

Php script stops after long time and no error could be found on the error_log

Question by Miki Amit

Im running a long php script which handles large amounts of data.

The problem is that the script suddenly stops and no exception is thrown or could be found on the error_log.
I have set the display_errors and the error_logging to 1 in the .ini config file.

Few more details:
1) The scripts executes the ‘file_get_contents’ function for many times.
2) The scripts contains recursion when the file_get_contents fails.
Any help would be appriciated.

Answer by Starx

It might have hit the max execution time.

set_time_limit(0); // to increase the timelimit to infinity
Read more

How to prepare a list of values based on a form's text inputs?

Question by Rachela Meadows

Given the following form:

<form class="email-form" action="" method="PUT" data-remote="true" data-method="put">
  <ul>
    <li>
      <label for="sEmail1">
        <input type="text" id="sEmail1" name="emails[]" value="d@google.com"
               placeholder="">
      </label>
    </li>
    <li>
      <label for="sEmail2">
        <input type="text" id="sEmail2" name="emails[]" value="d2@google.com"
               placeholder="">
      </label>
    </li>
    <li>
      <label for="sEmail3">
        <input type="text" id="sEmail3" name="emails[]" value="d3@google.com"
               placeholder="">
      </label>
    </li>
  </ul>
  <button type="submit">Continue</button>
</form>

How can I use query to get the full list of emails and post it as follows to rails:

Parameters: {"emails"=>{"list"=>["d@google.com", "d2@google.com","d2@google.com"]}}

I have the following:

    $.ajax({
        type: 'POST',
        url: '/send_invites',
        data: {
            emails : {
                list : $('.email-form').serialize()
            },
            _method : 'PUT'
        },
        success : function() {
        }
    });

Answer by Starx

Here is a way to do that

var listval = [];
$("input['name=emails[]']").each(function() {
    listval.push($(this).val());
}
Read more

Getting Div's to align side by side in narrow browser

Question by Dave

http://jsfiddle.net/ZGhEe/

I’ve read several tutorials and they all say use float or use relative positioning, but all the techniques I try aren’t giving me expected results. This is a pretty simple thing to do, but I want to do it the “correct” way since using html tables is punishable by death. Any help?

If I use float left it stacks unnecessarily when the browser gets narrow..

Answer by Lie Ryan

When using float and you want it to show side-by-side, you need to set the width and make sure the sum of the widths are less than the width of the container, like so.

Answer by Starx

If you want to make your browser fit it all of the browser. Make your browser fluid.

i.e. Give % while defining the width of the layout.

Read more

jquery contact form php issue

Question by itom07

So I have a contact field which sends an email when submitted, I want to have the javascript alert when complete but am returning issues.

The javascript:

jQuery(document).ready(function() {

    $.ajax({
        url: './contactengine.php',
        type: 'GET',
        dataType: 'JSON',
        success: function(response) {
                        alert("GOOD");
                },
        error: function() {
                        alert("BAD");
                }
    });

});

The php:

<?php

$EmailFrom = "emailname@gmail.com";
$EmailTo = "emailto@gmail.com";
$Subject = "new contact from website";
$Name = Trim(stripslashes($_POST['Name'])); 
$company = Trim(stripslashes($_POST['company'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Message = Trim(stripslashes($_POST['Message'])); 

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv="refresh" content="0;URL=error.htm">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "n";
$Body .= "company: ";
$Body .= $company;
$Body .= "n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success)
{
    $result = array('success' => true);
}
else
{
    $result = array('success' => false, 'message' => 'Something happened');
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
  echo json_encode($result);
?>

When I submit the form I get redirected to a page which says the following:

{"success":true}

When I should be staying on the same page and just alerting good.

Answer by jammypeach

The problem here is in your script I think, from the behaviour you describe it sounds like your PHP is doing the job.

I’ve made a few corrections to the ajax call based on the PHP code, try this and see if it helps.

$.ajax({
        url: 'contactengine.php', //removed ./ - that's wrong I think
        type: 'POST',  //you are accessing $_POST not $_GET in the PHP file
        data: $('myform').serialize(), //you need to send some data atleast
        dataType: 'JSON',
        success: function(response) {
                        alert("GOOD");
                },
        error: function() {
                        alert("BAD");
                }
    });

What I’ve done is removed ./ from the front of your URL – it should be either nothing, / for the root directory, or ../ for one directory up from the current directory. If the file is in the same directory as your page, keep it like I’ve done.

I’ve changed type from GET to POST – you are accessing the PHP $_POST global in your script, so the PHP would have been looking in the wrong place for variables.

Last but not least, I’ve put some data in. You need to pass in those variables that the PHP expects – so I’ve used a serialize() call. Replace the jQuery selector so that it will target your form, and it should pass in everything in your form to the PHP.

For more detail on the jQuery ajax function, see here: http://api.jquery.com/jQuery.ajax/

Hope this helps

Answer by Starx

Where is the data?

Plus You defined the request type as GET, but reading them as POST too. Send datas like this inside and change the request type to post

   $.ajax({
        url: './contactengine.php',
        type: 'POST',
        data: { variable1: "value1", .... }
        dataType: 'JSON',
        success: function(response) {
                        alert("GOOD");
                },
        error: function() {
                        alert("BAD");
                }
    });
Read more

Page reload doesn't reset jQuery / CSS styles

Question by Emerson

I’m designing an HTML page which has one button. The user clicks the button and a simple jQuery script animates that div away, revealing lower page content. You can see it here.

I’ve noticed that it looks/works fine the first time, but if I refresh the page with the browser button, it doesn’t fully reset. The initial container is only half on the page. If I enter the URL again and load the page, it resets as expected.
NOTE: This only happens if you scroll down a bit after clicking the initial button… which seems weird.

I had no idea that there was any difference between these two operations, but there clearly is. What is the difference and how can I fix this problem from happening?

Here’s my jQuery code, in case it’s relevant:

    $(document).ready(function(){

    var faqs = $("#FAQ");
    $("#learnmore").click(
        function(){
            $("#home").animate({top:'-=1066px'},600);
            $("#more").animate({top:'-=1066px'}, 600, function() {$("#background").hide();} );
            $("body").css('overflow-y', 'scroll');

            //$("#home").slideUp();
            console.log("jquery loaded");
            }
        );

});

Answer by happyproff

It happens because browser trying to scroll to the same position, what was before page reload. To check it, try press button and don’t scroll to bottom of page and then reload page.
Okey, the reason is clear.

Now we need solution. Try this:

#more {display:none}

in your css. And then use

$("#more").show().animate(...

in your $("#learnmore").click() function. I hope this will solve the problem.

Answer by Starx

It happens because it is cached by the browser.

If you styles are regularly modiefied, then as easy fix is to attach a unique id on the end of the reference, like

<link href="style.css?time=168768234928" ..../>

What it does, it makes the browser think it is a new request everytime it loads.

Read more

How can I detect (and correct?) various scroll bar visibilities cross-browser?

Question by Alan H.

Basically, I need to have (or fake) scrollbars showing up exactly at the same times in textarea and in a div (with white-space: pre-wrap, so as to treat whitespace the same), when their contents are the same.

In Webkit, this is easy:

textarea.foo, div.foo {
  overflow: auto; /* show scrollbars exactly when needed */
  /* also match padding, height, width, font, line-height, etc. */
}

But some other browsers (Firefox on OS X, I think, and IE7) will actually show a scrollbar on only the textarea and not the div (or vice versa) when the content isn’t long enough to require scrolling.

For clarity, I am not demanding that scrollbars show the same across all browsers. I need this to be true in all major browsers: A div and a textarea show scrollbars exactly whenever the other element does, given the same content, within the same browser. If that’s sometimes, always, or (on Safari/OS X Lion) never is inconsequential.

Answer by Starx

Configure the scroll bar to show up all the time

textarea.foo, div.foo {
  overflow-y: scroll; /* Show vertical scroll bars at all time 

}
Read more

Center text inside relative div with no size

Question by tomash

I have following (simplified) HTML structure:

<table>
  <tr>
    <td>
      <div class="PromptContainer">
        <span class="Prompt">Prompt text</span>
      </div>
      <input type="text" name="..."/>
    </td>
  </tr>
</table>

and CSS:

.PromptContainer{
   width: 0;
   height: 0;
   position: relative;
   margin: 0 auto;
}

.Prompt{
   bottom: 0;
   padding-left: 0;
   white-space: nowrap;
   position: absolute;
}

I want to center span element over input element. Note that I cannot change size of .PromptContainer because of edge alignment rules (.Prompt element could be aligned to any edge of input element). The text inside span element has variable length and may be longer than width of input element. I cannot use javascript to perform this task, because it is too ineffective in my case (large number of such elements).

Edit:
Image visualizing what I have and what I want to achieve is available here: enter image description here

Edit 2:
Let me describe purpose of this question. We are writing new web-based runtime for giant old application written in even older technology (which worked as windows application). We have created converter from source code of this application to our new environment (ASP.NET). All controls in this old application are absolutely positioned, so we do it in the same way. Control (e.g. table of input tags) has its position and size, as well as prompt text associated with it. Prompt text is positioned relatively to control, so we don’t know its absolute position during translation. Note that it depends on font settings, text, offset from control and edge of control to which the prompt is attached.

I’m trying to write a CSS rule to position prompt in right place. I’ve resolved almost all configurations, but I have big problem with centering.

Because of absolute positioning, I cannot use .PromptContainer with non-zero size – I only know position of control, not the .Prompt itself. Bigger .PromptCointainer would move entire control down.

Additionally prompt text longer than control width must not change size of control.

Answer by Starx

How about this?

.Prompt { display: inline-block; margin: 0 auto; }
Read more

PHP Session Variables – passing through pages

Question by ez007

Im hoping someone can point me in the right direction of where im going wrong as I feel like im going around in circles!

Im putting together a simple shopping applications – its only very basic at the moment to demonstrate techniques.

The scenario is that there is one database table with items in. They have been split into a blue and red range of items.

On the index page the user has the option of going to either the blue or red items.

Once on the red (or blue) items page, items are displayed and current price and stock level is pulled from the database (MySQL). The user then selects one item and clicks the buy button to add it into their cart.

The page then redirects to the shopping cart page where the user can either update the quantity of the item, proceed to the checkout page or return to the ‘red’ or ‘blue’ ranges.

My issue is this…..

1) How do I set up my session array to capture the items as they are added on the buy ‘click’?

So far I have this on the top of all pages…

<?php session_start();
?>

However only one item seems to be able to be added to the ‘cart’.

This is how im pulling items from my DB:

<?php
$result = mysql_query ('SELECT * FROM items WHERE colour="red"');
// fetch the resulting row as an associative array
while ($row = mysql_fetch_assoc ($result)){
  echo '£', number_format( $row ['price'] / 100, 2, '.', ' ' );
  }
?></p>

2) This is the code for the form action under each item on either the red or blue page.

<form method="post" action="cart.php">
                    <p>
<input type="submit" name="submit" value="Buy" />
<input type="hidden" name="cart" value="add" />
<input type="hidden" name="item" value="redplate" />
                    </p>
                </form>

3) How do I display the ‘ordered’ item in the checkout page after any quantity updates on the shopping cart page?

So far this is what it on the shopping cart page – would I repeat this on the checkout page pulling with it the updated quantity??….

<?php
$submit = $_POST["submit"];

//Call the function and save all data into the array $_SESSION['form'] 
if($submit == "Buy"){setSessionVars();} 

function setSessionVars() {

    $item = array();
    foreach($_POST as $fieldname => $fieldvalue) {
        $item[$fieldname] = $fieldvalue;
    }  
    $_SESSION['cart'] = $item;

          echo "            <table> 
          <tr> 
            <td> 
                <img src="images/{$item['item']}.jpg" />
                    <td/> 
            <td>
                {$item['item']} =
                    </td>
            <td> 
            <input type="text(5)" name="value" value="1" />

            <input type="submit" name="puchasedquan" value="Click to update" /> 

             </td> 
            </tr> 
                            </table>";
}
?>

Any help would be greatly appreciated!! I feel as if i’m traveling around in circles!

Answer by Starx

The big mistake here is, you are putting all you datas on one session variable altogether, i.e. $_SESSION['cart'].

Since you want to insert multiple item on the sessions, you have use $_SESSION['cart'][] to insert the items.

Whenever you are trying to get the values stored, again use a for loop to read as well as .

foreach($_SESSION['cart'] as $cartItem) {
  $cartItem; // will have all the item individually on each pass
}
Read more
...

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