Insert Data Into MySQL: jQuery + AJAX + PHP

Video tutorial illustrates insertion of data into MySQL database using jQuery and PHP, using AJAX method i.e., $.post() method of jQuery.

There are 5 shortcuts for AJAX in jQuery, ultimately calling ajax method, and by default configured to have different parameters.
$.get
$.post
$.getJSON
$.getScript
$.load

Tutorial Theme: Insert Data Into Database Without Refreshing Webpage

In this tutorial we’ll illustrate $.post method of jQuery.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head><title>Insert Data Into MySQL: jQuery + AJAX + PHP</title></head>
<body>
 
<form id="myForm" action="userInfo.php" method="post">
Name: <input type="text" name="name" /><br />
Age : <input type="text" name="age" /><br />
<button id="sub">Save</button>
</form>
 
<span id="result"></span>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have a form with an id called myForm, which has 2 input box.
A button with id sub. And a span tag with an id of result.

Once the user enters his/her name, age and hits Save button, the information will be sent to userInfo.php file present in the action field, via post method.

Using AJAX technique, we would make sure the form doesn’t redirect to userInfo.php file after the submission, and we’ll display appropriate message to the user on index.html file itself after the user entered values has been processed by userInfo.php file.

Database Connection code: PHP
db.php

1
2
3
4
< ?php
  $conn = mysql_connect('localhost', 'root', '');
  $db   = mysql_select_db('test');
?>

We connect our application to mysql server using the user name root( and we leave password field empty, as we haven’t set any password to it on our machine ).
Also select the database called test.

Create Database called test.
A table user inside the database test.
user table has 2 fields called name and age.

Processing Page code: PHP
userInfo.php

1
2
3
4
5
6
7
8
9
10
11
< ?php
 include_once('db.php');
 
$name = $_POST['name'];
$age = $_POST['age'];
 
if(mysql_query("INSERT INTO user VALUES('$name', '$age')"))
  echo "Successfully Inserted";
else
  echo "Insertion Failed";
?>

Once the user hits the Save button of our form in index.html, the information is being sent to userInfo.php

Where the user entered values are being copied to local variables $name and $age.
Next a simple MySQL query is formed to insert the data into the table user.

Using mysql_query() standard php function, the MySQL query is being processed.
Using if else conditional statements, we check if the process was successful or failed. Based on which we echo the result.

jQuery code: AJAXing
my_script.js

1
2
3
4
5
6
$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
  });
});

Once the user clicks on the button with the id sub, $.post() method is invoked.
$.post() is a shortcut to $.ajax() method.

General Syntax:
$.post( ‘pass_data_to_this_url’, ‘data’, ‘callback_function’ );

We fetch the URL from myForm form, from its action attribute.
Serialize all the user entered input’s.
SerializeArray makes the input into property: value pair.
After the data is passed to the url and is being processed, the result will be returned back to the callback function and is caught in info variable, and is inserted inside the span tag using html() method – which is similar to innerHTML() method of JavaScript.

jQuery code: Disable Form Redirection
my_script.js

1
2
3
$("#myForm").submit( function() {
  return false;
});

Select the form and make sure to return false upon submission.

jQuery code: Clear Input Fields
my_script.js

1
2
3
4
5
function clearInput() {
$("#myForm :input").each( function() {
   $(this).val('');
});
}

input-fields-form

Write a custom function. Select the input fields and set each of its value to none or empty.
Call this function once the user clicks the submit button.

Full jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
   });
 clearInput();
});
 
$("#myForm").submit( function() {
  return false;
});
 
function clearInput() {
$("#myForm :input").each( function() {
   $(this).val('');
});
}

Note that, we have called clearInput() function inside the click event of #sub.

Video Tutorial: Insert Data Into MySQL: jQuery + AJAX + PHP


[youtube https://www.youtube.com/watch?v=gvGb5Z0yMFY]

YouTube Link: https://www.youtube.com/watch?v=gvGb5Z0yMFY [Watch the Video In Full Screen.]



Note:
You have to implement addslash and stripslash or any other methods into your PHP code, to secure your script from SQL Injection.

If the PHP returns json encoded data, then we need to use json in $.post() method as follows:

1
2
3
4
5
$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); },
         "json" );

