...

Hi! I’m Starx

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

How to provide table name to select from a search text box like: SELECT * FROM $query

User2425381’s Question:

I cant find the answer anywhere, maybe someone could help me. I need to display my MySQL table, but I need to give the name of the table through search box.
Something like this:

$raw_results = mysql_query("SELECT * FROM $query") or die(mysql_error());

Your code already does that, only thing remaining is to pass the value to the variable $query

$query = "your search query";

$raw_results = mysql_query("SELECT * FROM $query") or die(mysql_error());

However, what you are doing is very vulnerable, you should not pass the table name from the text box to the code directly.

$query = $_POST['searchbox'];

Doing such will leave your code very vulnerable as I could type in users and get all the details of the user.

Change your programming, whatever you are trying to do is wrong.

Read more

Using click event while button is disabled

Xegano’s Question:

I need to check on clicks while the button is disabled is this possible? Or is there any other way to this?

HTML:

<form id="form">
  <input type="submit" id="submit" value="Submit" />
</form>

JS:

$("#form").submit(function (e) {
    e.preventDefault();
    return false;
    $("#submit").on("click", function () {
        alert("Bla");
    });
});

JS Fiddle: http://jsfiddle.net/hjYeR/1/

return statements are the end point in the function, the codes will not proceed ahead of that.

What you can do is simply remove the click event handler from within the submit handler itself.

$("#form").submit(function (e) {

    return false; //e.preventDefault(); is not needed when used return false;

});

$("#submit").on("click", function () {
    alert("Bla");
});
Read more

How to determine whether it was the class or id selector clicked in joint event handler?

Sephiith’s Question:

In the below event handler I need to determine whether it was ID or Class that was clicked and assign a variable based on that.

What would be the easiest way of determining that in an IF statement?

jQuery CODE:

   $(document).on('click', '.inter [class], .inter [id]', function () {
   prevClass = className;
   IF CLASS >>>>>>>   className = this.className.substring(1);
   IF ID >>>>>>>>>>   className = this.id.substring(1);


    var back = '<div id="_'+ prevClass +'"></div>';

    link[prevClass] = original;
    original = link[className];
    link[className] += back;


       $('.inter').fadeTo(250, 0.25, function () {
           $('.inter').html(link[className]); 

           $('.inter').css({'background-image': 'url("' + className + '.png")'});
           $('.inter').fadeTo(250, 1.00);

       });
   });
 });

Something like this will work: (this.id || this.className).substr(1)

This works

IF this.className.substring(1) !== "" className = this.className.substring(1);
IF this.id.substring(1) !== ""   className = this.id.substring(1);
Read more
May 25, 2013

div how to make its dimensions exactly as those of the contents

Stark’s Question:

How do I form a div to have the same dimensions as those of the content housed by it , and not any larger ?

The div that I currently has a larger width than that of the three divs that i have placed inside it.How can i get it to fit the inner div’s size?

Here is the link to what i have now :: http://jsfiddle.net/jairajdesai/Fd5hQ/

HTML :

<div id="initial_options">
            <div class="option_button" id="option_1">
                <big>1</big> <span class="supplementary_text">text goes here</span>
            </div>
            <div class="option_button" id="option_2">
                <big>2</2></big> <span class="supplementary_text">text goes here</span>
            </div>
            <div class="option_button" id="option_3">
                <big>3</big> <span class="supplementary_text">text goes here</span>
            </div>
</div>

CSS :

#initial_options {
position:relative;
top:18%;
left:0;
z-index:10;
background-color:#eee;
}
.option_button{
width:20%;
border-radius:none;
}
#option_1{
background-color:#013adf;
}
#option_2{
background-color:#f7fe2e;
}
#option_3{
background-color:#ff0000;
}

Inline element like <span> wraps around the content and more. Either you can use this or you can set the display property as inline.

div {
   display: inline;
}

However setting to display as inline will not give you any option to add top/bottom margin and padding. If you want to add that too, you should use inline-block as the property.

div {
    display: inline-block;
}
Read more
May 23, 2013

Is this jquery or just javascript?

SJS’s Question:

