I have a HTML table with three columns
ID, BuildingLocation, Status
and a Active Link in each row. When I Click on Active Link, Status value changed from 0 to 1 into the database but updated value data from the database is not displayed into the HTML table. It will display when I press the F5 key.
Building.php
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function Active(ID)
{
$.ajax(
{
type: "POST",
url: "buildingactive.php",
data: {ID:ID},
dataType: "JSON",
success: function(data)
{
$("#Response").html(data);
},
error: function(err)
{
//console.log("Fail"+err.call);
$("#Response").html(err);
}
});
}
</script>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Location</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$sq="Select * from buildingmaster";
$Table=mysqli_query($CN,$sq);
while ($Row=mysqli_fetch_array($Table))
{
$ID=$Row['ID'];
echo("<tr>");
echo("<td>".$Row["ID"]."</td>");
echo("<td>".$Row["BuildingLocation"]."</td>");
echo("<td>".$Row["Status"]."</td>");
echo("<td>");
echo("<a href='#' onclick='Active($ID)'>Change</a>");
echo("</td>");
echo("</tr>");
}
?>
</table>
<?php
echo("<div>");
echo("<p id='Response'></p>");
echo("</div>");
?>
</body>
</html>
buildingactive.php
This is my PHP file which is used to update the status column of the buildingmaster table.
<?php
$ID=$_POST['ID'];
$UpdateQuery="Update buildingmaster set Status=1 where ID=$ID";
require_once "connection.php";
$R=mysqli_query($CN,$UpdateQuery);
if($R==1)
{
$res="Building Active Successfully:";
echo json_encode($res);
}
else
{
$error="Server Error... Try Again...";
echo json_encode($error);
}
?>
You have to pass status value along with success message like,
$res={status:'1', msg: 'Building Active Successfully:'};
And you have to decode the data in Ajax success
var myObj = $.parseJSON(data);
Modified Code,
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function Active(ID)
{
$.ajax(
{
type: "POST",
url: "buildingactive.php",
data: {ID:ID},
dataType: "JSON",
success: function(data)
{
$("#Response").html(data.msg);
$(".row"+ID).text(data.staus);
$("#Response").addClass("alert alert-success");
$("#Response").fadeOut(3000);
},
error: function(err)
{
//console.log("Fail"+err.call);
$("#Response").html(err);
$("#Response").addClass("alert alert-danger");
$("#Response").fadeOut(3000);
}
});
}
</script>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Location</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$sq="Select * from buildingmaster";
$Table=mysqli_query($CN,$sq);
while ($Row=mysqli_fetch_array($Table))
{
$ID=$Row['ID'];
echo("<tr>");
echo("<td class='row".$ID."'>".$Row["ID"]."</td>");
echo("<td>".$Row["BuildingLocation"]."</td>");
echo("<td>".$Row["StatusName"]."</td>");
echo("<td>");
echo("<a href='#' onclick='Active($ID)'>Change</i></a>");
echo("</td>");
echo("</tr>");
}
?>
</table>
<?php
echo("<div>");
echo("<p id='Response'></p>");
echo("</div>");
?>
</body>
</html>
<?php
$ID=$_POST['ID'];
$UpdateQuery="Update buildingmaster set Status=1 where ID=$ID";
require_once "connection.php";
$R=mysqli_query($CN,$UpdateQuery);
if($R==1)
{
$res={status:'1', msg: 'Building Active Successfully:'};
echo json_encode($res);
}
else
{
$error="Server Error... Try Again...";
echo json_encode($error);
}
?>
Add to success: function(data){}
either window.location.reload(); or you can
assign
window.location = window.location
Related
I try to make some reorder with drag and drop with PHP and some ajax with this tutorial.
I set up my files for my needs but nothing going on.
On my index.php just change this thing that equal to my MySQL
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
Here is Java script in index.php:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
var selectedData = new Array();
$('.row_position>tr').each(function() {
selectedData.push($(this).attr("id"));
});
updateOrder(selectedData);
}
});
function updateOrder(data) {
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:data},
success:function(){
alert('your change successfully saved');
}
})
}
</script>
</html>
Here is and ajaxPro.php that i change:
require('db_config.php');
$position = $_POST['position'];
$i=1;
foreach($position as $k=>$v){
$sql = "Update `channels` SET `channel_number`=".$i." WHERE `id`=".$v;
$mysqli->query($sql);
$i++;
}
And here is MySQL
When I try to reorder, just want to change field channel_number but nothing goings-on. Where is my mistake
I've change some code, and turn on some log, but still have problem. If anyone can assist will be so happy. Here it is:
index.php
<div class="container">
<h3 class="text-center">Dynamic Drag and Drop table rows in PHP Mysql - ItSolutionStuff.com</h3>
<table id="myTable" class="table table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">#</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody class="row_position">
<?php
require('db_config.php');
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>"> <!-- data-channel-number="<?php echo $user['channel_number'] ?>">-->
<td><?php echo $user['id'] ?></td>
<td class="index"><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- container / end -->
</body>
<!--<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
//console.log(chArray);
}
});
</script>-->
<script>
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function(e, ui) {
$('td.index', ui.item.parent()).each(function (i) {
$(this).text(i+1);
});
};
$("#myTable tbody").sortable({
distance: 5,
//delay: 100,
opacity: 0.6,
cursor: 'move',
helper: fixHelperModified,
update: function() {
var chArray = [];
$('.row_position>tr').each(function() {
chArray.push({
chid : $(this).attr("id"),
chnumber : $(this).closest('tr').find('td.index').text()
});
});
console.log(chArray);
// console.log(data);
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:chArray},
success:function(data){
console.log(data);
//alert('your change successfully saved');
},
error: function (error) {
// console.log(error);
}
})
},
stop: updateIndex
}).disableSelection();
</script>
</html>
ajaxPro.php
error_reporting(1);
require('db_config.php');
$data = $_POST['position'];
echo $data;
//$i=1;
foreach($data as $d){
echo $d['chnumber'];
$sql = "Update channels SET channel_number=".$d['chnumber']." WHERE id=".$d['chid'];
$mysqli->query($sql);
}
It's look good in browser everything is changed (if i move chanel from possition 4 to position 2 it's change on the screen to position 2, but in array chnumber is still 4, and i don't know how to change this.
Here is some pics.
1st order when you load page
Reorder when move channel from pos:4 to pos:2
And here is console log
I'm trying fill the table with fetched data from database by the id of selected option. Table content must change when user selects other option. Chosen plugin is working fine and select options is filled with correct values, how to give var selektas from test.php to loader.php in query where kliento_id = $idofclient?
Somehow make selektas == $idofclient so that i could use this variable in query in loader.php
My test.php:
<script type="text/javascript">
$(document).ready(function () {
$('.chosen-select').chosen();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
var selektas = $(this).val().split('|');
$.ajax({
type: "POST",
url: "loader.php",
data: {selektas[o]},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
</script>
<select class="chosen-select" name="pavname" id="pavadinimai">
<option selected="selected" value = "">---Pasirinkti---</option>
<?php
echo "Pasirinkite klienta";
$sql = "SELECT id, kliento_pav FROM klientai";
$stmt = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($stmt)) {
echo "<option value='" . $row['id'] .'|'. $row['kliento_pav'] . "'>" . $row['kliento_pav'] . "</option>";
}
list($idofclient,$pavofclient) = explode ('|',$_POST['pavname']);
?>
</select>
<div id="show">
</div>
And this is my code in loader.php
<?php
require_once "config.php";
if(isset($_POST["pavadinimas"])){
$sql_query="SELECT uzsakymai.id, kliento_id, uzsakymai.kiekis,prekes.pavadinimas,uzsakymai.aprasymas FROM uzsakymai INNER JOIN prekes ON uzsakymai.prekes_id = prekes.id INNER JOIN klientai on uzsakymai.kliento_id = klientai.id WHERE kliento_id = $idofclient"
$resultset = mysqli_query($link, $sql_query) or die("database error:". mysqli_error($link));
while( $result = mysqli_fetch_assoc($resultset) ) {
?>
<br>
<table id="data_table" class="table table-striped">
<thead>
<tr>
<th>Prekės pavadinimas</th>
<th>Kiekis</th>
<th>Aprašymas</th>
</tr>
</thead>
<tbody>
<tr id="<?php echo $result ['id']; ?>">
<td><?php echo $result ['pavadinimas']; ?></td>
<td><?php echo $result ['kiekis']; ?></td>
<td><?php echo $result ['aprasymas']; ?></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
echo $result
}
?>
I'm using ...jquery/3.1.1/jquery.min.js
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this.....
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
$.ajax({
type: "POST",
url: "loader.php",
data: {$idofclient},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
$(document).ready(function() {
$("#pavadinimai").on("change", function() {
var pavadinimai = $("#pavadinimai").val();
$.ajax({
type: "POST",
url: "loader.php",
data: {
pavadinimai: pavadinimai
},
success: function(result) {
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
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!');}
}
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();
}
?>
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();
}
?>