May 31, 2013

javascript or jquery : mouse events

VJS’s Question:

Need your help in understanding this code..Is this Javascript ( expression language ) or JQuery. I tried to understand but didn’t get it.

var interval = 0, changed = false;
...............
...............

var start = function () {
    $(document).on('mousedown mousemove scroll touchstart touchmove keydown', change);
    setInterval(check, 1000);
};

 var change = function () {
    changed = true;
};

var check = function () {
   console.log("changed .....");
};

start();

Basically I want to do something ( business logic ) if user had performed some events on browser.Got this code on net and felt like something this is doing the same what i want.

This following part is jQuery specific, all other are pure JavaScript.

$(document).on('mousedown mousemove scroll touchstart touchmove keydown', change);

This is a event handler of jQuery which is calling a native javascript function change().

Notes:

  • To run the jQuery part you need to import jQuery Library from their site.

  • You can identify the jQuery selectors by user of $ infront. ($ does not always means jQuery)

Calling ajax once

User2310422’s Question:

I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,

My Goal :

  1. When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
  2. When it is clicked for the second time, I just want to hide the content, and
  3. When it is clicked for the third time, I just want to show the container without calling the ajax again.

jQuery:

$(function() {
    $('#click_me').click(function(){
        var container = $('#container').css('display');
        var id = $('#id').html();
            if(container == 'none'){
                $.ajax({
                type: 'POST',
                data: {id: id},
                url: "ajax/get_items.php",
                }).done(function(data) {
                $('#container').html(data);
                }).success(function(){
                $('#container').show('fast');
                });
                }else if(container == 'block'){
        $('#container').hide('fast');
        }
        });
});

Html :

<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>

You can do this by defining a simple variable counting the clicks.

$(function() {
    var clickCount = 1; //Start with first click

    $('#click_me').click(function(){
        switch(clickCount) {
             case 1: //Code for the first click

                 // I am just pasting your code, if may have to change this
                 var container = $('#container').css('display');
                 var id = $('#id').html();
                     if(container == 'none'){
                         $.ajax({
                         type: 'POST',
                         data: {id: id},
                         url: "ajax/get_items.php",
                         }).done(function(data) {
                         $('#container').html(data);
                         }).success(function(){
                         $('#container').show('fast');
                         });
                         }else if(container == 'block'){
                 $('#container').hide('fast');
                 }
              break;
              case 2: 
                 //code for second click
                 break; 
              case 3:
                 //Code for the third click
                 break;      
        });
        clickCount++; //Add to the click.
});

Can I select a update from database field

Ramin Rahimi’s Question:

What I am trying to do is to select a update from a portion of my site where users upload pictures and I know I have to create a field for that in my database but first I was wondering to know if I can use this syntax like:

SELECT UPDATE 
FROM photos 
WHERE album LIKE BINARY 'loggedin_avatar'  
ORDER BY datemade ASC

so is this a right syntax? also where can I learn about filtering the files being uploaded to my site. Generally filtering the files being uploaded.

No, that is not the correct syntax. SELECT and UPDATE are two different query statements.

If you trying to select a field called update from your database table, then you have to quote them

SELECT `update` FROM photos WHERE album LIKE BINARY 'loggedin_avatar' ORDER BY datemade ASC"; 

If you are trying to select a updated row after updating them, you have to send mulitple statements.

  • First update the rows
  • Select the updated row which the help of a primary key field.
May 30, 2013

PDO – get two select values into an array

NojoRu’s Question:

I have this PDO:

$id = 1;
$title = 'resourceName';
$url = 'resourceURL';
$result = array($title => $url);

include('../dbconnect.php');

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare("SELECT resourceName, resourceURL FROM Resources WHERE categoryID = :id");
$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result));
$row = $stmt->fetchAll();
print_r($row);

I am just getting this error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

How can make the PDO result be an array where resourceName is the key and resourceURL is the value?

You are binding unneeded parameters to the query.

$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result)); //On this line. These parameters are 
                                         not needed

Let me explain

$stmt->bindParam(':id', $id);

Binds the value of $id to the SQL Parameter :id and Again

$stmt->execute(array_values($result));

You are binding another parameters without any indexes.

Thus your query wants 1 parameter and you are sending two paramters.

Solution: Use one of them

Either

$stmt->bindParam(':id', $id);

Or , directly like this

$stmt->execute(array(":id" => $id));

After, that get columns from the rows and convert them into a new array in your required format

$row = $stmt->fetchAll();
//Now assuming only one was returned from the database this might work
$new = array($row[0] -> resourceName => $row[0] -> resourceURL);

Javascript not checking whether a checkbox was selected or not

User2437473’s Question:

I’m trying to build a quiz with multiple choice questions, one of which has multiple correct answers. So I’m trying to check which checkboxes in my questions have been selected by a student in order to give the right feedback. my code is:

