I have some data in MySQL database. I want to show that data in html table based on the parameter selected by the user.
Following is the input section (HTML)
<form class="form-inline">
<div class="input-group">
<div>Enter Person Name</div>
<input class="form-control" id="tags">
</div>
<div class="btn-group">
<button type="submit" id="btnSubmit">Search</button>
</div>
</form>
This is the table where I want to populate the data coming from AJAX response.
<div class="dataTable_wrapper">
<table class='table table-striped table-bordered table-hover' id='records_table'>
<tr class='odd gradeX'>
<th>Name</th>
<th>Group</th>
<th>Work</th>
<th>Grade1</th>
<th>Grade2</th>
<th>Grade3</th>
<th>TeacherName</th>
<th>RollNo</th>
</tr>
</table>
</div>
Now on clicking the 'Search' button, I want to send the name to PHP file, and get the information form database.
for which I have done this:
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var selText = $('#tags').val();
if (selText === '') {
alert("Please select a name!");
} else {
$.ajax({
type: 'GET',
url: 'getData.php',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
jsonp: false,
data: {
q: selText
},
success: function (response) {
alert(response);
var trHTML = '';
$.each(response, function (i, item) {
$.each(item, function (_, o) {
trHTML += '<tr><td>' + o.Name +
'</td><td>' + o.Group +
'</td><td>' + o.Work +
'</td><td>' + o.Grade1 +
'</td><td>' + o.Grade2 +
'</td><td>' + o.Grade3 +
'</td><td>' + o.TeacherName +
'</td><td>' + o.RollNo. +
'</td></tr>';
});
});
$('#records_table').append(trHTML);
},
error: function (e) {
$("#txtHint").html(e.responseText);
}
});
}
});
});
The PHP code is
<?php
$servername = "localhost"; $username = "root"; $password = "21343"; $dbname = "do_demob";
$selectedName = $_GET['q'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT *** Don't have rights to reveal";
$result = mysqli_query($conn, $sql);
$rows = array();
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
}else {
echo 'MySQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($conn);
?>
The AJAX response is
[{"Name":"Sagar Mujumbdar","Group":"","TeacherName":"John Cena","RollNo":"SX51998","Work":"Sales","Grade1":"Good","Grade2":"5","Grade3":"1"}]
the Status Code is:200 OK. I also checked in Developer Tools' Network section, the data is coming completely and in correct format. The key names are also correct.
But unfortunately the data is not being displayed in the table.
Is the reason that because JSON object contain null values it is not displaying?
If not, then what else can be the reason?
You have a syntax error right after RollNo:
'</td><td>' + o.RollNo. +
Remove the ..
In your iteration, you go one element to deep, o.* will be undefined, because o already is "Sagar Mujumbdar", "", etc. One .each is enough:
$.each(response, function (i, o) {
trHTML += '<tr><td>' + o.Name +
'</td><td>' + o.Group +
'</td><td>' + o.Work +
'</td><td>' + o.Grade1 +
'</td><td>' + o.Grade2 +
'</td><td>' + o.Grade3 +
'</td><td>' + o.TeacherName +
'</td><td>' + o.RollNo. +
'</td></tr>';
});
I also created a fiddle with your AJAX response.
Try following logic. There may some error like braces, and comma because i edited it in here. try the table heading is also in javascript. I done it below. Please check
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var selText = $('#tags').val();
if (selText === '') {
alert("Please select a name!");
} else {
$.ajax({
type: 'GET',
url: 'getData.php',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
jsonp: false,
data: {
q: selText
},
success: function (response) {
alert(response);
var trHTML = "<table class='table table-striped table-bordered table-hover' id='records_table'>
<tr class='odd gradeX'>
<th>Name</th>
<th>Group</th>
<th>Work</th>
<th>Grade1</th>
<th>Grade2</th>
<th>Grade3</th>
<th>TeacherName</th>
<th>RollNo</th>
</tr>";
for(var i =0;i < response.length-1;i++)
{
var o= response[i];
trHTML += '<tr><td>' + o.Name +
'</td><td>' + o.Group +
'</td><td>' + o.Work +
'</td><td>' + o.Grade1 +
'</td><td>' + o.Grade2 +
'</td><td>' + o.Grade3 +
'</td><td>' + o.TeacherName +
'</td><td>' + o.RollNo +
'</td></tr>';
}
trHTML+="</table>"
$('#records_table').append(trHTML);
},
error: function (e) {
$("#txtHint").html(e.responseText);
}
});
}
});
});
Related
custom.js file:
$(document).ready(function() {
$("#company_name").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
data: {
keyword: $("#company_name").val()
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.length > 0) {
$('#DropdownCompany').empty();
$('#company_name').attr("data-toggle", "dropdown");
$('#DropdownCompany').dropdown('toggle');
} else if (data.length == 0) {
$('#company_name').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCompany').append('<li role="displayCountries" ><a role="menuitem DropdownCompany" id=' + value['company_id'] + ' Address1=' + value['company_address1'] + ' Address2=' + value['company_address2'] + ' city=' + value['company_city'] + ' state=' + value['company_state'] + ' pincode=' + value['company_zip'] + ' class="dropdownlivalue">' +
value['company_name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#company_name').val($(this).text());
$('#company_id').val($(this).attr("id"));
// $('#company_address1').val($(this).text());
$('#tableCityID').html($(this).attr("id"));
$('#tableCityName').html($(this).text());
$('#Address1').html($(this).attr("Address1"));
$('#Address2').html($(this).attr("Address2"));
$('#city').html($(this).attr("city"));
$('#state').html($(this).attr("state"));
$('#pincode').html($(this).attr("pincode"));
});
});
I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '<span id="tableCityID">';
and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";
I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15
If anybody faces this problem, please help me. Thanks in advance.
just use the </span>
like this
$com = '<span id="tableCityID"></span>';
I want to print all sql table and show them in html table. I am new in php, JSON and AJAX. I send username successfully and get result in php. I think there is a problem in JSON part or AJAX. Can anyone help me?
index.php
<div class="col-lg-6">
<p id="usr" style="color:gray; font-size: 48px;"></p>
<script type="text/javascript">
var usr = document.getElementById("dom-target");
var username = usr.textContent;
username = username.trim().replace(/ /g, '%20');
document.getElementById("usr").innerHTML = username;
var sendtophp = "username="+username;
$.ajax({
type: "POST",
url: "getcoursetable.php",
data: sendtophp,
dataType:"json",
success: function(response) {
console.log(response);
var trhtml ='';
document.getElementById("demo").innerHTML = response;
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.cname + '</td><td>' + item.subject + '</td><td>' + item.course + '</td><td>'+ item.grade + '</td></tr>';
});
$('#results').append(trHTML);
}
});
</script>
<table id="results"></table>
</div>
getcoursetable.php
<?php
include_once "connection.php";
if(isset($_POST["username"])){
$nick = $_POST["username"];
$prep = "SELECT * FROM `enrolledtable` WHERE nickname='$nick'";
$results = mysqli_query($con, $prep);
$jsonData = array();
while ($row = $results->fetch_row()) {
$jsonData[] = $row;
}
echo json_encode($jsonData);
}
?>
Now, I can print data but not like a table, like that
<p id="demo">denemee,CS,300,B,denemee,CS,301,B ,denemee,CS,305,B ,denemee,CS,307,B,denemee,CS,408,A-,denemee,IE,208,B ,denemee,MATH,306,B</p>
your ajax function is looking for data of type json so you need to declare this at the top of getcoursetable.php
header('Content-Type: application/json');
The problem might sit around here :
console.log(response);
var trhtml ='';
document.getElementById("demo").innerHTML = response;
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.cname + '</td><td>' + item.subject + '</td><td>' + item.course + '</td><td>'+ item.grade + '</td></tr>';
});
$('#results').append(trHTML);
First, JavaScript is a Case Sensitive language : trhtml and trHTML are not the same variables.
Second, if your sentence "output of php" means you reported the output of console.log(), then response look like a string to me, you must make it parsed as Json.
Moreover, I don't know what the beginning of the string denemee is but it breaks the Json notation.
I solve my problem. This can take table in php and create html table.
index.php
<div class="col-lg-6">
<p id="usr" style="color:gray; font-size: 48px;"></p>
<script type="text/javascript">
var usr = document.getElementById("dom-target");
var username = usr.textContent;
username = username.trim().replace(/ /g, '%20');
document.getElementById("usr").innerHTML = username;
var sendtophp = "username="+username;
$.ajax({
type: "POST",
url: "getcoursetable.php",
data: sendtophp,
dataType:"json",
success: function(response) {
var trhtml ='';
$.each(response, function (i, item) {
trhtml += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td><td>'+ item[2] + '</td></tr>';
});
$('.append').append(trhtml);
}
});
</script>
<table id="results">
<tr>
<th>Name</th>
<th>Subject</th>
<th>Course</th>
<th>Grade</th>
</tr>
<tbody class="append">
</tbody>
</table>
</div>
getcoursetable.php
<?php
header('Content-Type: application/json');
include_once "connection.php";
if(isset($_POST["username"])){
$nick = $_POST["username"];
$prep = "SELECT subject,course,grade FROM `enrolledtable` WHERE nickname='$nick'";
$results = mysqli_query($con, $prep);
$jsonData = array();
while ($row = $results->fetch_row()) {
$jsonData[] = $row;
}
echo json_encode($jsonData);
}
?>
I have a php script that works correctly when executed directly:
The PHP:
<?php
header('Content-Type: application/json');
$fileName = "../appfiles/Courses.json";
if (file_exists($fileName))
{
$json = json_decode(file_get_contents($fileName), true);
echo json_encode($json);
}
else
{
echo "The file $fileName does not exist";
}
;
?>
Running
http://localhost/RickVideos/php/getRegCourses.php
, I get:
[{"coursecode":"ACCTD_001","cflag":"Y","pflag":"Y","dateregistered":"08\/11\/14","timeregistered":"12:55 pm."},{"coursecode":"LWPRG1_004","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:30 pm."},{"coursecode":"LWPRG2_005","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:32 pm."}]
Trying to run the php from jquery ajax, what returns seems to be the text of the script rather than the json data.
JavaScript:
// registered courses
var registeredCourses = {
init: function ()
{
$.ajax(
{
type: 'POST',
dataType: "JSON",
url: "php/getRegCourses.php",
}
)
.done(function(data)
{
$.each(data, function(index, element)
{
$('#registeredCourses').append(
$('<option value="' + index + '">' + this['coursecode'] + '</option>')
);
}
);
$('#registeredCourses').val('0');
$("#registeredCourses").trigger('chosen:updated');
registeredCourses.getSelected();
}
)
.fail (function(jqXHR, textStatus, errorThrown )
{
alert('request failed :'+errorThrown);
alert ('textStatus :'+textStatus);
console.log(jqXHR);
}
);
},
getSelected: function ()
{
$.ajax(
{
type: 'GET',
url: "getSelCourseInfo.php",
data:
{
course: $("#registeredCourses option:selected").text()
}
}
)
.done(function( data )
{
$("#courseCode").val($("#registeredCourses option:selected").text());
$("#courseTitle").val(data.Title);
$("#projectManager").val(data.ProjectManager);
$("#initRegDate").val (data.LastModDate + ' at ' + data.LastModTime);
var tasks = [ ];
$.each(data.ProjectTasks, function(i, item)
{
$("#projectTasks").append(
'<tr>' +
'<td>' + this + '</td>' +
'</tr>'
);
tasks[i] = this;
}
);
var projectMems = [ ];
$.each(data.ProjectMembers, function(i, item)
{
$("#projectMembers").append(
'<tr>' +
'<td>' + this.PersonName + '</td>' +
'<td>' + this.EmailAddress + '</td>' +
'</tr>'
);
projectMems[i] = this.PersonName;
}
);
$("#selectedCourseData").find("tr:gt(0)").remove();
$.each(data.Chapters, function(i, item)
{
$("#selectedCourseData").append(
'<tr>' +
'<td>' + this.label + '</td>' +
'<td>' + this.title + '</td>' +
'<td>' + registeredCourses.makeList('Sciptwriter1', i, projectMems, this.ScriptWriter) + '</td>' +
'<td>' + registeredCourses.makeList('Recorder1', i, projectMems, this.Recorder) + '</td>' +
'<td>' + registeredCourses.makeList('Status1', i, tasks, this.Status) + '</td>' +
'<td>' + registeredCourses.makeList('Assignedto1', i, projectMems, this.Assignedto) + '</td>' +
'</tr>'
);
}
);
}
);
},
makeList: function (cname, num, array, selected)
{
var string = '<select class="' + cname +'">';
if (selected== " " && array[0] != " ")
{
array.splice(0, 0, " ");
};
for (var i=0; i < array.length; i++)
{
if (array[i]==selected)
{
string = string + '<option value="' + array[i] + '" selected>' + array[i] + '</option>';
}
else
{
string = string + '<option value="' + array[i] + '">' + array[i] + '</option>';
};
};
string = string + '</select>';
return string;
}
};
The first alert shows:
request failed :SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The second alert shows:
textStatus :parsererror
And the response text for the jqXHR object shows:
"<?php header('Content-Type: application/json'); $fileName = "../appfiles/Courses.json"; if (file_exists($fileName)) { $json = json_decode(file_get_contents($fileName), true); echo json_encode($json); } else { echo "The file $fileName does not exist"; } ; ?> "
Why is the text of the script showing rather than the json data?
Not sure if this helps or not but the following code works for me. Set up a directory with your json, your php, and an html file for basically just populating the select menu. This works fine for me and when taking a look at your code there were some js errors:
$('<option value="' + index + '">' + this['coursecode'] +/option>') is missing the '< before the option close tag
Also missing a } after you ) at the end of fail. After fixing those files your code worked for me as far as populating the dropdown, though you get js errors because registeredCourses.getSelected(); doesn't exist. Which makes me wonder if the above code is complete?
If all that doesn't help then have you looked at teh raw html that is output when you go directly to your php file, like viewing the source?
`bonk.php`
<?php
header('Content-Type: application/json');
$fileName = "courses.json";
if (file_exists($fileName))
{
$json = json_decode(file_get_contents($fileName), true);
echo json_encode($json);
}
else
{
echo "The file $fileName does not exist";
}
;
?>
`courses.json`
[
{
"coursecode": "ACCTD_001",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/11/14",
"timeregistered": "12:55 pm."
},
{
"coursecode": "LWPRG1_004",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/18/14",
"timeregistered": "3:30 pm."
},
{
"coursecode": "LWPRG2_005",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/18/14",
"timeregistered": "3:32 pm."
}
]
`html file`
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var registeredCourses = {
init: function (){
$.ajax ({
type: 'GET',
dataType: "JSON",
url: "bonk.php",
})
.done(function(data){
$.each(data, function(index, element){
$('#registeredCourses')
.append($("<option></option>")
.attr("value",index)
.text(this['coursecode']));
});
})
.fail (function(jqXHR, textStatus, errorThrown){
console.log(errorThrown, textStatus, jqXHR);
})
}
};
registeredCourses.init();
</script>
</head>
<body>
<select name="test" id="registeredCourses"></select>
</body>
</html>
I coverted both the php file and the Courses.json file to utf-8 and it now runs.
I am using jQuery (1.9.1) with jQuery Mobile (1.3.0). I am having trouble with the Reflow table in JQM. When I AJAX to get my JSON data from a script to add more rows to my table, the reflow table headings are not generated after I trigger a refresh and create on the table. Here is my code:
HTML/PHP
'<table data-role="table" id="itemTable" data-mode="reflow" class="ui-responsive table-stroke" style="display:table;">' .
'<thead>' .
'<tr>' .
'<th data-priority="1">Location</th>' .
'<th>Name</th>' .
'<th data-priority="3">Barcode</th>' .
'<th data-priority="4">Needed</th>' .
'<th data-priority="5">Scanned</th>' .
'</tr>' .
'</thead>' .
'<tbody>' .
$tableData .
'</tbody>' .
'</table>' .
JavaScript
$('.getOrder, .getStoreOrder').on('vclick', function(e) {
e.preventDefault();
var sel = this;
var theLink = $(this).attr('href');
if (activeOrder === true) {
return false;
}
$.ajax({
url: 'ajax.php',
data: {
pa: ($(sel).hasClass('getStoreOrder') ? 'store' : '') + 'order'
},
dataType: 'json',
beforeSend: function() {
$.mobile.showPageLoadingMsg();
$('#itemTable tbody').html('');
$('#leftPanel ul li').not(':first-child').remove();
},
success: function(data) {
testVar = data;
var i;
for (i=0; i <= data.length -1; i++) {
$('#itemTable tbody').append( '' +
'<tr id="item' + (i+1) + '">' +
'<td><span>' + data[i].Location + '</span></td>' +
'<td><a onclick="showImageOverlay(\'' + data[i].Image + '\');">' + data[i].Name + '</a></td>' +
'<td>' + data[i].Barcode + '</td>' +
'<td>' + data[i].Qty + '</td>' +
'<td>0</td>' +
'</tr>' +
'');
$('#leftPanel ul').append( '' +
'<li>' +
'<a href="#item' + (i+1) + '" class="itemLink" onclick="changeItem(\'item' + (i+1) + '\')">' +
'Item ' + (i+1) +
'</a>' +
'</li>' +
'');
}
$('#itemTable').trigger('refresh');
$('#itemTable').trigger('create');
$('#leftPanel #leftUl').listview('refresh');
},
complete: function() {
$('#rightPanel', '.ui-page-active').panel('close');
$.mobile.hidePageLoadingMsg();
//pageChange(theLink);
}
});
});
The AJAX does succeed and add my rows to the table how I want them to. My question is how do I trigger JQM to add the reflow column names.
I know that I can use <b class="ui-table-cell-label">Column Name</b> to my row appends to add the column names but I want it done dynamically so I don't have to change the jQuery when I change my HTML.
Thank you.
In my opinion its preferable to do like this: $('#tableContainer').load('revisedTable.php?json=yourJsonString');
That way you're doing the table layout in php rather than javascript.
Figured it out. Turns out that jQuery Mobile version 1.3.0 does not have a proper .table('refresh') method implemented. I solved this by upgrading to jQuery Mobile version 1.3.1 which has the proper method I needed.
I have a form that will contain a html table which allows users can add or delete rows from it. That will works fine .
/*add row*/
function add_Items(itemtypeid, itemid, reqqty) {
var mode = 1;
var pstSettings = {
url: 'ajax_Items/' + itemid + '/' + mode
callback: function (data) {
var dyntd = "";
var hidval = "";
var $response = $(data);
var resitmname = $response.filter('#Item_Name').text();
var resitmdesc = $response.filter('#Item_Descrip').text();
dyntd = "<td><label>" + itemid + "</label></td>";
dyntd += "<td><label>" + resitmname + "</label></td>";
dyntd += "<td><label>" + resitmdesc + "</label></td>";
dyntd += "<td><label>" + reqqty + "</label></td>";
hidval += '<input type="hidden" name="itemid" value=' + itemid + ' />';
hidval += '<input type="hidden" name="reqitem" value=' + reqqty + ' />';
dyntd += '<td>' + hidval + '<input type="button" name="min" class="minus" value="-" />';
$('.item-result-table tr:last').after('<tr>' + dyntd + '</tr>');
}
};
post_Call(pstSettings);
}
}
/* delete row */
$(document).ready(function () {
$('.item-result-table').delegate('.minus', 'click', function (e) {
$(this).parent().parent().remove();
});
});
But now my problem is how to submit the html table in a form, because of all are html tags not input type tags . I have added a hidden tag . But it also creates problem that it only takes the first element , others are ignored. Is any other method existing to submit this html table data?
The reason you are only getting one input is because you defined it wrong, you need to define it as array:
<input type="hidden" name="itemid[]" value=' + itemid + ' />
<input type="hidden" name="reqitem[]" value=' + reqqty + ' />'
and then in PHP:
$_POST['itemid'][0];
I think that you could use the $.ajax jquery function. You can serialize all your inputs in the form like this:
$("#btn_submit").on('click', function() {
$.ajax({
url: $(this).closest("#div_content").find("#form").attr( 'action' ),
type: 'post',
data: $(this).closest("#div_content").find("#form").serialize(),
}).done( function(msg) {
//console.log("ok");
}).fail( function(jqXHR, textStatus) {
//console.log("fail");
});
});
With the "serialize" you can send all the variables and on the controller you can read the variables with $_POST and the name of the input.