But in our example, we are not returning json encoded data from userInfo.php file, so we do not specify encoding information in $.post() method.

Reading XML File Using jQuery AJAX Method

Video tutorial to read XML file using jQuery ajax method.

AJAX full form: Asynchronous JavaScript and XML
We’ll also see the use of setTimeout() function.

Using AJAX technique, we fetch only the required data from the server without reloading the entire page.

In this video tutorial, we fetch the data present in XML format and display fetched content on the webpage and update it in real time, without reloading the html page.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head><title>Reading an XML file using jQuery</title></head>
<body>
 
 <ul></ul>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have 1 ul tag. We’ll load the list items dynamically using jQuery, from XML file.

XML File Content
corporateData.xml

1
2
3
4
5
6
7
8
9
< ?xml version="1.0" ?>
 
<corporate>
 <employee>
  <name>Satish</name>
  <age>25</age>
  <company>Microsoft</company>
 </employee>
</corporate>

Here we have a base tag called corporate. Inside that we have employee details like name, age and company which is bound inside employee tag. Each employee will have his/her details inside separate/individual employee tag.

For more about XML, please visit XML category.

jQuery File: corporateData() function
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function corporateData() {
 
$.ajax({ 
 
 url: "corporateData.xml",
 dataType: "xml",
 success: function(data) {
 
  $("ul").children().remove();
 
  $(data).find("employee").each( function() {
 
   var info = '<li>Name: '+$(this).find("name").text()+'</li>
                       <li>Age: '+$(this).find("age").text()+'</li>
                       <li>Company: '+$(this).find("company").text()+'</li>';
 
   $("ul").append(info);
 
  });
 
 },
 error: function() { $("ul").children().remove(); 
                             $("ul").append("<li>There was an error baby!</li>"); }
     });
}

Here we write a custom jQuery function called corporateData.
$.ajax() is a jQuery static method and it has a lot of properties. In this tutorial, we illustrate url, dataType, success and error properties.
Specify the url from which the data has to be fetched, along with its data type.
If the file gets parsed successfully, the function inside the success property gets executed. If there is an error, the error property function gets triggered.

Once the xml file gets parsed successfully, $.ajax method throws an object which contains xml file data. We catch this data with anonymous function present in success property.
Next, we clear any previous data got attached to the unordered list of html document.

Using the object, we find each employee tags present inside the XML file, fetch individual name, age and company names and then append it to the unordered list.

jQuery File: setTimeout() method
my_script.js

1
2
3
4
5
6
7
8
function fetch() {
 
setTimeout( function() {
 corporateData();
fetch();
}, 100);
 
}

Inorder to make sure our application fetches the fresh data from the XML file, we check the XML file after certain period of time.
Using setTimeout() method of jQuery:
setTimeout() takes two parameters, first one being the function names to be called and the second one being the time interval after which those functions has to be called.

using setTimeout() we have called itself( fetch() ) and corporateData() function. This makes sure, whenever the XML file gets updated, our application fetches the data and displays on our webpage, without refreshing the page.

jQuery File: call the functions to make it work
my_script.js

1
2
3
4
$(document).ready( function() {
 corporateData();
fetch();
});

Make sure to call both corporateData and fetch method once the page loads. This makes sure the XML data is fetched before fetch functions tries to re-fetch the things.

jQuery File: Complete Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$(document).ready( function() {
 corporateData();
fetch();
});
 
function fetch() {
 
setTimeout( function() {
 corporateData();
fetch();
}, 100);
 
}
 
function corporateData() {
 
$.ajax({ 
 
 url: "corporateData.xml",
 dataType: "xml",
 success: function(data) {
 
  $("ul").children().remove();
 
  $(data).find("employee").each( function() {
 
   var info = '<li>Name: '+$(this).find("name").text()+'</li>
                       <li>Age: '+$(this).find("age").text()+'</li>
                       <li>Company: '+$(this).find("company").text()+'</li>';
 
   $("ul").append(info);
 
  });
 
 },
 error: function() { $("ul").children().remove(); 
                             $("ul").append("<li>There was an error baby!</li>"); }
});
}

