No Data Message Show - php

this code,i have done searching through enroll number. All code are correct and running properly but when match data are not found. No message shown .so, i want to show a message when match data are not found like that "No Such Data Found".
How can i do this? please help to solve that problem,
My code is below.
index.php
<!DOCTYPE html>
<html>
<head>
<title>How to return JSON Data from PHP Script using Ajax Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#result {
position: absolute;
width: 100%;
max-width:870px;
cursor: pointer;
overflow-y: auto;
max-height: 400px;
box-sizing: border-box;
z-index: 1001;
}
.link-class:hover{
background-color:#f1f1f1;
}
</style>
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">How to return JSON Data from PHP Script using Ajax Jquery</h2>
<h3 align="center">Search Employee Data</h3><br />
<div class="row">
<div class="col-md-4">
<input type="text" name="employee_list" id="employee_list" class="form-control">
</div>
<div class="col-md-4">
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
</div>
</div>
<br />
<div class="table-responsive" id="employee_details" style="display:none">
<table class="table table-bordered">
<tr>
<td width="10%" align="right"><b>Name</b></td>
<td width="90%"><span id="name"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Address</b></td>
<td width="90%"><span id="address"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Gender</b></td>
<td width="90%"><span id="total_marks"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Designation</b></td>
<td width="90%"><span id="email"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Age</b></td>
<td width="90%"><span id="ph"></span></td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#search').click(function(){
var enroll= $('#employee_list').val();
if(enroll != '')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{enroll:enroll},
dataType:"JSON",
success:function(data)
{
if(data.length != 0){
$('#employee_details').css("display", "block");
$('#name').text(data.name);
$('#address').text(data.address);
$('#total_marks').text(data.total_marks);
$('#ph').text(data.ph);
$('#email').text(data.email);
}
else { alert("Please Select Employee"); }
}
})
}
else
{
alert("Please Select Employee");
$('#employee_details').css("display", "none");
}
});
});
</script>
fetch.php
<?php
//fetch.php
if(isset($_POST["enroll"]))
{
$connect = mysqli_connect("localhost", "root", "", "aviation");
$query = "SELECT * FROM student WHERE enroll = '".$_POST["enroll"]."'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$data["name"] = $row["name"];
$data["address"] = $row["address"];
$data["total_marks"] = $row["total_marks"];
$data["email"] = $row["email"];
$data["ph"] = $row["ph"];
}
echo json_encode($data);
}
}
?>

In your PHP code, you seam to use a loop to fetch database rows. But your PHP Code acts like you only receive 1 row on data.
Ill consider for the moment that you only will get 1 row of data unless you specify otherwise.
You already check if mysql returns 1 or more results.
So, all we need is a variable that tells you if a results has been found.
Example:
<?php
$output = array(
'result' => 0
);
if (isset($_POST["enroll"])) {
$connect = mysqli_connect("localhost", "root", "", "aviation");
$query = "SELECT name,address,total_marks,email,ph FROM student WHERE enroll = '" . $_POST["enroll"] . "'";
$result = mysqli_query($connect, $query);
if (mysql_num_rows($result) == 1) {
$output['row'] = mysqli_fetch_array($result);
$output['result'] = 1;
}
}
echo json_encode($output);
Then, if your javascript code, you only have to test if the data.result is equal to 1 or 0 and act accordingly. Example:
<script>
$(document).ready(function () {
$('#search').click(function () {
var enroll = $('#employee_list').val();
if (enroll != '')
{
$.ajax({
url: "fetch.php",
method: "POST",
data: {enroll: enroll},
dataType: "JSON",
success: function (data)
{
if(data.result == 1){
$('#employee_details').css("display", "block");
$('#name').text(data.row.name);
$('#address').text(data.row.address);
$('#total_marks').text(data.row.total_marks);
$('#ph').text(data.row.ph);
$('#email').text(data.row.email);
}
else{
alert("No Such Data Found");
}
}
})
} else
{
alert("Please Select Employee");
$('#employee_details').css("display", "none");
}
});
});
</script>
Edit: be carefull, you should also sanitise the POST variable before using it in your mysql query