for(var i = 0; i< input1.length; i++)
    {
        if(input1[0].checked && input1[1].checked)
        {
        submit_answer.onclick = showFeedback1; 
        }
        else
        {
        submit_answer.onclick = false1; 
        }
    }

It never takes the first if, even if I select those two only. No matter what I put in the if statement, it only takes the else.

and this is just a part of my .js

var quiz = document.getElementById('quiz');

var questions = quiz.getElementsByTagName('p');

input1 = questions[0].getElementsByTagName('input');

var submit_answer = document.getElementById('submit_answers'); // this is the submit button

I cannot make proper assumption of what you are trying to do.

FIRST PROBLEM

Your for loop is incrementing on 1, so on the each next iteration it is comparing using same previously used value.

SECOND PROBLEM

Your structure is horrible, your script fetches up all the input elements inside every p. You should properly organize your element in groups and then match whether or not they are checked.

Warning: mysql_result() expects parameter 2 to be long, string given in

Vicente Carlos’s Question:

newbie here…

I need some help or a solution to the following error please.

Warning: mysql_result() expects parameter 2 to be long, string given in /home/username/public_html/shop/admin/includes/th.inc.php on line 1036

CODE:

<?php
    $sql = "SELECT description from affiliSt_themes WHERE title = 'default' LIMIT 1";
    $thisDesc = mysql_result(mysql_query($sql, $databaseConnect), '');
?>

Greatly appreciated.

Here is your answer:

$thisDesc = mysql_result(mysql_query($sql, $databaseConnect), '');
   //                                                         ^ Remove this, OR USE LONG VALUE
May 29, 2013

Using margin on wrap list won't work. margin: top is always 0

Vibskov’s Question:

http://jsfiddle.net/MqPDH/10/

Why does the 1st wrap .wp-list margin: 10px and .a .b use margin: 10px not work?

.wp{
    background-color: blue;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    left: 0;
    right: 0;
    width: 450px;
}
.wp_list{
    background-color: red;
    margin: 10px;
    height: 130px;
    position:relative;
}
.a, .b, .c{
    background-color: gray;
}
.a{
    width: 220px;
    height: 30px;
    margin: 10px;
}
.b{
    width: 220px;
    height: 100px;
    margin: 10px;
}
.c{
    width: 130px;
    height: 130px;
    top:0;
    right:0;
    position:absolute;
}

HTML:

<div class="wp">
    <div class="wp_list">
        <div class="a">a</div>
        <div class="b">b</div>
        <div class="c">c</div>
    </div>
    <div class="wp_list">
        <div class="a">a</div>
        <div class="b">b</div>
        <div class="c">c</div>
    </div>
    // generate from php
</div>

Margins collapse on block elements, this means that when you have an element with a 10px margin set on the bottom, followed by an element with 5px margin set on the top. The margin between the two will not be 15px, but will collapse down to the largest of the two: 10px, or in this case when they’re both 10px, it will collapse to be 10px.

You should add display: inline-block; to .a, .b, .c, that will fix it:

.a, .b, .c{
    background-color: gray;
    display: inline-block;  
}

jsFiddle

This is mainly because because it is behaving as inline element. Add display: inline-block;

.wp_ist{
    display: inline-block;
    background-color: red;
    margin: 10px;
    height: 130px;
    position:relative;
}

mod_rewrite, Adding a Condition

A A’s Question:

I have this .htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ zone.php [L]

Right now it works pretty well. How can I make this RewriteRule not work in a certain directory?

I do not want the rule to work for anything in domain.com/manage/

Change your code with this:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule (?!^manage/)^.*$ /zone.php [L,NC]

Add a condition by using the RewriteCond keyword to apply the rule if the directory is not manage

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/manage(/|$)
RewriteRule ^(.*)$ zone.php [L]

How to get value of radio button with dynamically generated name

Daniel Young’s Question:

I have a whole bunch of radio buttons with dynamically generated names like below:

        <input type="radio" id="Red<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="Red" <?php if ($category == "Red") { ?>checked="true"<?php } ?>>
          <label for="Red<?php echo $wineID; ?>">Red</label>

        <input type="radio" id="White<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="White" <?php if ($category == "White") { ?>checked="true"<?php } ?>>
          <label for="White<?php echo $wineID; ?>">White</label>

        <input type="radio" id="Sparkling<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="Sparkling" <?php if ($category == "Sparkling") { ?>checked="true"<?php } ?>>
          <label for="Sparkling<?php echo $wineID; ?>">Sparkling</label>

I need to get the selected value and add it into my dataString for an ajax call to update my database. How can this be done using jQuery?

You can use attribute selector to get the element

$('input[name="category<?php echo $wineID; ?>:selected"')

However this uses a PHP inline script, so it will only work if rendered at the page load.

Or easiest would be:

console.log($(":radio:selected").val());
...

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