JQuery Ajax with get
From w3cyberlearnings
Contents |
What is get method in jQuery?
- The get() method uses and perform request based on the AJAX HTTP GET request
- when uses get() method you must use $_GET[] or $_REQUEST[] in PHP to process the data,
if you try to use $_POST[] you will not be able to process the request data
get() method syntax
- url: URL to send request to
- data (optional): data send along the request
- success (optional): when the request success.
response: contain response data from the request
status: response status type (success, notmodified, error,timeout, or parseerror)
xhr: contain the XMLHttpRequest object
- dataType: data type uses for the response
xml: XML document data type
html: HTML or text data type
text: text string data type
script: runs response as javascript data type, and returns it as text
json: runs response as json data type, and return as javascript object
jsonp: loads in a json block by using JSONP
$.get() method syntax
$(selector).get(url,data,success(response,status,xhr),dataType)
get() method Example 1
- goodtext.txt expect to contain some string
- When running this example, you will be able to see the content of the goodtext.txt load
into the home page.
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Profile List</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $.get('goodtext.txt',function(data){ $('#content').html(data); },'text'); }); </script> </head> <body> <div id="content"></div> </body> </html>
get() method Example 2
mygreeting.php
<?php $user_id = $_GET['id']; if (!empty($user_id)) { if ($user_id == 1) { echo 'Good work!'; } else if ($user_id == 2) { echo 'Great day!'; } else { echo 'Must be something else!'; } } else { echo 'Please try again'; } ?>
jquery_get.html
- This get method require the parameter.
<script type="text/javascript" language="javascript"> $(document).ready(function() { $.get('mygreeting.php',{id:2},function(data){ $('#content').html(data); },'text'); }); </script>
get() method Example 3
mygreeting.php
<?php $name = $_GET['name']; $location = $_GET['location']; if (!empty($location) && !empty($name)) { printf("%s is from %s", $name, $location); } else { echo 'Please try again'; } ?>
jHtml3.html
- Need two parameters to be sent to the $.get().
<script type="text/javascript" language="javascript"> $(document).ready(function() { $.get('get1.php',{name:'John',location:'NY'},function(data){ $('#content').html(data); },'text'); }); </script>
get() method Example 4
- You need to setup the database in MySQL
- Create table and insert some sample records
Create Table and Insert Records
CREATE TABLE user_profile ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(200) NOT NULL, age INT NOT NULL, PRIMARY KEY(id) ); INSERT INTO user_profile(name,age) VALUES('Bob',39), ('Jing',41), ('Paul',42), ('David',40), ('Jamy',20), ('Christ',28);
get_user.php
<?php define('HOST', 'localhost'); define('USER', 'user2000'); define('PASS', 'password2000'); define('DBNAME', 'w3cyberlearning'); $db = new mysqli(HOST, USER, PASS, DBNAME); $age = $_GET['age']; if (!empty($age)) { if ($db->connect_errno) { echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error; } else { $query = "SELECT * FROM user_profile WHERE age >=?"; $conn = $db->prepare($query); if ($conn) { $conn->bind_param("i", $age); $conn->execute(); $conn->bind_result($id, $name, $age); $my_table = '<table border="1" cellspacing="8" cellpadding="8">'; $my_table .='<tr><td>Id</td><td>Name</td><td>Age</td></tr>'; while ($conn->fetch()) { $my_table .='<tr>'; $my_table .='<td>' . $id . '</td>'; $my_table .='<td>' . $name . '</td>'; $my_table .='<td>' . $age . '</td>'; $my_table .='<tr>'; } $my_table .='</table>'; echo $my_table; } $conn->close(); } } else { echo 'Error, try again!'; } $db->close(); ?>
myUserProfile.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Profile List</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $.get('get_user.php',{age:38},function(data){ $('#content').html(data); },'html'); }); </script> </head> <body> <div id="content"></div> </body> </html>
get() method Example 5
- $(selector).get(url,{},function(){},'json') is same as $(selector).getJSON(url,{},function(){});
get_userjson.php
- This file will query the table and generate json data for return.
<?php define('HOST', 'localhost'); define('USER', 'user2000'); define('PASS', 'password2000'); define('DBNAME', 'w3cyberlearning'); $db = new mysqli(HOST, USER, PASS, DBNAME); $age = $_GET['age']; $result = array('error' => 'sure'); if (!empty($age)) { if ($db->connect_errno) { echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error; } else { $query = "SELECT * FROM user_profile WHERE age >=?"; $conn = $db->prepare($query); if ($conn) { $conn->bind_param("i", $age); $conn->execute(); $conn->bind_result($id, $name, $age); $result = array(); while ($row = $conn->fetch()) { $result[] = array('id' => $id, 'name' => $name, 'age' => $age); } echo json_encode($result); } $conn->close(); } } else { echo json_encode($result); } $db->close(); ?>
jsonTest.html
- You can replace this function with getJSON()
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Profile List</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $.get('get_userjson.php',{age:21},function(data){ if(data.error=='sure'){ $('#content').html('Error processing!'); } else { var table = '<table border="1">'; table += '<tr><td>User Id</td><td>User Name</td><td>User Age</td></tr>'; $.each(data,function(i,element){ table +='</tr>'; table +='<td>'+ element.id + '</td>'; table +='<td>'+ element.name + '</td>'; table +='<td>'+ element.age + '</td>'; table +='</tr>'; }); table +='</table>'; $('#content').html(table); } },'json'); }); </script> </head> <body> <div id="content"></div> </body> </html>
Related Links
Ajax and MySQL Tutorial