Showing posts with label JQuery. Show all posts
Wednesday, January 25, 2017
Ajax jQuery File Upload with Codeigniter using BlueImp with image preview
Hello friends, are you looking for ajax based jquery file upload using codeiginter. Then here is tutorial for you. In this tutorial we will discuss about File Uploading using PHP Codeigniter and Jquery with ajax. Blueimp file upload gives you a best option for file uploading. I found this script very useful for my projects and I would like to share this information with you. Blueimp is a free open source code.Why Blueimp?
Blueimp is a file upload widget which can be used for multiple file uploads with validations and is highly secured. It also supports cross domain, chunked and resumable file uploads. It can be used for image, audio, video etc., It has a progress bar shown for each image and supports drag and drop. It works with any server side platform such as Google App Engine, PHP, Python, Ruby on Rails, Java etc., However in this tutorial we are going to discuss about PHP and Codeigniter.
Demo
Blueimp with codeigniter
As we already discussed that Blueimp supports PHP, so we can use with Codeigniter too. Blueimp wiki says that you can easily integrate this script with Codeigniter but when I tried to work with it I found it very hard to do. I made it simpler and will share it with you.
How to integrate Blueimp with Codeigniter?
Open constants.php file in config folder and add the below given code in it. You can add it at the bottom of the code in constants.php
// Define Ajax Request
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
Now create a new php file using any text editor and add the following code to it.
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url', 'file'));
}}
public function do_upload() {
$upload_path_url = base_url() . 'files/';
//you should create a folder uploads in the root directory of your codeigniter
$config['upload_path'] = FCPATH . 'files/';
//to allow only image files of below type
$config['allowed_types'] = 'jpg|jpeg|png|gif';
//max size to upload else return error message. change it to more if you want to allow large files
$config['max_size'] = '50000';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
//Load the list of existing files in the upload directory
$existingFiles = get_dir_file_info($config['upload_path']);
$foundFiles = array();
$f=0;
foreach ($existingFiles as $fileName => $info) {
if($fileName!='thumbnails'){//Skip over thumbnails directory
//set the data for the json array
$foundFiles[$f]['name'] = $fileName;
$foundFiles[$f]['size'] = $info['size'];
$foundFiles[$f]['url'] = $upload_path_url . $fileName;
$foundFiles[$f]['thumbnailUrl'] = $upload_path_url . 'thumbnails/' . $fileName;
$foundFiles[$f]['deleteUrl'] = base_url() . 'upload/deleteImage/' . $fileName;
$foundFiles[$f]['deleteType'] = 'DELETE';
$foundFiles[$f]['error'] = null;
$f++;
}
}
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('files' => $foundFiles)));
} else {
$data = $this->upload->data();
// to re-size for thumbnail images un-comment and set path here and in json array
$config = array();
$config['image_library'] = 'gd2';
$config['source_image'] = $data['full_path'];
$config['create_thumb'] = TRUE;
$config['new_image'] = $data['file_path'] . 'thumbnails/';
$config['maintain_ratio'] = TRUE;
$config['thumb_marker'] = '';
$config['width'] = 300;
$config['height'] = 100;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
//set the data for the json array
$info = new StdClass;
$info->name = $data['file_name'];
$info->size = $data['file_size'] * 1024;
$info->type = $data['file_type'];
$info->url = $upload_path_url . $data['file_name'];
// I set this to original file since I did not create thumbnails. change to thumbnail directory if you do = $upload_path_url .'/thumbnails' .$data['file_name']
$info->thumbnailUrl = $upload_path_url . 'thumbnails/' . $data['file_name'];
$info->deleteUrl = base_url() . 'upload/deleteImage/' . $data['file_name'];
$info->deleteType = 'DELETE';
$info->error = null;
$files[] = $info;
//this is why we put this in the constants to pass only json data
if (IS_AJAX) {
echo json_encode(array("files" => $files));
//this has to be the only data returned or you will get an error.
//if you don't give this a json array it will give you a Empty file upload result error
//it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
// so that this will still work if javascript is not enabled
} else {
$file_data['upload_data'] = $this->upload->data();
$this->load->view('upload/upload_success', $file_data);
}
}
}
public function deleteImage($file) {//gets the job done but you might want to add error checking and security
$success = unlink(FCPATH . 'files/' . $file);
$success = unlink(FCPATH . 'files/thumbnails/' . $file);
//info to see if it is doing what it is supposed to
$info = new StdClass;
$info->sucess = $success;
$info->path = base_url() . 'files/' . $file;
$info->file = is_file(FCPATH . 'files/' . $file);
if (IS_AJAX) {
//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
}
}
Thursday, April 23, 2015
How to show password strength using JQuery
Hello friends, I want to discuss about JQuery code to show password strengths when a user types in a password into password field.
Password security is necessary to keep our accounts safe from hackers. Generally we use common passwords to remember them easily. However we should use secured passwords so that it couldn't be guessed by anyone. Recently I had a client who wants to show the password strength when a user types his password. So I tried the Jquery code which is explained in this tutorial to check the password strengths. This code will use JQuery regular expressions to check the strength of a password typed by the user.
I have also provided the CSS in this tutorial to add style to the message which shows the strengths of password entered.
I have also provided the CSS in this tutorial to add style to the message which shows the strengths of password entered.
Please check the below JQuery code:
$('#pwd').keyup(function(e) { var strongPass = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g"); var midPass = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); var morePass = new RegExp("(?=.{6,}).*", "g"); if (false == morePass.test($(this).val())) { $('#msg').html('Please enter more characters'); } else if (strongPass.test($(this).val())) { $('#msg').className = 'ok'; $('#msg').html('Great! your password is strong.'); } else if (midPass.test($(this).val())) { $('#msg').className = 'alert'; $('#msg').html('Better, your password strength is medium.'); } else { $('#msg').className = 'error'; $('#msg').html('Sorry, your password is too weak.'); } return true; });
Here I have included the CSS to add styles to the div when the password strength status changes while typing in the password filed.
CSS:
.error{ background:#BE4C39; color:#fff; }.alert{ background:#fd7c2a; color:#fff; }.ok{background:#3cc16e; color:#fff; }
Below is the HTML code for the input field and the div that holds the message which shows the password strength.
<input type="password" name="pwd" id="pwd" /><span id="msg"></span>
I used pwd as name and id in the above input fields and the respective id has been used in the JQuery code and "msg" is the id used for the span which holds the message for the password strength.
I hope this code will help you in your projects. Please don't hesitate to ask your queries in the comment section below. Thank you. Happy coding :) Labels: blogger tips, JQuery, Tips and Tricks, Web Development
Friday, March 28, 2014
How to display preview of image before upload using JQuery
When our application needs to have an option for image uploads we use input tag in a form. The upload process is handled inside a PHP file which we can discuss in future. We have already discussed about hiding an image which is broken. File uploading is very easy but sometimes we even want to preview the image before it is uploaded. For this purpose we can use JQuery code which will show the image before it is uploaded. Today I am going to discuss about the code which helps you preview the image before upload.
Here is the code for showing image before uploading.
JQuery:
$(document).ready(function(){
$("#image").change(function(){
var file = document.getElementById("image").files[0];
var readImg = new FileReader();
readImg.readAsDataURL(file);
readImg.onload = function(e) {
$('.imagepreview').attr('src',e.target.result).fadeIn();
}
})
})
This code uses the advantage of HTML5 attribute. FileReader reads the file, here the file is an image. It fetches the URL of the current image to show up when it is selected through file browser field.
The above code jquery code fetches the image and shows the preview. Below is the HTML code which refers the above jquery code.
HTML:
<input name="image" type="file" class="image" id="image"><br/>
<img class="imagepreview" src="">
Since the above HTML code has no image in the source it displays a broken image, so in order to eliminate the broken image we can use the code for this link to avoid broken images or we can use the following CSS code instead of the code specified in the link. I recommend you to use the CSS code below.
CSS:
.imagepreview{width:500px;
display:none;}
Here are some helpful posts for bloggers and web designers.
Add Google Plus Follower Gadget For Blogger
How to add floating widget to blogger blog
Add awesome sticky footer menu to Blogger with simple HTML
How to trace details of an unknown person with mobile number
Why every freelance worker wants to be a blogger?
Which is the best way to optimize mobile site?
How facebook fan page can make you money?
Separate Contact page in Blogger
How to add Contact Form Widget to blogger Official Plugin
SEO Title Tag Best Practices
How to disable graph search on facebook/trick to remove facebook graph
How to find fake profile pictures on facebook?
Add Facebook Like Button below posts titles (Speed Loading)
How to delete Facebook account permanently?
How to use facebook on slow internet connections
How to delete Google Search History/Cache?
8 Tips to reduce load time of Blog/Website
Xenon Blogger Template Download
3 ways to make money online
5 Idiotic ways you can promote your blog
I have given you three blocks of code for image preview. Look below for the complete code after combining all the above blocks of code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Preview image before upload by TricksTown.com</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#image").change(function(){
var file = document.getElementById("image").files[0];
var readImg = new FileReader();
readImg.readAsDataURL(file);
readImg.onload = function(e) {
$('.imagepreview').attr('src',e.target.result).fadeIn();
}
})
})
</script>
<style>
.imagepreview{width:500px;
display:none;}
</style>
</head>
<body>
<input name="image" type="file" class="image" id="image"><br/>
<img class="imagepreview" src="">
</body>
</html>
Copy the above code and paste it in your notepad. Save it with .html extension and check it.
Enjoy... :) Happy coding.
Thank you. If you have any doubts, please comment below. Spam comments will be removed. Labels: HTML5, JQuery, Web Design, Web Development
Thursday, March 27, 2014
How to hide or fix a broken image using jquery
We commonly face a problem with broken images on websites. Our browsers will show a broken image when the link to an image doesn't work or when there is no image. Mostly this problem is faced when you make dynamic websites in which you work on putting a default image for posts. When a user/visitor come across your site having a broken image then he/she may lose interest on your website. So we need to put a small JQuery code so that the broken image disappears. In today's tutorial I want to show you the code for hiding the broken images.You may like these
Get free likes for your facebook account.
Login script in PHP
Delete file using PHP
Delete Facebook account permanently
Disable graph search on Facebook
Pagination with PHP
Awesome stylish sliding professional contact form for your website
Use facebook on slow internet
How to delete google cache from search
How to scare your friends with simple code
Just look at the code below.
<script>
$(document).ready(function(){
$("img").error(function(){
$(this).hide();
});
})
</script>
Copy the above code and paste it above the closing </head> tag. That's it. You are done. is
Explanation:
$(document).ready(function()) says the function to execute when the page loads.$("img") finds the img tag.
error(function()) checks if the img tag has any error and executes the function to hide the broken image using $(this).hide();
Here this refers to the current one i.e., the img tag.
Thanks for reading this article. If you have any doubts please don't hesitate to comment below. Labels: blogger tips, JQuery, Web Design, Web Development
Subscribe to:
Posts (Atom)


