...

Hi! I’m Starx

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

How to create a new object from an existing one?

Question by defunct

This doesn’t work, and I have no idea how to fix it

function bar() {...}

function foo() {
    this = new bar();

    this.newfunction = function() {...};
    this.newvalue = "foobar";
}

var foobar = new foo();

Thanks in advance,

Answer by dfsq

Are you trying to inherit from bar? Then you can borrow its constructor and all its own properties using call (or apply):

function bar() {...}

function foo() {
    bar.call(this);
    this.newfunction = function() {...};
    this.newvalue = "foobar";
}

var foobar = new foo();

Answer by Starx

Do not use this to represent another object.

function bar() {...}

function foo() {
    var bar = new bar();

    bar.newfunction = function() {...};
    bar.newvalue = "foobar";
}

var foobar = new foo();
Read more

Get only one array from the $_SESSION variable

Question by Nadia Shiwdin

I have an array that stores in a session variable. However I want to send only one part of the array in the SESSION variable to another page depending on which button is clicked.

The code for the button

foreach($name as  $bookname => $name){
        echo "<div class='control-group' align='center'><h4>$bookname</h4><a href='/handler' class='btn btn-large btn-block btn-primary' type='button'>follow $name</a></ul></div>";    
        $_SESSION['name'] = $name;
        $_SESSION['bookname'] = $bookname
        print_r($_SESSION['name']);

        }

The print_r gives me each in the array, what I want to do is when the button is clicked only the $name for that button is set as the $_SESSION. The way I have it now it sets the SESSION for only the last part of the array.

Answer by Starx

It works for only last part, because of the loop overrides every preceding value.

If you want to set the value in SESSION after it is clicked, you have to send the request to a different page (HTTP GET or POST request) or an AJAX request to set the values.

Read more

trigger function from autocomplete input selection

Question by Bwyss

I have an input field that will autocomplete an address, I want an address selection to trigger a function.

html

Address: <input id="searchTextField" type="text" autocomplete="on" runat="server" />

JS

$('input[searchTextField]').bind('autocompleteSelect', function() {
  // some code...
});

I feel like I’m not anywhere close with the above…

Answer by Starx

I think you are trying to do this.

$("#searchTextField" ).autocomplete({
    change: function( event, ui ) {
        // The code you want after selection is made
    }
});
Read more

php form and onsubmit javascript function call

Question by user1060187

I’ve created a form with html being echoed in PHP and am trying to call a Javascript function in the same form. I’ve copied and pasted the js part which I have put in my head tags at the top of the php file.

<script>
    function validate(){
        alert("You need to enter the date in format dd-mm-yyyy");
    }
</script>

Further on I have this at the start of the form

echo "<form method="post" action="index.php" onsubmit="validate()">
        <br>
        <span>Name: <input type="text" name="name" value="$name"></span>"

Is it possible to call javascript from php in the same document?
Cheers

Answer by Starx

You need to make your function available when it is executed.

window.onload = function() {
    function validate(){
        alert("You need to enter the date in format dd-mm-yyyy");
    }
};
Read more

Search code error

Question by IMEzzat

I have a php/ mysql search code like the following:

error_reporting(E_ALL);
ini_set('display_errors', '1');

$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
    $searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['searchquery']);

    if($_POST['filter'] == "user"){
        $sqlCommand = "SELECT id, username AS title FROM users 
          WHERE MATCH (username,email) AGAINST ('$searchquery')";
    } else if($_POST['filter'] == "email"){
        $sqlCommand = "SELECT id, blog_title AS title FROM blog 
          WHERE MATCH (blog_title,blog_body) AGAINST ('$searchquery')";
    }

    include_once("php_includes/db_conx.php");

    $query = mysql_query($sqlCommand) or die(mysql_error());

    $count = mysql_num_rows($query);
    if($count > 1){
        $search_output .= 
          "<hr />$count results for <strong>$searchquery</strong>
           <hr />$sqlCommand<hr />";

        while($row = mysql_fetch_array($query)){
            $id = $row["id"];
            $title = $row["title"];
            $search_output .= "Item ID: $id - $title<br />";
        } // close while
    } else {
        $search_output = 
          "<hr />0 results for <strong>$searchquery</strong>
           <hr   />$sqlCommand";
    }
}

When I run this code I got the following errors:

Warning: mysql_query() [function.mysql-query]: Access denied for user 'famebox'@'localhost' (using password: NO) in /home/famebox/public_html/search.php on line 15

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/famebox/public_html/search.php on line 15
Access denied for user 'famebox'@'localhost' (using password: NO)

Answer by Starx

Access denied for user ‘famebox’@’localhost’ (using password: NO)

Your database username and password and possibly the database name is incorrect. Check these details and verify them.

Above error message says you haven’t specified a password.

Read more

Is it bad practice to shadow variables of a callback?

Question by hexacyanide