corporateData.xml and index.html files must be in the same folder.

Video Tutorial: Reading XML File Using jQuery AJAX Method


[youtube https://www.youtube.com/watch?v=Dj3MP5w0dpc]

YouTube Link: https://www.youtube.com/watch?v=Dj3MP5w0dpc [Watch the Video In Full Screen.]



Note:
Make sure you open the html file from a server(even from localhost), and not directly from a folder. XML and the files which are fetching XML data must be on the same server, otherwise XML data won’t be fetched.

Testing The Application
To test this small application, open the index.html file from the server, and then add / modify / delete any entry. Once you save the XML file, the content of XML file must get updated on the html file immediately without the page(index.html) being reloaded.

Custom Functions: jQuery

Video tutorial illustrates writing custom functions in jQuery.

Following topics are covered in the video:
Function Declaration.
Function Expression.
Passing parameters.
Returning value.
Returning nothing, etc ..

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head><title>Functions in jQuery!</title></head>
<body>
 
<span></span>
<button id="name">Software</button>
 
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have 1 span tag for display purpose and a button with an id name.

jQuery code: Passing Parameter To Function
my_script.js

1
2
3
4
5
6
7
8
9
$(document).ready( function() {
 fun1("Oracle");
});
 
 
function fun1(text){
  $("span").append(text);
  return false;
}

function is a keyword, fun1 is a function name we have given.
Once the webpage is loaded, fun1 function will be called, and Oracle is passed to it as parameter.
Inside fun1(), the span tag is selected and the passed parameter is appended to the span tag.
Since the function doesn’t return any value back, we have written return false.

jQuery code: Passing Parameter To Function And Returning Value
my_script.js

1
2
3
4
5
6
7
8
9
10
$(document).ready( function() {
 
 var d = fun1(10, 20);
 $("span").append(d);
 
});
 
function fun1(a, b){
     return(a+b);
}

Once the webpage is loaded, fun1 function will be called, and 10, 20 is passed to it as parameters.
Inside fun1(), 10 and 20 are added and the resulting value is returned back to the calling function, where in it is stored in a variable called d, where we append it to the span tag.

jQuery code: Function Expression
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
  $("#name").click(software);
});
 
var software = function() {
 $("span").append("<h1>Microsoft ltd</h1>");
 return false;
}

Here, once the user clicks on the button(with an id name), the custom function software gets invoked.
Since the function here doesn’t return any value, we have written return false;

jQuery code: Function Expression with Event Binding
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
  $("#name").bind('click', software);
});
 
var software = function() {
 $("span").append("<h1>Microsoft ltd</h1>");
 return false;
}

Here we bind the event click to the button and then invoke the function software.

Video Tutorial: Custom Functions: jQuery


[youtube https://www.youtube.com/watch?v=P_68D1foqXg]

YouTube Link: https://www.youtube.com/watch?v=P_68D1foqXg [Watch the Video In Full Screen.]



Main Purposes of writing a function:
Re-usability of code.
Reduce the number of lines of code.
Cleaner looking code.
We could easily trace, modify and maintain the code.

Helps in Object Oriented Programming, as the data is bind to methods.
We could write the code in such a way that, we could pass different parameters to the same function and get desired results. Hence reducing a lot of code overhead and cost of writing extra useless codes!

Detach and Attach DOM Elements: jQuery Array

Video tutorial illustrates the use of jQuery’s special type of variable called array.

Array variable stores multiple data with single name with different index. Indexing starts from zero in jQuery.
This helps in storing and retrieving easily using some conditional looping.

In this example, we take a unordered list with some list items which has two type of class veg and nonveg.
Another ordered list, with only 1 list item.
Two buttons. One to detach the items from unordered list, which has a class called veg.
Another button, to attach it to the ordered list.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head><title>Detach and Attach DOM Elements: jQuery Arrays!</title></head>
<body>
 
<ul>
<li class="veg">Rice</li>
<li class="nonveg">Fish</li>
<li class="nonveg">Chicken</li>
<li class="veg">Veg Pizza</li>
</ul>
 
<ol>
<li class="veg">Veg Paneer</li>
</ol>
 
<button id="remove">Remove</button>
<button id="attach">Attach</button>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here you have 1 unordered list. 1 Ordered list and 2 buttons.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
 $("#remove").click( function() {
   $store = $("ul li.veg").detach();
 });
 
 $("#attach").click( function() {
   $("ol li").after($store);
 });
 
});

