Category Archives: jQuery

Legends in Morris Chart

With help from this article https://github.com/morrisjs/morris.js/issues/346

This is about adding Legends to Morris charts. Though Morris chart shows legend on hovering on the graphs, but I wanted to show a legend permanently on one corner of the chart area.

Below are the codes. It is mostly plug and play code

The div in which the chart will be displayed

<div class="box-body chart-responsive">
    <div id="visitor_legend" class="bar-chart-legend"></div> <!-- the legend area -->
    <div class="chart" id="bar-chart" style="height: 300px;"></div> <!-- the chart area -->
</div>

The CSS

<style>
.bar-chart-legend {
	display: inline-block;
	right: 25px;
	position: absolute;
	top: 8px;
	font-size: 10px;
}

.bar-chart-legend .legend-item {
	display: block;
}

.bar-chart-legend .legend-color {
	width: 12px;
	height: 12px;
	margin: 3px 5px;
	display: inline-block;
}
</style>

The JS code

// Legend for Bar chart
bar.options.labels.forEach(function(label, i) {
	var legendItem = $('<span class="legend-item"></span>').text( label).prepend('<span class="legend-color">&nbsp;</span>');
	legendItem.find('span').css('backgroundColor', bar.options.barColors[i]);
	$('#visitor_legend').append(legendItem) // ID pf the legend div declared above
});

Morris charts documentation https://morrisjs.github.io/morris.js/lines.html

Upload Files through AJAX (using Jquery and PHP)

This post demonstrates how to upload files to the server through AJAX. For the javascript  part JQuery has been used.

Besides the file upload thing there are few other useful codes here:

  • A generalised mail function. The function is capable of sending mails with attachments also.
  • Ajax call using JQuery.
  • Some server side validation codes.

Things might look a little jumbled up here, suggested to copy and paste the code to some IDE or editor first.

Form HTML
<span id="statusMessage"></span>

<form action="" method="post" name="" id="form1" enctype="multipart/form-data" onsubmit="return sendCareerData()">
    <input type="text" id="formName" name="formName" placeholder="Name" />
    <input type="text" id="formEmail" name="formEmail" placeholder="Email" />
    <input type="text" id="formPhone" name="formPhone" placeholder="Phone No." />
    <input type="file" id="formFile" name="formFile" placeholder="Upload File" />
    <input type="submit" id="button4" name="formSubmit" value="Submit" />
</form>
The Javascript part
<script type="text/javascript">
function sendCareerData()
{
    var data = new FormData(document.getElementById("form1"));
   
    // make the AJAX request
    jQuery.ajax({
        type: "POST",
        url: 'form-backend.php',
        data: data,
        mimeType:"multipart/form-data",
        contentType: false,
        cache: false,
        processData:false,
        dataType: 'json',
        success: function (data) {
            if (data.success == 0) //error on server side
            {
              /* error messages from server side validation */  
                var errors = '<ul>';
                if (data.name_msg != '')
                    errors += '<li>' + data.name_msg + '</li>';
                if (data.email_msg != '')
                    errors += '<li>' + data.email_msg + '</li>';
                if (data.phone_msg != '')
                    errors += '<li>' + data.phone_msg + '</li>';

                jQuery("#statusMessage").html(errors);
                jQuery("#statusMessage").css("display","block");
            }
            else if (data.success == 1) 
            {
                jQuery("#statusMessage").html("Thank you! We will get in touch.");
                jQuery("#statusMessage").css("display","block");
            }

        },
        error: function (error) 
        {
            jQuery("#statusMessage").html(error);
            jQuery("#statusMessage").css("display","block");
        }
    });
    
    return false;
}
</script>
The backend part using PHP
/******* form-backend.php *********/
<?php
ob_start(); //to suppress any newlines being sent before the header call