I am really a backend java programmer but I am working on a project that has some frontend code. I have a question with the following code is the

.validate

Just plan javascript or is it part of jquery?

<script src="/common/js/jquery.maskedinput.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {

        // apply the masked input format to the phone number field
        $("#phonenumber").mask("999-999-9999");

        $("#memberrequest").validate({
            rules: {
                phonenumber: {
                    minlength: 12,
                    maxlength: 12
                },

                content: {
                    minlength: 3,
                    maxlength: 1000
                }

            }
        });


    });
</script>

Not being a javascript/frontend guy can someone put some light on this

I am disappointed at the quality of answers here. I will try to answer in another way:

<script type="text/javascript">
    $(document).ready(function () {    
  //^ This is the DOM Ready event of jQuery so it is event handler in jQuery

        // apply the masked input format to the phone number field
        $("#phonenumber").mask("999-999-9999");
      //^ $ is most commonly read as jQuery nowadays
      //  But, since you imported a file before with the name "jqery.maskedinput.js" it is also jQuery

        $("#memberrequest").validate({
                        // ^  Just like the masked plugin above, 
                        //    this is another plugin written in jQuery

            rules: {
                phonenumber: {
                    minlength: 12,
                    maxlength: 12
                },

                content: {
                    minlength: 3,
                    maxlength: 1000
                }

            }
        });


    });
</script>
Read more

How to pass value from page to another page without using SESSION OR GET

Bhavesh Vaghela’s Question:

index.php page : here I want to display successfully added record message , coming from add.php page

add.php page : here I have written insert code , if data successfully inserted it will redirect to index.php page then message will be display on index.php page

But I dont want to pass in$_SEESSION or $_GET ,

Without $_SEESSION or $_GET is it possible ?

You can use the following methods:

  1. Cookie
  2. Database
Read more

HTML Tag Contains Display Table and Display Inline-Block

Someyoungideas’s Question:

I am looking to truncate a tag in html with ellipsis and to do so it needs to be display: inline-block, block, etc. The problem is that I also have a class on it that contains the css of display: table. The tag is keeping both display styling somehow and will not allow the ellipsis to occur. Why is both display styles allowed instead of one overriding the other?

I understand I could remove the class with the display: table, but I am more curious why it can hold both display styles.

One element can have one display property at a time not two. You can override the style by providing inline style instead like

<div style="display: inline;">
...</div>

Doing so will override any other style property defined before.

Read more
May 22, 2013

Merging columns if a column has a count &gt; 1

Lotier’s Question:

I’m trying to create a column that is merged column if the count of column_1 is greater than 1, and just the value of one of the columns if 1, when matching to column_1. So far I can get the column to merge properly, but it only returns the first row back, not all of them.

Example Table

id, col_1,   col_2,   col_3
---------------------------
1, 'Name1', 'Value',  '1',
2, 'Name2', 'Value',  '2',
3, 'Name2', 'Value',  '3',
4, 'Name3', 'Value2', '1',
5, 'Name2', 'Value3', '1';

What I would like back

2, Name2, Value 2
3, Name2, Value 3
5, Name2, Value3

What I’ve attempted so far

SELECT id,
IF (count(col_2) > 1, concat(col_2, ' ', col_3), col_2) as merge
FROM mytable 
where col_1 = 'Name2'

which only returns ‘2, Value 2’ Thanks for the help. I’ve messed with it at http://sqlfiddle.com/#!2/9ce7e/7

count() is a aggregate function, thus it return single row as output.

You can user the following query to make sure col_2 has some value before concatenating

SELECT id,
IF (col_2 <> "" , concat(col_2, ' ', col_3), col_2) as merge
FROM mytable 
where col_1 = 'Name2'
Read more

Overriding variable value inside the $.get()

Starx’s Question:

I am facing a quite Strange problem, I dont seem to be able to override variable jSonData from inside the success function of $.get()

$.fn.name = function(data, options) {
        var jSonData = data;
        var settings = $.extend({
                ....        
        }, options);

        if(typeof data !== 'object') {
            if(settings.debug) console.log('Getting configuration settings from: ', data);
            $.get(data, function(d) {
                jSonData = d; //I attempt to override the value here
            }, 'json');
        }
        console.log(jSonData); // Gives the same value as it was before
};

