Tuesday, October 28, 2014

How To Limit Characters in Div With jQuery?

It is really easy to limit the number of characters in a div, particular class, ID etc by a particular value.
$(function(){

  $(".target-div").each(function(i){

    var len = $(this).text().length;

    if(len > 100){

      $(this).text($(this).text().substr(0,100)+'...');

    }
  });
});
If desired, remove the dots from the end ('...'). I would recommend keeping it to let your users know that the text was shortened.

Monday, October 27, 2014

How To Upgrade Mysql/phpMyAdmin in MAMP?


Follow these simple steps to upgrade phpMyAdmin or Mysql in MAMP. The latest version was phpMyAdmin 4.2.10.1 (at the time of writing).
1. Download the latest version from http://www.phpmyadmin.net/home_page/index.php
2. Unpack the archive you just downloaded, the resulting folder should be called somewhat like "phpMyAdmin-x.y-all-languages"
3. Rename "/Applications/MAMP/bin/phpMyAdmin" to "/Applications/MAMP/bin/phpMyAdmin-OLD"
4. Copy "phpMyAdmin-x.y-all-languages" to "/Applications/MAMP/bin/"
5. Rename "/Applications/MAMP/bin/phpMyAdmin-x.y-all-languages" to "/Applications/MAMP/bin/phpMyAdmin"
6. Restart the MAMP and upgrading task is completed. You have successfully upgraded to latest phpMyAdmin or Mysql 4.2.10.1 version.

What is phpMyAdmin?
phpMyAdmin is a free software tool written in PHP, intended to handle the administration of MySQL over the Web. phpMyAdmin supports a wide range of operations on MySQL, MariaDB and Drizzle. Frequently used operations (managing databases, tables, columns, relations, indexes, users, permissions, etc) can be performed via the user interface, while you still have the ability to directly execute any SQL statement.

Wednesday, October 15, 2014

When And How To Use jQuery mouseenter And mouseleave Events?

If elements you are binding to are loaded with javascript after the document loads, it is better to use mouseenter and mouseleave events of jQuery.
$(document).on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
}, ".selector"); //pass the element as an argument to .on
This code will work for an element populated with JavaScript after a .load() event has happened. Just change your argument to the appropriate selector.

This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.

I have tried to use jQuery .on and hover for an above situation, but it didn't work.

Ref: http://stackoverflow.com/a/9827114

Friday, October 10, 2014

How To Capture Array Values from Dynamic input Fields Using PHP?

In my previous post, you were able to add multiple dynamic fields using jQuery. In this tutorial, we will collect values from those dynamically generated input fields, which can be displayed on user browser or store in MySql database.

Let's assume you have a HTML form with multiple input fields like example shown below. This fields are generated by jQuery code in my previous post.
<form method="post" action="collect_vals.php">
 <div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
 </div>
</form>
Notice the name attribute mytext[] of each input fields? they all have same name. The brackets indicate that the value of such input field will be posted as an array, so another input field means another value to existing array.

Capture Array Values using PHP
Collecting values from above input fields is pretty simple, take a look at example below. Once the value is captured from input fields, you can output it on the browser.

We can directly access array values using array's indexed number, but this will cause error if indexed value doesn't exist in array.
echo $_POST["mytext"][0];
echo $_POST["mytext"][1];
Another way is using PHP implode, it converts POST array into string, separated by commas. Just make sure POST variable is not empty:
if($_POST){
    $subject = implode(",", $_POST["mytext"]);
    echo $text;
}
You can also loop through each POST array like so, result is same as above.
<?php
if(isset($_POST["mytext"])){
    
    $capture_field_vals ="";
    foreach($_POST["mytext"] as $key => $text_field){
        $capture_field_vals .= $text_field .", ";
    }
    
    echo $capture_field_vals;
}
?>

Save values into Database
You can save above captured strings on your database using MySql/MySqli.
<?php

//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO table ( captured_fields ) VALUES( $capture_field_vals )");

if($insert_row){
    print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}
?>


Source: Source: Capture Array Values from Dynamic input Fields using PHP

Thursday, October 9, 2014

How To Add or Duplicate Input Fields Dynamically Using jQuery?

If you are looking to add and remove duplicate input fields, here's another jQuery example below to do the task for you. This jQuery snippet adds duplicate input fields dynamically and stops when it reaches maximum allowed fields.


If you read comment lines carefully, the process is pretty straight forward. We start with 1 input field and let user add more fields until the count reaches maximum. Same process goes to delete button, when clicked, it removes current text field by removing the parent element, which is div element.
$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

HTML Code
Here's HTML code you need to place within BODY tag of your page, perhaps within a FORM tag.
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>
We start with single Input field and a “Add more Field” button to allow user to add more fields. The text input field is wrapped in div element, as explained above, on delete button click, it finds parent element, which is a div and removes it.

How to capture array values using PHP from these input fields and save it in mysql in my next post.

Source: Add/Remove Input Fields Dynamically with jQuery

Tuesday, October 7, 2014

How To Load JSON Data With jQuery, PHP and MySQL ?

This post shows how to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP script that gets the data from a MySQL database.

HTML Code
The initial HTML code looks like this:
<form>
    Fruit:
   <select name="name" id="fruitName">
      <option>Apple</option>
        <option>Banana</option>
        <option>Orange</option>
        <option>Pear</option>
    </select>
    Variety:
    <select name="variety" id="fruitVariety">
    </select>
</form>
The set of fruit names was already populated on the server-side and the default set of varieties could be too; I have chosen to populate them with Javascript in this example.

jQuery Code
The jQuery code needs to initially populate the variety drop down based on the value of the fruit drop down. It then needs to update the variety if the fruit drop down changes.

Assuming the PHP script to fetch the fruit is at /fruit-varieties.php do this:
function populateFruitVariety() {
   
    $.getJSON('/fruit-varities.php', {fruitName:$('#fruitName').val()}, function(data) {

        var select = $('#fruitVariety');
        var options = select.prop('options');
        $('option', select).remove();

        $.each(data, function(index, array) {
            options[options.length] = new Option(array['variety']);
        });

    });

}

$(document).ready(function() {
 
 populateFruitVariety();
 $('#fruitName').change(function() {
  populateFruitVariety();
 });
 
});
The "$.getJSON('/fruit-varities.php', {fruitName:$('#fruitName').val()}" line is what retrieves the data and it passes the currently selected fruit name value as part of the get string to the PHP script.

PHP Code
The PHP script connects to the database, retrieves the data for the selected fruit name and then returns it as a JSON encoded string.
$dsn = "mysql:host=localhost;dbname=[DATABASE NAME HERE]";
$username = "[USERNAME HERE]";
$password = "[PASSWORD HERE]";

$pdo = new PDO($dsn, $username, $password);

$rows = array();
if(isset($_GET['fruitName'])) {
    $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
    $stmt->execute(array($_GET['fruitName']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);

Downloadable example
A downloadable example can be found here. This contains a PHP file which connects to the database and returns data when the fruitName parameter is specified.
All you need to do is add in your database name, login name and password to the PHP file and create the fruit table. The SQL for doing this is included in a comment at the end of the PHP file.
The HTML file should then work as-is, as long as you run the whole thing through a web server (e.g. don't just open the HTML file in your web browser and expect it to work).

Source: Load JSON data with jQuery, PHP and MySQL