/********* a general mail sending function with or without attachment ***********/
function _mail($to, $from='', $subject = " ", $body = " ", $attachment = "" , $fileatt_type = "", $fileatt_name = "")
{
    $headers = "MIME-Version: 1.0" . "\r\n";
    if(strlen($from))
        $headers .= 'From: ' . $from . "\r\n";
    $headers .= 'Bcc: [email protected]' . "\r\n";
    
    if(strlen($attachment)) //if attachment is there
    {
        $fp = fopen($attachment, "rb");
        if(! $fp)
        {
            echo "Cannot attach file";
            return false;
        }
        $buffer = fread($fp, filesize($attachment));
        $attach_this=chunk_split(base64_encode($buffer));
        fclose($fp);
        $semi_rand = md5(time());
         $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
            /*'From: ' . $from . "\r\n" .
            'Reply-To: ' . $from . "\r\n" .*/
        $headers .= 'Content-Type: multipart/mixed; ' . " boundary="PHP-mixed-{$mime_boundary}"". "\r\n" . /* THIS BOUNDARY LINE AFTER CONTENT TYPE IS IMPORTANT */
        //$headers .= 'X-Mailer: PHP/' . phpversion() ; -- causing problems        
        $msg =     "--PHP-mixed-{$mime_boundary}\r\n" .
                "Content-Type: text/html; charset="iso-8859-1"\r\n" .
                "Content-Transfer-Encoding: 7bit\r\n\r\n". $body . "\r\n";
        $msg =     "--PHP-mixed-{$mime_boundary}\r\n";
        $msg .=  "--PHP-mixed-{$mime_boundary}\r\n" .
                "Content-Type: {$fileatt_type}; " . " name="{$fileatt_name}"\r\n" .
                "Content-Disposition: attachment; " . " filename="{$fileatt_name}"\r\n" .
                "Content-Transfer-Encoding: base64\r\n\r\n" .
                $attach_this . "\r\n" . /* DON'T PUT TWO NEWLINES AFTER THE ATTACHMENT */
                "--PHP-mixed-{$mime_boundary}--\r\n"; 
        $body = $msg;
    }
    else //no attachment - send simple html mail
    {
        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
        $headers .= 'X-Mailer: PHP/' . phpversion();
    }
    $mail_sent = mail($to, $subject, $body, $headers);
    $status = $mail_sent ? "1" : "0"; //1 - no error / success . 0 - error / failed
    return $status;
}

/**** a function for validating the user inputs **********/
function validate($name,$email,$phone)
{
  $return_array = array();
  $return_array['success'] = '1';
  $return_array['name_msg'] = '';
  $return_array['email_msg'] = '';
  $return_array['phone_msg'] = '';

  if($email == '')
  {
    $return_array['success'] = '0';
    $return_array['email_msg'] = 'email is required';
  }
  else
  {
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    if(!preg_match($email_exp,$email)) 
    {
      $return_array['success'] = '0';
      $return_array['email_msg'] = 'enter valid email.';  
    }
  }

  if($name == '')
  {
    $return_array['success'] = '0';
    $return_array['name_msg'] = 'Name is required';
  }
  else
  {
    $string_exp = "/^[A-Za-z .'-]+$/";
    if (!preg_match($string_exp, $name)) 
    {
      $return_array['success'] = '0';
      $return_array['name_msg'] = 'enter valid Name.';
    }
  }
  
  if($phone == '')
  {
    $return_array['success'] = '0';
    $return_array['phone_msg'] = 'Phone is required';
  }
  else
  {
     $string_exp = "/^[0-9 -]+$/";
     if (!preg_match($string_exp, $phone)) 
     {
        $return_array['success'] = '0';
        $return_array['name_msg'] = 'enter valid Phone.';
     }
  }

  return $return_array;
}

/****** assigning the values to some variables for easy handling ********/
$name = $_POST['formName'];
$email = $_POST['formEmail'];
$phone = $_POST['formPhone'];
$subject = $_POST['formSubject'];
$file = $_FILES['formFile']['tmp_name'];

$type = $_FILES['formFile']['type'];

$return_array = validate($name,$email,$phone); // validate the user input and get the result in $return_array

if($return_array['success'] == '1') //if input is okay then send the mail (with attachment)
{
  $body = "<strong>Email = </strong>".$email."<br>";
  $body .= "<strong>Name = </strong>".$name."<br>";
  $body .= "<strong>Phone = </strong>".$phone."<br>";
  
    
   if(strlen($_FILES['formFile']['tmp_name'])) //if attachment is there
   {
        _mail("[email protected]",$email,$subject,$body,$file,$type,$_FILES['formFile']['name']);
   }
   else
   {
        _mail("[email protected]",$email,$subject,$body);
   } 
  
}

ob_end_clean();//discard any output thrown above
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>