I have the following problem when I want to visualize data in the famous Datatable library using a Store Procedure made in SQLServer, I use the Store Procedure to display my information in the table, the problem is that my data is not being reflected in the table, so this I use PHP and AJAX.
To see the information in my Datatable I use its API to attach secondary rows better known as Child Rows, the following is the AJAX code with which I build my table and its parameters:
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Currency</td>'+
'<td>'+d.Currency+'</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table = $('#example').DataTable( {
// "processing": true,
"serverSide": true,
"ajax": {
url :"../utileria.php",
type: "POST",
data: {
param: 1,
},
},
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data" : "Order_Buy" },
{ "data" : "Currency" },
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
It is important to note that my parent row will contain the Order_Buy field and my child row the Currency field
The following is my PHP code where I call my Stored Procedure and the class conectar.php
utileria.php
<?php
header('Content-Type: text/html; charset=utf-8');
$param = $_POST['param'];
switch($param) {
case '1':
$query = array();
include 'conectar.php';
$sql = "{call SPTest(?)}";
$stmt = sqlsrv_query($conn, $sql);
if ( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
$record = array(
"F.ORDER" => utf8_encode ($row['Order_Buy']), //Orden de compra
"F.CURRENCY" => utf8_encode ($row['Currency']), //Moneda
);
array_push($query, $record);
}
echo json_encode($query);
sqlsrv_free_stmt( $stmt);
sqlsrv_close($conn);
break;
}
?>
I do not know why my table does not show me data, it could be that I have something wrong in any of my codes.
If it helps to give a better clarity of the question I attach the HTML code with which I generate my Datatables table.
!doctype html>
<html lang="es">
<head>
<title></title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="libraries/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="libraries/css/estilos.css" type="text/css">
<script src="libraries/js/jquery-1.12.3.min.js"></script>
<script src="javascript/Example.js"></script>
<link href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<link rel="icon" type="image/png" href="libraries/img/icon.png" />
</head>
<body>
<div class="cuerpo">
<div class="dividir menu">
<div class="centrar-vertical">
<img src="libraries/img/logo.jpg" width="200" height="40" alt="Test" class="img-responsive">
</div>
<div class="alinear-derecha centrar-vertical">
<button id="logout-btn" class="btn btn-default">Cerrar SesiĆ³n</button>
</div>
</div>
<div id="tablaDatatable">
<table id="example" class="display" width="100%">
<thead>
<tr>
<th></th>
<th>Order_Buy</th>
<th>Currency</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
I have written a js datagrid as I was not happy with any of the available sources, just try it if you are after a data tables Hope it benefit you.
JS Datargid on github
cheers
Related
I've tried the other solutions but been unable to make it work.
How do I make each row of DataTables a hyperlink to its ENSG ID?
I've tried to do it outside the Ajax interface.
<!DOCTYPE html>
<html>
<title>Datatable Demo1 | CoderExample</title>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dataTable = $('#gene-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"gene-grid-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".gene-grid-error").html("");
$("#gene-grid").append('<tbody class="gene-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#gene-grid_processing").css("display","none");
}
}
} );
} );
</script>
</head>
<body>
<div class="container">
<table id="gene-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>ENSG ID</th>
<th>Gene</th>
<th>Biotype</th>
</tr>
</thead>
</table>
</div>
</body>
I would store the id of the row in a data attribute and then write a click handler to do this... Just remember though, datatables creates dynamic html so if setting a click event for something that is getting destroyed and redrawn, you will need to attach the handler to a parent element. I usually use the body element.
//add this option to datatables initialization
//this will add a data attribute containing the id
//to each row in table.
"rowCallback": function( row, data ) {
$(row).data('id',data.ID);
}
//handler to redirect to detail page...
$('body').on('click', 'tr', function(){
window.location = "http://svr/app/controller/action/" + $(this).data('id');
});
I need datatable to be implemented in my project. I wanna show total number at the bottom of the table like below:
I already make default data table like this :
This is my code.
<?php
include "db.php";
$obj->tglan=$obj->get_hari();
if (isset($_POST['tanggal2'])) {
$obj->tglan = $_POST['tanggal2'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="assets/DataTables/media/js/jquery.js"></script>
<script type="text/javascript" src="assets/DataTables/media/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/dataTables.bootstrap.css">
<link rel="stylesheet" href="assets/css/bootstrap.min.css"/>
<link rel="stylesheet" href="assets/datepicker/css/bootstrap-datepicker3.css"/>
</head>
<body>
<center>
<h3>Daftar SPTA<br><?php echo $obj->tanggal("D, j M Y",$obj->tglan);?></h3>
</center>
<left>
<h5>   Last refreshed : <?php echo $obj->tanggal("D, j M Y",$obj->tglan)." ".date("H:i:s");?></h5>
</left>
<br/>
<form action="viewLaporanUtama2.php" method="POST">
<div class="form-group" >
<label for="tanggal">   Tanggal</label>
<input type="text" name="tanggal1" class="tanggal" id="myText" required/>
<input type="submit" name="enter" value="Cari" class="btn btn-info btn-sm">
</div>
</form>
<div class="container-fluid">
<div class="table-responsive">
<table border = '0' class="table table-striped table-bordered data" id="tabelSpta">
<thead>
<tr>
<th>No</th>
<th>No SPTA</th>
<th>No Register Induk</th>
<th>Nama Petani</th>
<th>Gawang/Pos</th>
<th>Timbang Bruto</th>
<th>Giling</th>
<th>Timbang Tarra</th>
<th>Netto(kw)</th>
<th>Kode Rafraksi</th>
<th>Potongan (kw)</th>
<th>Netto Akhir (kw)</th>
</tr>
</thead>
<tbody>
<div id="bagReload">
<?php
echo $obj->tampilLaporan();
?>
</div>
</tbody>
</table>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
var tabel = $('.data').DataTable();
});
</script>
<!-- <script src="js/jquery-3.2.1.min.js"></script> -->
<script src="assets/js/bootstrap.js"></script>
<script src="assets/datepicker/js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.tanggal').datepicker({
format: "yyyy-mm-dd",
autoclose:true
});
});
</script>
</html>
I've already searched but, there's few reference but I couldn't understand that
How I can add Total cell and show at the bottom of datatable?
See this example here http://jsbin.com/putiyep/edit?js,output written by bindrid.
http://jsbin.com/putiyep/edit?js,output
Basically it leverages the footerCallback of the API and use the column index of the table and basic math to return your total.
Excerpt of the code (again not my code):
// Table definition
var dtapi = $('#example').DataTable({
data: dataSet,
pageLength: 3,
"deferRender": false,
"footerCallback": function (tfoot, data, start, end, display) {
var api = this.api();
var p = api.column(4).data().reduce(function (a, b) {
return a + b;
}, 0)
$(api.column(4).footer()).html(p);
$("#total").val(p);
},
"order": [1],
"columns": [
// rest of the columns
{ data: "first_name" },
{ data: "last_name" },
{ data: "firstNumber" },
{
data: "secondNumber", render: function (data) {
return '<input type="text" style="width:50px" value="' + data + '">';
}
},
{ data: "rowTotal" }
]
});
I am connected to mysql database and I want to generate table with content from mysql with php after clicking on a button by a user.
But after clicking on a button, the whole page with header, body, etc. is generated to div where are table and php script. The button also duplicate visually of course.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-2">
<meta http-equiv="content-language" content="cs">
<meta name="author" content="Marek Ciz, Tomas Veskrna">
<meta name="keywords" content="galerie, iis, iis projekt 2016, informacni system">
<link rel="icon" type="image/png" href="./icons/gallery.png" />
<title>Employee</title>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#expo-but").click(function(){
$.ajax({
url: "./employee.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});
</script>
</head>
<body>
<div class="page">
<div class="menu">
<button id="expo-but">Exposition</button>
</div>
<div id="table-wrapper">
<div id="table">
<table class="striped">
<thead>
<tr class="header">
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
More correct solution will be separate html and php part:-
Your html should be like this:-
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-2">
<meta http-equiv="content-language" content="cs">
<meta name="author" content="Marek Ciz, Tomas Veskrna">
<meta name="keywords" content="galerie, iis, iis projekt 2016, informacni system">
<link rel="icon" type="image/png" href="./icons/gallery.png" />
<title>Employee</title>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(#expo-but).trigger("click"); // on document ready trigger click itself so that table will load initially
$("#expo-but").click(function(){
$.ajax({
url: "./employee.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});
</script>
</head>
<body>
<div class="page">
<div class="menu">
<button id="expo-but">Exposition</button>
</div>
<div id="table-wrapper">
<div id="table">
</div>
</div>
</div>
</body>
</html>
And php(employee.php) will be like this:-
<?php
include './db_init.php';
//echo $_SESSION["user"];
$data = '';
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$data .= "<tr>";
$data .="<td>".$row[id_zamestnance]."</td>";
$data .="<td>".$row[jmeno]."</td>";
}
}
}
$final_data = '<table class="striped"><thead><tr class="header"><td>Id</td><td>Name</td></tr></thead><tbody>'.$data.'</tbody></table>';
echo $final_data;
?>
Note:-
Why i am saying more correct because in your php page you also have same code what you written in your current html div, so no need to do the repetition.
Just on document load call the click function of button ,that's it.
cut this code and add this code to top of the page
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
exit();
}
?>
this is a normal mistake most of us do, I suggest you to request to another php page instead requesting the same page.
table.php
<table class="striped">
<thead>
<tr class="header">
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
}
?>
</tbody>
</table>
and change the url in the scrtipt
<script>
$(document).ready(function(){
$("#expo-but").click(function(){
$.ajax({
url: "./table.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});
Update This is a complete update to my question
<!doctype html>
<html>
<meta charset="utf-8">
<meta name="author" content="Amsul - http://amsul.ca">
<meta name="viewport" content="width=device-width,user-scalable=no">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Pickadate.js</title>
<link rel="stylesheet" href="../../lib/themes/default.css">
<link rel="stylesheet" href="../../lib/themes/default.date.css">
<link rel="stylesheet" href="../../lib/themes/default.time.css">
<!--[if lt IE 9]>
<script>document.createElement('section')</script>
<style type="text/css">
.holder {
position: relative;
z-index: 10000;
}
.datepicker {
display: block;
}
</style>
<![endif]-->
<body>
<?php
require 'connect-db.php';
try{
$stmt = $db->query("SELECT ddate FROM testdates");
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}catch(\PDOException $e){
echo $e->getMessage();
}
$json_array = json_encode($result)
?>
<section class="section">
<form>
<fieldset>
<h3><label for="datepicker_id">Pick a date.</label></h3>
<input
id="datepicker_id"
class="datepicker"
name="date"
type="text"
value=""
data-value="">
<br><br><br><br><br>
<h3><label for="timepicker_id">Pick a time</label></h3>
<input
id="timepicker_id"
class="timepicker"
value=""
type="time"
name="time">
<!-- valuee="2:30 AM"
data-value="0:00" -->
<!-- <button type="button">Disable all dates</button>
<input class="button" type="submit" value="open"> -->
</fieldset>
</form>
<div id="container"></div>
</section>
<script src="../jquery.1.9.1.js"></script>
<script src="../../lib/picker.js"></script>
<script src="../../lib/picker.date.js"></script>
<script src="../../lib/picker.time.js"></script>
<script src="../../lib/legacy.js"></script>
<script type="text/javascript">
//datepicker
var disdates = <?php echo $json_array; ?>
var $input = $( '.datepicker' ).pickadate({
formatSubmit: 'yyyy/mm/dd',
min: true,
container: '#container',
// editable: true,
closeOnSelect: true,
closeOnClear: false,
disable: [ disdates
]
})
var picker = $input.pickadate('picker')
// picker.set('select', '14 October, 2014')
// picker.open()
// $('button').on('click', function() {
// picker.set('disable', true);
// });
</script>
<script type="text/javascript">
//timepicker
var dtimes = new Date(2015,11,28,5,30);
var $timeinput = $( '.timepicker' ).pickatime({
disable: [
[2,0],
dtimes
]
})
var timepicker = $timeinput.pickatime('picker')
</script>
</body>
</html> // i must thank users in php chatroom for helping me fix the errors.
That above, is a page where you see a calendar, and some dates are disabled, which are fetched from the database. I'm using this picker
disable: [
[2015,29,9], // disables today strangely month -1 and only accepts yyy,mm,dd
[some other array]
]
})
In my databese 'ddate' is varchar, no primary key, no unique id, nothing, containing
2015,9,30
2015,9,31
2015,10,30
the values aren't being passed or something from mysql to javascript or something, and i guess i want multidimentional array.
what i want the javascript array to have is month -1 because as I explained above, in disable option to disable this day, you have to enter last month number. and if first month, means 12.
Note I want to use the same for timepicker but I guess I could do on my own if I understand the issue with calendar
I assume, that your db content is:
ddate: varchar()
Values stored in table testdates (as strings):
2015-10-29
2015-10-15
2015-10-10
Select is still as is plus create a string for array build to js
try{
$stmt = $db->query("SELECT ddate FROM testdates");
$db_ddates = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$js_ddates = "";
foreach ($db_ddates as $row => $record) {
$js_ddates .= '"' . $record['ddate'] . '",';
}
}
catch(\PDOException $e) {
echo $e->getMessage();
}
Now use that inside building the script part
// take dates as array of strings from db
var ddates_str_arr = [ <?php echo $js_ddates; ?> ];
// build dates array for picker
var disdates = [];
for (var i = 0; i < ddates_str_arr.length; i++) {
disdates.push(new Date(ddates_str_arr[i]));
}
// just use it in picker
var $input = $( '.datepicker' ).pickadate({
formatSubmit: 'yyyy/mm/dd',
min: true,
container: '#container',
// editable: true,
closeOnSelect: true,
closeOnClear: false,
disable: disdates
});
ATTENTION: I have not test it but just write those lines from mind. There may some typing erratas but should work in general.
UPDATE:
Not sure about picker but give this a try too instead of the above script part
// just use it in picker
var $input = $( '.datepicker' ).pickadate({
formatSubmit: 'yyyy/mm/dd',
min: true,
container: '#container',
// editable: true,
closeOnSelect: true,
closeOnClear: false,
disable: [ <?php echo $js_ddates; ?> ]
});
Just simple,
I am trying to access the variable in javascript inside the php while working with elrte,
bleow is my index.php file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>One textarea with elRTE and file upload plus one text field with elFinder</title>
<!-- jQuery and jQuery UI -->
<script src="js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-ui-1.8.7.custom.min.js" type="text/javascript" charset="utf- 8"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.7.custom.css" type="text/css" media="screen" charset="utf-8">
<!-- elRTE -->
<script src="js/elrte.min.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/elrte.min.css" type="text/css" media="screen" charset="utf-8">
<link rel="stylesheet" href="css/elrte.full.css" type="text/css" media="screen" charset="utf-8">
<!-- elFinder -->
<link rel="stylesheet" href="css/elfinder.css" type="text/css" media="screen" charset="utf-8" />
<script src="js/elfinder.full.js" type="text/javascript" charset="utf-8"></script>
<!-- elRTE and elFinder translation messages -->
<!--<script src="js/i18n/elrte.ru.js" type="text/javascript" charset="utf-8"></script>
<script src="js/i18n/elfinder.ru.js" type="text/javascript" charset="utf-8"></script>-->
<script type="text/javascript" charset="utf-8">
// elRTE with elFinder on a textarea
$().ready(function() {
var opts = {
cssClass : 'el-rte',
lang : 'en', // Set your language
allowSource : 1,
height : 450,
toolbar : 'maxi', // 'tiny', 'compact', 'normal', 'complete', 'maxi', or 'custom' (see advanced documentation for 'custom')
cssfiles : ['css/elrte-inner.css'],
fmAllow : 1,
fmOpen : function(callback) {
$('<div id="myelfinder" />').elfinder({
url : 'connectors/php/connector.php',
places : '',
lang : 'en', // Set your language
dialog : { width : 900, modal : true, title : 'Files' }, // Open in dialog window
closeOnEditorCallback : true, // Close after file select
editorCallback : callback // Pass callback to file manager
})
}
}
$('#editor').elrte(opts);
// Text field with elFinder
var opt = {
url : 'connectors/php/connector.php',
places : '',
lang : 'en',
editorCallback : function(url) {document.getElementById('field').value=url;}, // The id of the field we want elfinder to return a value to.
closeOnEditorCallback : true,
docked : false,
dialog : { title : 'File Manager', height: 500 },
}
$('#open').click(function() { // The id of the button that opens elfinder
$('#finder').elfinder(opt) // The id of the div that elfinder will open in
$('#finder').elfinder($(this).attr('id')); // it also has to be entered here.
})
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
});
})
})
</script>
</head>
<body>
<?php
$q=mysql_query("select * from aw_about_us")or die(mysql_error());
$r=mysql_fetch_array($q);
extract($r);
?>
<div id="finder"></div>
<table cellpadding="5" cellspacing="5" border="0" width="100%">
<form name="feedback" id="frm" method="post">
<tr>
<td>Title : </td>
<td><input type="text" id="atitle" size="75" value="<?=$abt_title?>"></td>
</tr>
<tr>
<td>Tag Line : </td>
<td><input type="text" id="atag" size="75" value="<?=$abt_small_line?>"></td>
</tr>
<tr>
<td colspan="2"><textarea id="editor" id="acontent" cols="50" rows="4">
<?=$abt_content?>
</textarea></td>
</tr>
<!--<input type="text" id="field" name="field" size="60"/> -->
<!--<input type="button" id="open" value="Browse..." /><br>-->
<tr>
<td><input type="submit" id="btnsub" value="Submit"></td>
</tr>
</form>
</table>
<?php
/*echo $_GET['val'];
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
*/?>
</body>
</html>
I am able to get the value of elrte inside the javascript variable, but now I wanted store this value inside the mysql database, as I am using PHP I want to access this value inside a php so that I can store it in database,
I tried using window.open("abc.php?val="+content); but the value is very large so get method cannot be acceptable here, so is there any way to get this value inside the php? or any alternate way to do this?
** Edit :**
Now it gives me a value of content variable after making following changes, but I want all 3 variables, but unable to get
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
var title = document.getElementById('atitle').val;
var tag = document.getElementById('atag').val;
alert('title'+title);
$.ajax({
type: "POST",
url: 'abc.php',
data: {title : title, tag : tag, content : content},
success: function(html) { $('result').append(html); },
dataType: 'html'
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and php file
<?php
include('inc/conn.php');
if(isset($_POST['updabt']))
{
$cont=$_POST['updabt'];
$q1=mysql_query("update aw_about_us set abt_title='$title', abt_small_line='$tag', abt_content='$cont'") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
Now how to get all three variables??
You'll need to submit the value to your PHP script using a POST request to your server. You can do this with Ajax requests, and I believe jQuery has built-in methods for Ajax which are cross-browser.
You need 2 pages, one which will send AJAX (this you have) and one wich will respond (below):
<?php
///ajax.php
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
In javascript you create AJAX post
data['updabt'] = '';
$.ajax({
type: "POST",
url: 'ajax.php',
data: data,
success: function(html) { $('result').append(html); },
dataType: 'html'
});
You can use AJAX (easiest with a library such as jQuery) to submit the variables to another PHP script that will INSERT the values to your database.
Start by reading the following...
jQuery.ajax
jQuery.post
This is actually very simple once you get your head around the subtleties of AJAX.
Here is a simple example to get you off and running. Suppose you wanted to log something to your PHP error log...
This would be my JavaScript function:
var log = function(val) {
$.post("ajax.php", {"mode": 'log', "val": val}, function() {});
}
ajax.php would be a collection of functions, ideally a class...
public function __construct() {
$arrArgs = empty($_GET)?$_POST:$_GET;
/**
* using 'mode' I can send the AJAX request to the right method,
* and therefore have any number of calls using the same class
*/
if (array_key_exists('mode', $arrArgs)) {
$strMethod = $arrArgs['mode'];
unset($arrArgs['mode']);
$this->$strMethod($arrArgs);
}
}
protected function log($arrArgs) {
error_log($arrArgs['val']);
}
The same idea can easily be adapted to write data to a database.