Once the user clicks on the button with the id remove, we detach the list items with class veg from the unordered list and store it inside the special jQuery array variable.
Next, when the user clicks on the button with the id of attach, we attach it to the ordered list using append(), after(), before() methods of jQuery, by passing the array variable to these methods.

Video Tutorial: Detach and Attach DOM Elements: jQuery Array


[youtube https://www.youtube.com/watch?v=UHSrD8j5Czc]

YouTube Link: https://www.youtube.com/watch?v=UHSrD8j5Czc [Watch the Video In Full Screen.]



Unlike remove() method, detach() doesn’t delete the DOM structure or the HTML elements.

Related Read:
jQuery Methods and CSS: Restaurant Application

Note: You could even use the normal javascript arrays in jQuery too. We shall look at it in the future videos.

Conditional Logic For Decision Making: jQuery

In this video tutorial we shall see how to make our applications smarter with artificial intelligence using conditional logic for decision making, using jQuery.

Here we take 2 numbers from the user and using jQuery, we find the result of division of those two numbers. If the user tries to divide by zero, then we alert the user with a message, that “Division by zero is not allowed”. Thus making our application smarter and get the feel of artificial intelligence!

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head><title>Conditional Logic For Decision Making: jQuery</title></head>
<body>
 
<form>
No1: <input type="text" id="no1" /><br />
No2: <input type="text" id="no2" />
<button>Division</button>
</form>
 
<span></span>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have a form, with 2 input box and a button.
There is a span tag to display the appropriate messages.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready( function() {
 
 $("button").click( function() {
     var no1 = $("#no1").val();
 var no2 = $("#no2").val();
 
 if( no2 == 0 )
   $("span").html("Division by zero not allowed!");
 else if( no2 == 1 )
   $("span").html("Division of "+no1+" and "+no2+" is "+(no1/no2));
 else
 
 $("form").submit( function() { return false; });
 });
});

Here we fetch and assign the values entered by the user to local variables.
using conditional operator, if else, we see if the second number entered by the user is zero.
If its zero, we show “Division by zero not allowed!” message, else we show the result of division.

We also need to make the form submit return false, so that the form doesn’t try to redirect to some other page once the user clicks on the submit button.

Video Tutorial: Conditional Logic For Decision Making: jQuery


[youtube https://www.youtube.com/watch?v=JMXbyAUMmEk]

YouTube Link: https://www.youtube.com/watch?v=JMXbyAUMmEk [Watch the Video In Full Screen.]



Comparison Operators
1. Equality: a == b;
2. Inequality: a != b;
3. Exactly Equal: a === b;
4. Greater than: a > b;
5. Greater than or equal to: a >= b;
6. Less than: a < b; 7. Less than or equal to: a < = b; Logical Operators: Negation: !a OR: a || b; AND: a && b;

TruthTable

Negation: True if a is false or doesn’t exist in the DOM.
OR: True if a is true or b is true, or if both are true, but not if both are false.
AND: True if a is true and b is true, but not if one or the other is false.

Ternary Operator
Ex: a > b ? if_true_code : else_this_code;

If a is greater than b, then if_true_code will be executed, else else_this_code will be executed.

Also see Ternary Operator in C for understanding the logic.
Biggest of Two Numbers Using Ternary Operator: C++.
Biggest of 3 Numbers Using Ternary Operator: C++.

Note: If there is only 1 statement inside the if and/or elseif and/or else, we need not put the code inside the brackets. If there are multiple statements then we MUST put the code inside the brackets. Also we can have any number of elseif’s in a if else block, but only 1 if and only 1 else part in it. We could have any number of if-elseif-else blocks in a program.

Also note that, we can have if without elseif and else. But we can not have elseif and else without if!