Retrieve database data using PHP and AJAX - php

I am trying to retrieve data from database using AJAX without any success. These are the codes I am using. I dont see any specific errors in console.
HTML:
<button type="button" name="result_submit" id="result_submit" >Submit</button>
<div class="result" id="result" name="result"> </div>
Jquery:
$(document).ready(function(e) {
$('#result_submit').click(function() {
$.ajax({
url :"Income.php",
type :'POST',
success: function(data){
$("#result").html(data);
}
});
});
});
Income.php content:
<?php
include_once 'dbConnection.php';
$stmt = mysqli_stmt_init($conn);
$income = "select SUM(amount) as incomeNumber FROM wp_formdata WHERE entry_type='Income'";
if(!mysqli_stmt_prepare($stmt,$income))
{
$message = '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
}
else
{
mysqli_stmt_execute($stmt);
$result= mysqli_stmt_get_result($stmt);
$income_sum=mysqli_fetch_assoc($result);
$TotIncome= "Total Income is ".$income_sum['incomeNumber'];
}
?>
dbConnection.php has connections details:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "wordpress";
$conn= mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
?>
Can someone guide me how to resolve the issue

You need to echo your data from your PHP file :
$income = "select SUM(amount) as incomeNumber FROM wp_formdata WHERE entry_type='Income'";
$response = '';
if (! mysqli_stmt_prepare($stmt,$income)) {
$response = '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$income_sum = mysqli_fetch_assoc($result);
$response = "Total Income is ".$income_sum['incomeNumber'];
}
echo $response;

First off all add on the beginig of page:
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('error_reporting', E_ALL);
and
printf("Errormessage: %s\n", mysqli_error($income_sum));
afther query to db.
Do you have any respons from the page called by ajax?

The script that you call using AJAX doesn't render anything.
echo $TotIncome;

Related

Check if value is exist in database jQuery and php

I m having a bit of trouble while validating value in database.
This is my html and js Code:
<input type="text" name="Unieke-voucher" value="" size="40" maxlength="8" minlength="8" id="voucher" aria-required="true" aria-invalid="false" placeholder="XYZ 1234">
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(vCode) {
jQuery.ajax({
url: 'voucher.php',
type: 'GET',
dataType: 'json',
data: {value: vCode},
success: function(data) {
if(data.status) {
jQuery("#codeError").html('');
console.log(data);
} else {
jQuery("#codeError").html('Value not found');
}
console.log(data);
}
});
}
With this getting value with keyup event and sending to php script till here working fine.
And this is php script:
$dbname = "voucher";
$dbuser = "root";
$dbpass = "root";
$dbhost = "localhost";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$voucherCode = $_GET['VoucherCode'];
$voucherCode['status'] = false;
//echo $voucherCode;
$result = mysqli_query($conn, "SELECT * FROM VoucherCode WHERE `code` LIKE '$voucherCode' LIMIT 1");
if(mysqli_num_rows($result)) {
$userData = mysqli_fetch_assoc($result);
$voucherCode['code'] = $Code;
$voucherCode['status'] = true;
}
echo json_encode($voucherCode);
I am always getting status value even providing correct value.
When i print_r table like
$resultAll = mysqli_query($conn, "SELECT * FROM VoucherCode");
$data2 = mysqli_fetch_all($resultAll);
print_r($data2);
I am able to see all data is there.
I am not sure what i am doing wrong here. Can anyone help me with this please.
Thanks in advance.

Unable to get html data From option value

I am getting the id of selected option value But the table data is not displayed with option change. I am not getting error and not able to find what is mistake.
dashboard.php
<select id="employee">
<option value="" selected="selected"></option>
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "test2";
$lastId="";
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
$sql = "SELECT asset_type,department,cost FROM track_data";
$resultset = mysqli_query($con, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["asset_type"]; ?></option>
<?php } ?>
</select>
<div id="display" style="color: black">
<div class="row" id="heading" style="color: black"><h3><div class="col-sm-4"><strong>Employee Name</strong></div><div class="col-sm-4"><strong>Age</strong></div><div class="col-sm-4"><strong>Salary</strong></div></h3></div><br>
<div class="row" id="records" style="color: black"><div class="col-sm-4" id="emp_name"></div><div class="col-sm-4" id="emp_age"></div><div class="col-sm-4" id="emp_salary"></div></div>
</div>
<script type="text/javascript">
$(function () {
// $("#show_table").show();
$(document).ready(function(){
// code to get all records from table via select box
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'id='+ id;
$.ajax({
url: 'getEmployrr.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#emp_name").text(employeeData.asset_type);
$("#emp_age").text(employeeData.department);
$("#emp_salary").text(employeeData.cost);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
}
}
});
})
});
});
</script>
getEmployrr.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "test2";
$lastId="";
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
if($_REQUEST['id']) {
$sql = "SELECT asset_type,department,cost FROM track_data WHERE id='".$_REQUEST['id']."'";
$resultset = mysqli_query($con, $sql) or die("database error:". mysqli_error($con));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
I am getting the head but not able to get the values inside the div. I am not getting any type of errors but values are not displaying. How can I solve the issue.
In first SQL query :
$sql = "SELECT asset_type,department,cost FROM track_data";
You don't select id, try to add it to your query :
$sql = "SELECT id,asset_type,department,cost FROM track_data";

withdraw my information from sql using ajax&js, dont know what's worng

I am working on a chrome extension (freshment) and have a little problem.
I have a button, and I want that when button is clicked, to show my information from my database on my extension page.
HTML :
<button class="button" id="show" style="vertical-align:middle" onclick="myAjax()"><span>Show my purchaes</span></button>
<div id="showhere">
//this is where i want to show the info
</div>
Java Script :
$(document).ready(function(){
function myAjax() {
$.ajax({
url:"http://127.0.0.1/show.php",
data:{ action:'showhere' },
method:"POST",
success:function(data) {
('#showhere').html(data);
}
});
}
});
PHP :
<?php
if($_POST['action'] == 'showhere') {
$servername = "localhost";
$username = "root";
$password = "********";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ProductName, Amount, Date, WebStore FROM budget";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ProductName"]."</td><td>".$row["Amount"]."</td><td>".$row["Date"]."</td><td>".$row["WebStore"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
What I want it to do is pretty simple : I have a button and below I have a div called : "showhere", and in this div I want to take mysql info and write it.
your write i didnt write the exact problem, the problem is that the button doesnt do anything.
agian , thx!
I suggest you set it this way:
$(document).ready(function() {
$('#show').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "http://127.0.0.1/show.php",
data: {
action: 'showhere'
},
method: "POST",
success: function(data) {
('#showhere').html(data);
}
});
});
});

