I'm trying fetch data count from database to HTML div using PHP, jQuery and AJAX, but code below is not working.
I just started learning ajax please help. Thank you!
index.php
<div class='col-lg-3 col-md-6'>
<div class='panel panel-primary'>
<div class='panel-heading'>
<div class='row'>
<div class='col-xs-3'>
<i class='fa fa-microphone fa-5x'></i>
</div>
<div class='col-xs-9 text-right'>
<!-- here i want to fetch result -->
<div id="leadmonth"></div>
<div>Total Leads</div>
</div>
</div>
</div>
</div>
</div>
Jquery
$(document).ready(function() {
$.ajax({
type:'POST',
url:'php_action/resourceqareportdashboardcount.php',
dataType : 'json',
success:function(html){
$('#leadmonth').html(html);
}
});
PHP
<?php
// This Month Count
require_once 'db_config.php';
$output= '';
$sql = "SELECT * FROM leads WHERE YEAR(leadcreationdate) = YEAR(NOW()) AND MONTH(leadcreationdate)=MONTH(NOW())";
$query = $connect->query($sql);
$totalleads = mysqli_num_rows($query);
if ($monthtotalleadscount > "0") {
$output = "<div class='huge'>$totalleads</div>";
} else {
$output = "<div class='huge'>0</div>";
}
// database connection close
$connect->close();
echo json_encode($output);
$(document).ready(function() {
$.ajax({
type:'POST',
url:'php_action/resourceqareportdashboardcount.php',
// dataType : 'json',
success:function(html){
$('#totalleadsmonth').html(html);
}
});
});
Related
I used this ajax PHP code for lazy load and filter according to category, i want to combine both of them because lazy load works on first load but doesnt work with category buttons.
My AJAX code sends limit and start values to fetch.php and fetch data in the division
A 2nd ajax code sends cat_id to load-prod.php to filter data on button click
index.php
<div class="row">
<div class="col-md-12 p-3 text-center">
<span>Categories  </span>
<div class="btn-group" role="group" aria-label="Basic outlined example">
<button type="button" class="btn btn-outline-dark active showct" value="">All</button>
<?php echo show_cat(); ?>
</div>
</div>
<div class="col-md-12">
<div class="row row-cols-1 row-cols-md-3 g-4" id="showpr">
</div>
</div>
<div class="col-md-12 text-center p-3" id="datamsg"></div>
</div>
//lazy load
<script>
var limit = 9; //The number of records to display per request
var start = 0; //The starting pointer of the data
var action = 'inactive'; //Check if current action is going on or not. If not then inactive otherwise active
function lazyload(limit, start)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
$('#showpr').append(data);
if(data == '')
{
$('#datamsg').html("<button type='button' class='btn btn-dark' disabled>No more data</button>");
action = 'active';
}
else
{
$('#datamsg').html("<button type='button' class='btn btn-outline-dark' disabled>Loading More...</button>");
action = 'inactive';
} }});}
if(action == 'inactive')
{
action = 'active';
lazyload(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $(document).height() - 100 && action== "inactive")
{
action = 'active';
start = start + limit;
setTimeout(function(){
lazyload(limit, start);
}, 1000);}});
</script>
//show according to category
<script>
$(document).ready(function(){
$('.showct').click(function(){
var cat_id = $(this).val();
$.ajax({
url:"load-prod.php",
method:"POST",
data:{cat_id:cat_id},
success:function(data){
$("#showpr").html(data);
}});
});});
</script>
load-prod.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["cat_id"]))
{
if($_POST["cat_id"]!='')
{
$cf = "select * from products where c_id = '".$_POST['cat_id']."'";
}
else{
$cf = "select * from products";
}
$filter = mysqli_query($con,$cf);
while ($ctf=mysqli_fetch_array($filter)) {
echo "<div class='col-12'><h5 class='card-title'>".$ctf['name']."</h5>";
}
}
?>
fetch.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["limit"], $_POST["start"]))
{
$query = "SELECT * FROM album ORDER BY id ASC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<div class='col-12'><h5 class='card-title'>".$row['name']."</h5>" ;
}
}?>
I was watching tutorial on how to display MySQL data in dynamic window then I realized its not for laravel i hope there is a why to use it on laravel.
jQuery / AJAX :
<script>
$(document).ready(function(){
$('.view_data').click(function(){
var student_id = $($this).attr("id");
$.ajax({
url:select.php,
method:"post",
data:{student_id:student_id},
success:function(data){
$('student_detail').html(data);
$('#dataModal').modal("show");
}
});
});
});
</script>
the window shows up when the script has only this line: $('#dataModal').modal("show"); so script works when its like this but does not show any data.
<script>
$(document).ready(function(){
$('.view_data').click(function(){
var student_id = $($this).attr("id");
$('#dataModal').modal("show");
});
});
</script>
url:select.php
<?php
if(isset($_POST["student_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "sms");
$query = "SELECT * FROM students WHERE id = '".$_POST["student_id"]."'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td width="30%"><label>first name</label></td>
<td width="70%">'.$row["firstName"].'</td>
</tr>
';
}
$output .= "</table></div>";
echo $output;
}
?>
I have more data columns but im using firstName for now
and this is the window model that shows up :-
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body" id="student_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Try this
<script>
$(document).ready(function(){
$('.view_data').click(function(){
var student_id = $(this).attr("id");// also here $this will be not defined
$.ajax({
url:select.php,
method:"post",
data:{student_id:student_id},
success:function(data){
$('#student_detail').html(data);//selector are not valid you are missing to add # at the beginning
$('#dataModal').modal("show");
}
});
});
});
</script>
You should do a test first, check (I don't know if you did this already or not) if the PHP script actually returns some data. You can do an ajax call and display the response in the console.
I am developing a page in php that has multiple dynamic modals for displaying pdf files in the page itself with respective title and author names. All the data comes from a database designed in MySQL. The trigger buttons are also meant to be dynamic. I have tried the following code. The problem is I am getting the modals blank. I am able to print the data in fetch-reader.php page itself. I think I am doing something wrong in AJAX or modal part. Please guide me through it.
<?php $sqlGal = "select * from articles where year = '2019'";
$queryGal = $con->query($sqlGal);
if ($queryGal->num_rows > 0) {
while ($row = $queryGal->fetch_array()) { ?>
<div class="col-md-3 gallery-grid">
<h3 style="height: 200px; vertical-align: bottom; margin: 0; display: table-cell;"><?php echo($row['title']) ?></h3>
by<h4><?php echo($row['name']) ?></h4>
<i class="fa fas fa-book-open"></i> Read
</div>
<?php }
}
?><div class="clearfix"></div>
<div class="modal fade" id="myReader" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 id="articleName"></h3>
<h4 id="name"></h4>
<h6 id="position"></h6>
<h6 id="address"></h6>
</div>
<div class="modal-body">
<object data="" id="reader" width="100%" height="450px"></object></div>
</div>
</div>
</div>
</div>
in <script> part
$(document).ready(function() {
$('#myReader').on('show.bs.modal', function(e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type: 'get',
url: 'include/fetch_reader.php',
data: 'rowid='+rowid,
dataType: 'json',
success : function(response) {
$('#articleName').text(response.title);
$('#name').text(response.name);
$('#position').text(response.position);
$('#address').text(response.address);
var add = "uploads/articles/" + response.yearSl + ".pdf";
$('#reader').prop('data', add);
}
});
});
});
in fetch-reader.php
<?php
require_once('connect.php');
if ($_GET['rowid']) {
$id = $_GET['rowid'];
$sql = "SELECT `title`, `name`, `position`, `address`, `yearSl` FROM articles WHERE `id` = '".$id."'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array();
}
$connect->close();
header('Content-Type: application/json');
echo json_encode($row);
}
Please guide me any other way which can serve my purpose, but I don't want to use any third-party tools for the purpose.
I think you are sending the wrong data in ajax. Try this into your "$ .ajax" call:
data: { 'rowid': rowid }
And try checking into browse console if the request shows any error. Into your ajax call you check only for success return, not for fail.
I have a page using bootstrap 3 framework that has a button which when pressed collects data from another page (mydata.php) with ajax and echoes it out within <div id="results"> on the page. The code works fine but as soon as I add <div class=\"col-xs-6\"> to mydata.php nothing appears on the page although I can see it within firebug.
If I change $("#results").append(html); to $("#results").text(html); the html echoes onto the page but as text without any formatting. If I remove <div class=\"col-xs-6\"> from mypage.php the data gets displayed on the page as expected. Why is the data from mydata.php not displayed when I add <div class=\"col-xs-6\">?
<div class="container">
<div class="row">
<div class="col-xs-12 col-centered">
<div class="col-xs-8 col-md-3 col-lg-3">
<button type="submit" name="btn" value="search" id="myButton" class="search_button btn btn-small btn-default btn-pull-right">Press</button>
</button>
</div>
</div>
</div>
<div class="row">
<div id="results"><!--data displayed here-->
</div>
</div><!--Row-->
</div><!--Cont-->
jQuery
$(document).ready(function(){
$(function() {
$("#myButton").click(function() {
var btn = $("#myButton").val();
var data = 'btn='+ btn;
// if location is not empty
if(data) {
// ajax call
$.ajax({
type: "POST",
url: "mydata.php",
data: data,
success: function(html){
$("#results").append(html);
}
});
}
return false;
});
});
});
mydata.php looks like this:
<?php
if (isset($_POST['btn'])) {
echo "
<div class=\"col-xs-6\">
<ul>
<li><h4>Data in this Div</h4></li>
</ul>
</div>
<div class=\"col-xs-6\">
<ul>
<li><h4>And Data in this Div</h4></li>
</ul>
</div>";
}
?>
if you do not add jQuery library then include it
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-12 col-centered">
<div class="col-xs-8 col-md-3 col-lg-3">
<button type="submit" name="btn" value="search" id="myButton"
class="search_button btn btn-small btn-default btn-pull-right">Press
</button>
</button>
</div>
</div>
</div>
<div class="row">
<div id="results"><!--data displayed here-->
</div>
</div><!--Row-->
</div><!--Cont-->
<script>
$(document).ready(function () {
$(function () {
$("#myButton").click(function () {
var btn = $("#myButton").val();
var data = 'btn=' + btn;
// if location is not empty
if (data) {
// ajax call
$.ajax({
type: "POST",
url: "http://localhost/edit.php", // your file path
data: data,
success: function (html) {
$("#results").append(html); // if you want to replace results div then change $("#results").html(html);
}
});
}
return false;
});
});
});
</script>
it is working fine my side, i have tested in my local side
this is output:
Removing the ajax part works without problems... Are you sure you are receiving that exact HTML?
$('#result').append("<div class=\"col-xs-6\">"+
"<ul>"+
"<li><h4>Data in this Div</h4></li>"+
"</ul>"+
"</div>"+
""+
"<div class=\"col-xs-6\">"+
""+
"<ul>"+
"<li><h4>And Data in this Div</h4></li>"+
"</ul>"+
"</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
</div>
$('#myButton').on('click',function(){
var form = jQuery("#form");
$.ajax({
url: 'mydata.php',
type: 'POST',
data: form.serialize(),
cache: false,
dataType : 'json',
success: function(data){
if(data==true){
$("#results").append(data);
}
if(data==false){
}
},
error: function(){
}
});
return false;
});
I have a table that queries from a database that is updated frequently, and where
<span id="totalvotes1"></span>
and where
<span id="totalvotes2"></span>
I need to be able to be able to identify those in the line
success: function(data) { $('#totalvotes1').text(data); } });
in my ajax for each corresponding row queried... the way it is set up right now, my ajax will just display the information back into
<span id="totalvotes1"></span>
in the last row queried....
<?php
$sql = mysql_query("SELECT * FROM blogData ORDER BY id DESC");
$sql2=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 0 ORDER BY mes_id DESC");
$sql3=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 1 ORDER BY mes_id DESC");
$count_variable = 0;
while(($row = mysql_fetch_array($sql))AND($row2 = mysql_fetch_array($sql2))AND($row3 = mysql_fetch_array($sql3)) ){
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$category = $row['category'];
$podcast = $row['podcast'];
$datetime = $row['datetime'];
$message1=$row2['msg'];
$mes_id1=$row2['mes_id'];
$totalvotes1=$row2['totalvotes'];
$message2=$row3['msg'];
$mes_id2=$row3['mes_id'];
$totalvotes2=$row3['totalvotes'];
?>
<table class="content">
<tr>
<td>
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<span id="totalvotes1"><?php echo $totalvotes1; ?></span><br />
</div>
<div id="message">
<?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
<div id="main">
<div id="right">
<br />
<span id="totalvotes2"><?php echo $totalvotes2; ?></span><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $message2; ?>
</div>
<div class="clearfix"></div>
</div>
</td>
</tr>
</table>
<?php
}
?>
here is my general.js file
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(data) { $('#totalvotes1').text(data); }
});
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(data) { $('#totalvotes2').text(data); }
});
}
});
});
});
Possibly a earlier version of your latest question,
JSON encode, ajax and display back in html
In my answer on your latest question about this, I've given a detailed example of how to use JSON data between PHP and jQuery.