Take the asynchronous Node function fs.stat() for an example. If I need to use fs.stat() on a file, then do it again later, the result is shadowed.

fs.stat(file, function(err, stats) {
  fs.stat(file, function(err, stats) {
  });
});

The err variable, as well as stats variable is shadow – does this even matter if I won’t be using the first callback inside the second? Is it better practice to rename the second callback variables?

Does overwriting these variables, once, or multiple times have any performance impact?

Answer by Starx

Yes, it is bad practice. Depends on a developer viewing it of how bad it can get. If I got something like this, the first thing to pop in my mind would be

Why is he passing the err and stats to this callback?

fs.stat(file, function(err, stats) {
                        \    \
                         \    \
  fs.stat(file, function(err, stats) {
  });
});

When working in multiple instances of same function like you are doing right now. You have to make sure that all the variables can be accessed independently.

Unless you are sure one variable or construct is no longer is use, then you can re use that. But you have to mention this in a helpful comment to ensure another developer understands it.


Update:

Those variables on the callback functions have a scope limit, so they will not affect outside the function declaration.

An example of a valid case is:

  fs.stat(file, function(err, stats) {

  });

  //Another similar functions somewhere with same varialbes
  fs.stat(file2, function(err, stats) {
  });
Read more

Suppress notice when passed array is a key and not array

Question by Mauritz Swanepoel

I have a simple function which should check if the passed in parameter is an array and has values. The function works perfectly except in the event when I pass a multi-dimensional array as the property. I suspect the isset() passes but because the key may possibly not exist it gives an undefined:

 <?php
 $array1 = array("John","Doe");
 $array2 = array();

 function valid_array($array) {
     if (is_array($array) && count($array) > 0) {
         return true;
     }
     return false;
 }

 // Below works great:
 valid_array($array1);

 // If I pass the following I get the notice 
 // Notice: Undefined index: sample_key in ....:
 valid_array($array2['sample_key']);     


 ?>

Any ideas?

Answer by Starx

That means, there is no array item as sample_key as its key. Use isset() to verify that, don’t suppress it.

if(isset($array2['sample_key'])) 
    valid_array($array2['sample_key']); 

Such cases are called Exceptions catch them and throw an error instead.

Here is a way to raise an error upon use.

function valid_array(array $array) {
                 //    ^ Asks for a generic array to be passed
     if (is_array($array) && count($array) > 0) {
         return true;
     }
     return false;
 }
Read more

Filtering table rows based on tags in the last coloumn

Question by DJDavid98

I set up a JSFiddle here: http://jsfiddle.net/DJDavid98/w2Xbd/

I have this page with quite a few table rows, from which the last row contains some tags. When the user clicks on one of the tags, I want to hide (fade out) all the rows that doesn’t have that given tag.

My attempts at making this work failed horribly, and I literally have no more ideas.

It works the way it is right now, but the thing is, it only shows the rows that only have that class in it, and no others. I need to expand the function so it’ll check for all the tags and decide if the row should be hidden or not.

Here is some related JS, that does what it does currently:

$('tbody td.type .tag').on('click',function(){
    var type = ($(this).attr('class')).replace(/tag /g,'');
    $('#tagSearch').fadeOut('fast',function(){
        $('#tagSearch').html(typesReverse[type]).attr('class','tag '+type).fadeIn('fast');
        $('tbody td.type .tag').each(function(index){
            if (!$(this).hasClass(type)) $(this).parent().parent().slideUp('fast');
        });
    });
})

Answer by Starx

I don’t understand the need for such complexity but, there is way to select all the element except some exceptions. Like:

$("tr:not('.type')")

Will select all the rows with does not have .type as its class. Use them like this (just an example)

$("tr:not('.type')").hide();
Read more
March 9, 2013

Stop code after if statment from excuting when error occurs

Question by shnisaka

This is what my code looks like:

if($allthevaluesarenotempty) {
    if($pictureexist) {
        // upload picture code
    }
    else
    {
        $message = "error";
    }

    // sql query here
}

How can I stop the SQL query from executing when $message is set?

Answer by Starx

  • If in case of loops like while, for and foreach, you can use continue; to escape the iteration and break; to end the loop.

  • In function return false; will stop the execution.

  • In a PHP document, exit() will terminate further execution of the script.

So, use which is suitable.

Read more

Javascript Canvas Sizes

Question by user1460819

I have a canvas on a HTML page:
<canvas id="canvas" class="canvas"></canvas>
Attributes width and height stretch the canvas into a certain field, but do not resize it (so, var canvasElement = document.getElementById('canvas');
canvasElement.width = 400;
canvasElement.height = 400;
doesn’t work. How can I resize the canvas (make it something not equal to 160*320)?

Answer by Starx

You can do it, this way.

var canvasElement = document.getElementById('yourCanvasElement');
canvasElement.width = 500;
canvasElement.height = 400;
Read more
...

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