How to limit checkbox selection in PHP?

So far I have been able to get data from MYSQL and display it as a checklist using PHP and HTML. Now I would like to limit the number of checkboxes that can be selected at a time. Javascript doesn't seem to be working with my PHP code.
EDIT: I've included my JScript below which is currently not workng. This JScript only works when I use it with manually created html checklists but not the one I have made below using MYSQL data. How can I fix my Javascript part so this works?
Here is my code:
<?php
$username = "root";
$password = "test";
$hostname = "localhost";
$dbname = "major_degrees";
$str='';
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT degree_name FROM majors";
$result = $conn->query($sql);
$out = '';
$cnt = 0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$cnt++;
$out .= '<input id="cb_' .$cnt. '" class="someclass" type="checkbox" />' .$row['degree_name']. '<br/>';
}
echo $out;
}
$conn->close();
?>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<script>
$out.on("click", ":checkbox", function(event){
$(":checkbox:not(:checked)", this.form).prop("disabled", function(){
return $(this.form).find(":checkbox:checked").length == 2;
});
});
</script>
try this:
<script>
$(".someclass").change(function() {
var count = $(".someclass:checked").length; //get count of checked checkboxes
if (count > 3) {
alert("Only 3 options allowed..!");
$(this).prop('checked', false); // turn this one off
}
});
</script>

How to display the result of my php in ajax

I want to do is display the result of my count.php in my index page. My plan is to auto count the number of rows of user_code and display the result in the index page everytime the page is visited or viewed.
My problem is that the ajax script doesnt recieve the result of count.php to display it in count inputbox on index page.
index page:
<input type="text" value="1" name="countValue" id="countValue" style="width: 12px;" /><br />
Count: <input type="text" name="count" id="count" readonly="readonly" /><br /><br /><br />
<script>
$(document).ready(function(){
var countTimer = setInterval(
function ()
{
codeValue();
}, 500);
var $count = $('#count');
function codeValue(){
$.ajax({
url:"count.php",
type:"GET",
data: { term : $('#countValue').val() },
dataType:"JSON",
success: function(result) {
$("#count").val(result.user_code);
}
});
};
});
</script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $_GET['term'];
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT user_code FROM students";
$query = $dbc->prepare($sql);
$query->execute();
$num_rows = $query->rowCount();
echo json_encode(array('user_code'=>$num_rows));
}
?>
Your problem
echo $_GET['term'];
This breaks the expected JSON format that your script is meant to produce. Also, you aren't even using any request parameters so I don't know why you'd even bother.
Here's your PHP, all cleaned up
<?php
try {
$dbc = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $dbc->query('SELECT COUNT(1) FROM students');
header('Content-type: application/json');
echo json_encode(['user_code' => $stmt->fetchColumn()];
} catch (Exception $e) {
http_response_code(500);
echo $e->getMessage();
}
I'd also suggest adding an error callback to your $.ajax options to handle HTTP errors.
i try your code and it works for my table i have (4) records! check your query if there is data
make sure you have jquery file in your header. I did not change anything your html file. I just create my own query on my table. then okay.
You need to create a div in indexfile and id of that div is provided in ajax file,so as to populate data form count.php in that div.
Here i will give you a similar type of example, Try it by making your related changes
index.php
<div id="content">
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'count.php',
success: function(data) {
$('#content').html(data);
}
});
<script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$con=mysqli_connect($host,$user,$pass,$db);
$result = mysqli_query($con,"SELECT user_code FROM students");
?>
<table>//this table will be loaded in div
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['user_code']; ?></td>
</tr>
<?php
}
?>
</table>
You can also add autorefresh ajax script which will only reload only particular div after specific time interval(1 sec in below code) without reloading whole page
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#content').load('count.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>

Categories