Note: The success event of the $.get() is triggered

By the time you logged the value, the $.get() has not overridden jSonData yet since the AJAX request has not returned by that time. Do the console.log inside the function instead.

$.get(data, function(d) {
  jSonData = d; //I attempt to override the value here - You just did!
  console.log(jSonData);
}, 'json');

I was having that problem because AJAX calls are asynchronous and thus the call would not have been completed when console.log() was executed.

Solution I used to fix my issue was by using deferring methods.

$.fn.name = function(data, options) {
    var jSonData = data;
    var settings = $.extend({
            ....        
    }, options);
    var getData = function() {
        if(typeof data !== 'object') {
            return $.get(data, 'json');
        }
        else { return jSonData; }
    };
    getData().done(function(result) {
        jSonData = result;
        console.log(jSonData); // Gives the same value as it was before
    }).fail(function() {
        //
    });

};
Read more
May 21, 2013

jQuery complete replace DOM of element with another DOM – faster way?

Tomis’s Question:

I’m using jQuery’s AJAX for getting new content from server. Data is loaded in JSON:

$.ajax({
    url: url,
    data: {
        'ajax': '1',
    },
    dataType: 'json',
    success: somefunction
});

For server-side application limitation, I’m not able to setup more JSON variables inside so I have to load everything into content. That is why I have to load result into jQuery, than search and replace some elements on page, like this (used in somefunction):

var somefunction = function(data) {
    var con = $('<div></div>').html(data.content); // just $(data.content) is not working
    $('div#mainContent').html(con.find('div#ajax-content').html());
    ... // same process with three more divs
}

EDIT: Please, note that I have to do same process to replace three divs!

There is more about that, but as example, it’s enough I hope. My question: For some logic way, I expect that loading result into DOM ($(data.content)), parsing to html (con.find('dix#ajax-content').html()) and back to DOM ($('div#mainContent').html()) seems to me like loosing some resources and decreasing the perfomance so I would like to know if there is any faster way to do it and load DOM directly, like:

$('div#mainContent').dom(con.find('div#ajax-content').dom());

I tried to google it but maybe I don’t know what to type in. Also jQuery documentation does not helped me a lot.

Some facts:

  • jQuery 1.9.1
  • jQuery UI 1.10.3 available

Finally, I know that it would be much more better to do something with server-side app to provide more JSON variables, however, I need to write not-so-easy peace of code which is requiring longer time to develop which I don’t have right now. Doing it on client side would be temporary solution for now, however, I don’t want to decrease performace a lot.

Side-question:

is it correct to use find() function in this case or there is any better one?

EDIT 2 (not working parsing string)
I’m expecting this working but it’s not:

content = '<div id="ajax-title">Pečivo běžné, sladké, slané</div>
<div id="ajax-whereami"><a href="/category/4">Chléba a pečivo</a> » Pečivo běžné, sladké, slané</div>';
$(content);

Actually, $(data.content) should work just fine, but you have to keep in mind that the top level elements can only be reached via .filter() instead of .find(). If the elements you wish to target are at least one level deeper than the root you should use .find() though; in the examples below you can replace .filter() with .find() where appropriate.

var $con = $(data.content);
$('div#mainContent')
  .empty()
  .append($con.filter('div#ajax-content'))
  .append($con.filter('div#another-id'))
  .append($con.filter('div#and-another-id'));

You can also combine the selectors together:

  .append($con.filter('div#ajax-content, div#another-id, div#and-another-id'));

Lastly, since identifiers should only appear once inside a document, you can drop the div part:

  .append($con.filter('#ajax-content, #another-id, #and-another-id'));

Update

Okay, it seems that jQuery doesn’t evaluate data.content properly when there are newlines in the wrong places; this should work in all cases:

var wrapper = document.createElement('div');
wrapper.innerHTML = data.content;

var $con = $(wrapper);

No, There aren’t any other way that will speed up the performance.

In order to traverse along the content, the content has to be loaded somewhere. So what you are doing is perfectly valid.

Read more
...

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