you could just add
error: function(){
alert('No Such Data Found!');
}
after the success:function(data)
so your ajax call would be like :
$.ajax({
url:"fetch.php",
method:"POST",
data:{enroll:enroll},
dataType:"JSON",
success:function(data)
{
if ($.trim(data)){
$('#employee_details').css("display", "block");
$('#name').text(data.name);
$('#address').text(data.address);
$('#total_marks').text(data.total_marks);
$('#ph').text(data.ph);
$('#email').text(data.email);}
else{alert('No Such Data Found!')}
},
error: function(){
alert('error !');
}
or add an else in your php code that return a false if result is empty :
if(mysql_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
//code ......
}
echo json_encode($data);
}else {
return false;
}
then your ajax call would be like :
$.ajax({
url:"fetch.php",
method:"POST",
data:{enroll:enroll},
dataType:"JSON",
success:function(data)
{
if(data != false){
$('#employee_details').css("display", "block");
$('#name').text(data.name);
$('#address').text(data.address);
$('#total_marks').text(data.total_marks);
$('#ph').text(data.ph);
$('#email').text(data.email);}else{alert('No Such Data Found!');}
}

Related

how to search a username in php ajax

hey guys I need some help please guide me where I am doing wrong in coding. This is table of showing record of users
I want pagination operation and search operation on my index.php file. Pagination is working but when I am type a single letter (example: a or Haris) on search bar then show me message that data not found this is message showing when type a username on search bar
This my ajax function that on index.php file I am pagination or search
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#message').keyup(function(){
var srch = $(this).val();
if(srch != '')
{
load_data(srch);
}
else
{
load_data();
}
});
function load_data(page)
{
$.ajax({
url:"search.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
This my search.php file
<?php
include("common/config.php");
$output = '';
if(isset($_POST["query"]))
{
$search = $_POST["query"];
$where = "id LIKE '%".$search."%'
OR name LIKE '%".$search."%'
OR email LIKE '%".$search."%'
OR phone LIKE '%".$search."%'";
$query = $db->select(array("*"),"user","$where","","id desc","");
}
else
{
$limit = 5;
$page = '';
if (isset($_GET["page"] ))
{
$page = $_GET["page"];
}
else
{
$page=1;
}
$record_index= ($page-1) * $limit;
$query = $db->select(array("*"),PREFIX."user", "", "", "id desc", "$record_index, $limit");
}
if($query)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th style="text-align: center !important;"><input type="checkbox" name="select_all" id="select_all" value=""/></th>
<th style="text-align: center !important;">ID</th>
<th style="text-align: center !important;">Name</th>
<th style="text-align: center !important;">Email</th>
<th style="text-align: center !important;">Phone</th>
<th colspan="4" style="text-align: center !important;">Action</th>
</tr>
';
foreach($query as $row)
{
$output .= '
<tr align="center">
<td align="center"><input type="checkbox" name="checked_id[]"
class="checkbox" value="'.$row->id.'"/></td>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->phone.'</td>
<td>Edit</td>
<td><a onclick="return confirm(\'Are you sure to delete?\')"
href="del.php?del='.$row->id.'">Delete</a></td>
</tr>';
}
$output .= '</table><br /><div align="center">';
$total_pages = ceil($db->countfields("*","user") / $limit);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
}
else
{
echo 'Data Not Found';
}
?>
When I am change the name of function,pagination is working but its still search a user record not working.
<script>
$(document).ready(function(){
load_data_1();
load_data_2();
function load_data_1(query)
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#message').keyup(function(){
var srch = $(this).val();
if(srch != '')
{
load_data(srch);
}
else
{
load_data_1();
}
});
function load_data_2(page)
{
$.ajax({
url:"search.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data_2(page);
});
});
</script>
I don't see from your code what "PREFIX" is, but in the search query it is missing while it is present in the pagination query. Hope it helps

Php ajax update button not working in jquery [duplicate]

list.php: A simple ajax code that I want to display only records of the Mysql table:
<html>
<head>
<script src="jquery-1.9.1.min.js">
</script>
<script>
$(document).ready(function() {
var response = '';
$.ajax({
type: "GET",
url: "Records.php",
async: false,
success: function(text) {
response = text;
}
});
alert(response);
});
</script>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<button>Get Records</button>
</body>
</html>
Records.php is the file to fetch records from Mysql.
In the Database are only two fields: 'Name', 'Address'.
<?php
//database name = "simple_ajax"
//table name = "users"
$con = mysql_connect("localhost","root","");
$dbs = mysql_select_db("simple_ajax",$con);
$result= mysql_query("select * from users");
$array = mysql_fetch_row($result);
?>
<tr>
<td>Name: </td>
<td>Address: </td>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>$row[1]</td>";
echo "<td>$row[2]</td>";
echo "</tr>";
}
?>
This code is not working.
For retrieving data using Ajax + jQuery, you should write the following code:
<html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
For mysqli connection, write this:
<?php
$con=mysqli_connect("localhost","root","");
For displaying the data from database, you should write this :
<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "</tr>";
}
echo "</table>";
?>
You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.
AjaxGet = function (url) {
var result = $.ajax({
type: "POST",
url: url,
param: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
// nothing needed here
}
}) .responseText ;
return result;
}
Please make sure your $row[1] , $row[2] contains correct value, we do assume here that 1 = Name , and 2 here is your Address field ?
Assuming you have correctly fetched your records from your Records.php, You can do something like this:
$(document).ready(function()
{
$('#getRecords').click(function()
{
var response = '';
$.ajax({ type: 'POST',
url: "Records.php",
async: false,
success : function(text){
$('#table1').html(text);
}
});
});
}
In your HTML
<table id="table1">
//Let jQuery AJAX Change This Text
</table>
<button id='getRecords'>Get Records</button>
A little note:
Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions are no longer encouraged..
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
response = text;
}
});
alert(response);
});
needs to be:
$(document).ready(function(){
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
alert(text);
}
});
});
This answer was for #
Neha Gandhi but I modified it for people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer
<html>
<!--Save this as index.php-->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
<?php
// save this as display.php
// show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
//errors ends here
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName = $row['lastName'];
$cell = $row['cell'];
echo "<tr>";
echo "<td align=center>$firstName</td>";
echo "<td align=center>$empid</td>";
echo "<td align=center>$lastName </td>";
echo "<td align=center>$cell</td>";
echo "<td align=center>$cell</td>";
echo "</tr>";
}
echo "</table>";
?>
<?php
// save this as dbconnector.php
function connected_Db(){
$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
#echo "Yes we are connected";
return new PDO($dsn,'username','password', $opt);
}
$con = connected_Db();
if($con){
//echo "me is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

Trying to display live table which is editable using ajax and php

I have four different files
index.php
select.php
insert.php
edit.php
delete.php
In my backend I have created a database named 'ecc'
Database 'ecc' has atable named 'task'
The table task has following fields
id, name, category, cost
Datatype for id set to int and index as primary also id field is on auto increment
My Issue:My code is only displaying 'Live Table Data'.
It would be grate if someone rewrite it or suggest some changes.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var name = $('#name').text();
var category = $('#category').text();
var cost = $('#cost').text();
if(name == '')
{
alert("Enter Service Name");
return false;
}
if(category == '')
{
alert("Enter Category of Service");
return false;
}
if(cost == '')
{
alert("Enter cost");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{name:name, category:category, cost:cost},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.category', function(){
var id = $(this).data("id2");
var category = $(this).text();
edit_data(id,category, "category");
$(document).on('blur', '.cost', function(){
var id = $(this).data("id3");
var category = $(this).text();
edit_data(id,cost, "cost");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id4");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$output = '';
$sql = "SELECT * FROM task ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
<td class="cost" data-id3="'.$row["id"].'" contenteditable>'.$row["cost"].'</td>
<td><button type="button" name="delete_btn" data-id4="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="name" contenteditable></td>
<td id="category" contenteditable></td>
<td id="cost" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$sql = "INSERT INTO tbl_sample(name, category, cost) VALUES('".$_POST["name"]."', '".$_POST["category"]."', '".$_POST["cost"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
}
?>
edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$id = $_POST["id"];
$text = $_POST["text"];
$column_name = $_POST["column_name"];
$sql = "UPDATE task SET ".$column_name."='".$text."' WHERE id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
delete.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$sql = "DELETE FROM task WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
you can use data tables for this, no need of all this
https://editor.datatables.net/examples/inline-editing/simple
check this, data tables provide libraries for this

Issue of undefined index while using ajax and php

I have four different files
index.php
select.php
insert.php
edit.php
delete.php
In my backend I have created a database named 'ecc'
Database 'ecc' has atable named 'task'
The table task has following fields
id, name, category, cost
Datatype for id set to int and index as primary also id field is on auto increment
My issue :( ! ) Notice: Undefined index: id in C:\wamp\www\select.php on line 38
and same for lines 39, 40, 41,
each of the error is displayed twice on the page.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var name = $('#name').text();
var category = $('#category').text();
if(name == '')
{
alert("Enter service Name");
return false;
}
if(category == '')
{
alert("Enter category");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{name:name, category:category},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.category', function(){
var id = $(this).data("id2");
var category = $(this).text();
edit_data(id,category, "category");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
$connect = mysqli_connect('localhost', 'root', '','ecc');
mysqli_select_db($connect,'ecc');
if(!$connect){
echo "yes";
}else{
echo "no";
}
$output = '';
$sql = "SELECT name, category FROM addservices ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">Service Name</th>
<th width="40%">Category</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="name" contenteditable></td>
<td id="category" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
You are getting this error Undefined index: id
Because you have not put id in select query
$sql = "SELECT id,name, category FROM addservices ORDER BY id DESC";
Chek your query.It need to change as:
$sql = "SELECT * FROM task ORDER BY id DESC";
You are getting this error because you have not selected "id" field in the $sql statement.
You have writen -
$sql = "SELECT name, category FROM addservices ORDER BY id DESC";
It should be
$sql = "SELECT id, name, category FROM addservices ORDER BY id DESC";

Using Jquery Ajax to retrieve data from Mysql

list.php: A simple ajax code that I want to display only records of the Mysql table:
<html>
<head>
<script src="jquery-1.9.1.min.js">
</script>
<script>
$(document).ready(function() {
var response = '';
$.ajax({
type: "GET",
url: "Records.php",
async: false,
success: function(text) {
response = text;
}
});
alert(response);
});
</script>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<button>Get Records</button>
</body>
</html>
Records.php is the file to fetch records from Mysql.
In the Database are only two fields: 'Name', 'Address'.
<?php
//database name = "simple_ajax"
//table name = "users"
$con = mysql_connect("localhost","root","");
$dbs = mysql_select_db("simple_ajax",$con);
$result= mysql_query("select * from users");
$array = mysql_fetch_row($result);
?>
<tr>
<td>Name: </td>
<td>Address: </td>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>$row[1]</td>";
echo "<td>$row[2]</td>";
echo "</tr>";
}
?>
This code is not working.
For retrieving data using Ajax + jQuery, you should write the following code:
<html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
For mysqli connection, write this:
<?php
$con=mysqli_connect("localhost","root","");
For displaying the data from database, you should write this :
<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "</tr>";
}
echo "</table>";
?>
You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.
AjaxGet = function (url) {
var result = $.ajax({
type: "POST",
url: url,
param: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
// nothing needed here
}
}) .responseText ;
return result;
}
Please make sure your $row[1] , $row[2] contains correct value, we do assume here that 1 = Name , and 2 here is your Address field ?
Assuming you have correctly fetched your records from your Records.php, You can do something like this:
$(document).ready(function()
{
$('#getRecords').click(function()
{
var response = '';
$.ajax({ type: 'POST',
url: "Records.php",
async: false,
success : function(text){
$('#table1').html(text);
}
});
});
}
In your HTML
<table id="table1">
//Let jQuery AJAX Change This Text
</table>
<button id='getRecords'>Get Records</button>
A little note:
Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions are no longer encouraged..
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
response = text;
}
});
alert(response);
});
needs to be:
$(document).ready(function(){
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
alert(text);
}
});
});
This answer was for #
Neha Gandhi but I modified it for people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer
<html>
<!--Save this as index.php-->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
<?php
// save this as display.php
// show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
//errors ends here
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName = $row['lastName'];
$cell = $row['cell'];
echo "<tr>";
echo "<td align=center>$firstName</td>";
echo "<td align=center>$empid</td>";
echo "<td align=center>$lastName </td>";
echo "<td align=center>$cell</td>";
echo "<td align=center>$cell</td>";
echo "</tr>";
}
echo "</table>";
?>
<?php
// save this as dbconnector.php
function connected_Db(){
$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
#echo "Yes we are connected";
return new PDO($dsn,'username','password', $opt);
}
$con = connected_Db();
if($con){
//echo "me is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

Categories