My Life and the world

World changes day by day!

Sunday, May 24, 2015

Ajax jquery delete data without refresh with animation effect

9 comments
With the help of jquery effects we can easily delete data without going to another page. In this jquery tutorial we are going to how to delete data without refresh i.e. delete the data from database as well as from webpage without page refresh. In this tutorial we are going to take advantage of Ajax to do this task. We also going to add some animation effect to it.
Like we have in facebook or twitter, where comments or tweets are deleted without refresh we are going to do the same. It's similar to like deleting comment without taking user to other page. Deleting the data in same page.
ajax jquery delete data without refresh with animation effect


First we are going to create a database. Add a table to the database as given below-

[highlight] CREATE TABLE IF NOT EXISTS `ajax_jquery_add_delete_record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; [/highlight]
Next to delete data without refresh with animation effect we have to create a simple form and then add javascript to them. A ajax call file also be created to make the changes occur without any refresh.
First create the form in html as like this -
[highlight]
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5" placeholder="Write what you are upto"></textarea>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
<button id="FormSubmit">Update Your Status</button>
</div>
[/highlight]

With this form we are going to get the text and update the status in the database. To make the ajax call we have to write jquery function. The jquery function to delete data without refresh is given as -


[highlight]

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

//##### send add record Ajax request to response.php #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val()==='')
{
alert("Please enter some text!");
return false;
}

$("#FormSubmit").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image

var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image

},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});

//##### Send delete Ajax request to response.php #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure

$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button

jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});

});
</script>

[/highlight]

Download Script View Live 

Sunday, May 17, 2015

The ready event in jQuery

No comments
As mentioned in examples of events in jquery ready event in jquery contains all other functions. The ready event occurs when the DOM (document object model) has been loaded, and the page has been fully loaded (including images). It's good practice to wait for the document to be fully loaded and ready, before working with it. Thus ready event in jQuery must enclose all other events, functions and triggers.
The inclusion of other events inside the ready event in jQuery,  allows  to have JavaScript code before the body document, in the head section, either directly or through a link to an external JavaScript file. This is done by just placing the code inside the document ready event. Let get understand use of ready event in jQuery as an example.

<div id="test1"></div>
<script type="text/javascript">
function DocumentReady()
{
        $("#test1").text("Hello, world!");   
}

$(document).ready(DocumentReady);
</script>
What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.

However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you're new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:
<div id="test2"></div>
<script type="text/javascript">
$(document).ready(function()
{
        $("#test2").text("Hello, world!");   
});
</script>
But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:
<div id="test3"></div>
<script type="text/javascript">
$(function()
{
        $("#test3").text("Hello, world!");   
});
</script>
In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.

As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.

Sunday, May 10, 2015

Know about jQuery effects

1 comment
The jQuery library provides several techniques for adding animation to a web page. There are many jQuery effects which will provides to do various kind of amazing effects with web interface. The jQuery API have many jQuery methods allow us to quickly apply commonly used effects, the jQuery effects. This tutorial deals with important jQuery effects.

Basic jQuery effects

Showing and Hiding Elements with jQuery

There are two functions, hide() and show() for showing and hiding any DOM elements. 
Syntax :
.show( duration [, easing ] [, complete ] ) 
.hide( duration [, easing ] [, complete ] )

Where the meanings are  -
        • duration (default: 400)
          • Type: Number or String
          • A string or number determining how long the animation will run.
        • easing (default: swing)
          • Type: Number or String
          • A string or number determining how long the animation will run.
$(selector).hide(speed,callback);
$(selector).show(speed,callback);

$("#hide").click(function(){
  $("p").hide();
});

$("#show").click(function(){
  $("p").show();
});

Sunday, May 3, 2015

jQuery events with examples

No comments
We have learn about the syntax of jQuery. The syntax have two major part in it, one the selector and other the events. We already gone through the lists of selectors, now time to take few step toward the jQuery events.

What are Events?

The action of the user to which the browser response from the web page is the event.  The event is either mouse click, key press, radio button or checkbox selection etc.

Like javascript, jQuery act on the DOM events. Below is list of few events -
Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload

jQuery Events Examples

Example 1: click event
$("p").click(function(){
$(this).hide();
});
This will select the p element and on click by user hide it.

Example 2: mouse hover event
$("#mousehover").hover(function(){
alert("You mouser the element!");
});
This function will alert the message, when mouser is hover over the element with id mousehover.

Example 3: blur event
$("input").blur(function(){
  $(this).css("background-color","yellow");
});
This function will on blur over any input element, changes the background color of that element to yellow.
Example4: focus event
$("input").focus(function(){
  $(this).css("background-color","red");
});
This function will on focus over any input element, changes the background color of that element to red. When focus is out it will back to it original color (backed by blur).

Example 5: change event
$("input").change(function(){
 alert("Text successfully changed.");
 $(this).css("background-color","#ccc");
 });
This function will alert the message and changes background color  to mentioned color code of  input element. This happens when text is tried to changed in the input element.

Example 6: keypress event
$("input").keypress(function(){
 $("span").text(i+=1);
 });
This function will add up the text count by one, each time a key get pressed by user.

Example 7: select event
$("input").select(function(){
 alert("Text selected!");
 });
This function will alert the message when the text inside input element is selected.

Example 8: submit event
$("form").submit(function(){
 alert("Submitted");
 });
This event alert if form with name attribute of  'form' get submitted by user on submit button click.

Example 9: scroll event
$("div").scroll(function(){
 $("span").text(x+=1);
 });
This event will count and increase the number by one in text as user scroll either up or down.

Example 10: ready event

This is most important event. The ready event occurs when the DOM (document object model) has been loaded, and the page has been fully loaded (including images). Since this event loads as DOM load so it is a good practice to place all the other jQuery events and functions inside it.
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
$("input").keypress(function(){
$("span").text(i+=1);
});
});
As seen this event perform other two task as mentioned above.