json ajax php mysql - php

I have table users.
id
login
password
I want to display the data in JSON format through php mysql
page: config.php
$rep = $db->query("SELECT * FROM users");
$array_user = array();
while($data = $rep->fetch()){
$array_user = $data;
}
echo json_encode($array_user);
?>
page listUsers.php
<div id="tab"></div>
<script>
$(document).on("ready",function(){
loadData();
});
var loadData = function(){
$.ajax({
type:"POST",
url:"config.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#tab").append(users[i].login + "<br>");
}
});
}
</script>
but it appears to me "undefined".

Use this
<?php
$rep = $db->query("SELECT * FROM users");
$array_user = array();
while($data = $rep->fetch()){
$array_user[] = $data;
}
echo json_encode($array_user);
?>
<div id="tab"></div>
<script>
$(document).on("ready",function(){
loadData();
});
var loadData = function(){
$.ajax({
type:"POST",
url:"config.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#tab").append(users[i].login + "<br>");
}
});
}
</script>

Related

Ajax response not returning

I am having a table with data where I have an action button in last column to delete that particular row. I want to make the delete via ajax and without refreshing the page. I am using the following code but their is no response coming from the ajax page. Also the queries at the ajax page is not executing. Can I have some insight over what could be possibly wrong.
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var $tr = $(this).closest('tr');
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
success : function(response) {
if(response=='deletion success'){
$tr.find('td').fadeOut(1000,function(){ $tr.remove(); });
}
}
});
}
return false;
});
});
</script>
And at delete_entry.php
<?php
header('Content-Type: application/json');
session_start();
require("../config.php");
require("../Database.class.php");
require("../site.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$fnc=new site_functions($db);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_ques","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_ques",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
if($db->query_update("tbl_ques", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
?>
Change your java script function as below
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data: info,
//changes from
success : function(response) {
if(response=='deletion success'){
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
}
});
//changes to
}
return false;
});
});
</script>
Also change you php file
<?php
header('Content-Type: application/json'); // Add this line its must
session_start();
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$id = $_POST['id'];
$deleted_date = date("Y-m-d h:i:s");
$deleted_by = $_SESSION['session_admin_id'] ;
$nots = $db->idToField("tbl_question","notes",$id);
if ($nots == "")
{
$date_string = "last deleted on|".$deleted_date."|" ;
}
else {
$date_string = $nots."last deleted on|".$deleted_date."|" ;
}
$fnc->update_is_not_deleted_for_Pearsonvue("tbl_question",$id, "$deleted_date", $deleted_by);
$notes_data = array("notes"=>$date_string);
//changes from
if($db->query_update("tbl_question", $notes_data, "id=$id")){
http_response_code();
echo json_encode('deletion success');
}else{
http_response_code(204);
}
//changes to
?>

display data from database using ajax,mysql,php

Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}

How to get two arrays from php using mysqli,jquery ajax?

i want the function(data) to get 2 attribute value from the database
This is the select option that display the display the address and contact value of the selected option in an input field
$('#recipient').change(function(){
var FULL_NAME = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{FULL_NAME:FULL_NAME},
success:function(data){
$('#address').val(data);
$('#contact').val(data);
}
});
});
and this is the load_data.php
<?php
$sql = "SELECT * FROM recipient";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output1 = $row["ADDRESS"];
$output2 = $row["CONTACT"];
$arr = array($output1,$output2);
}
echo $output1,$output2;
?>
How do i pass the $output1 into $('#address').val(data) and $output2 into $('#contact').val(data)
$('#recipient').change(function(){
var FULL_NAME = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
dataType: "json",
data:{FULL_NAME:FULL_NAME},
success:function(data){
$('#address').val(data['ADDRESS']);
$('#contact').val(data['CONTACT']);
}
});
});
and the load_data.php
<?php
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$arr["ADDRESS"] = $row["ADDRESS"];
$arr["CONTACT"] = $row["CONTACT"];
}
echo json_encode($arr);
?>

Display details from database using ajax/jquery

getStudents.js
$("#submit").click(function(){
$.ajax({
url: "displayStudents.php?branchCode=1",
datatype:"JSON",
success: function(obj){
for(var i=0; i<obj.length; i++){
$("ul").append(obj[i].name)
}
}
})
});
displayStudents.php
<?php
include 'config.php';
$branchCode = $_GET['branchCode'];
$list = mysqli_query($con, "Select * from student where branchCode = '$branchCode' ORDER BY rollNo");
$result = array();
while($row = mysqli_fetch_array($list)){
$result[] = array("RollNo"=>$row['rollNo'], "Name"=>$row['name']);
}
header("Content-type: application/json");
echo json_encode($result);
?>
The php file 'displayStudents.php' is sending the json correctly but I'm not able to display the names of the students.

username availability PDO not working

This is my HTML Code
<input type="text" class="form-control" id="stfmail" name="staffmail" placeholder="E-Mail" required="required"><span id="result"></span>
In jQuery Ajax
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
PHP
if($_POST)
{
$username = $_POST['name'];
$ob->useravailable($username);
}
public function useravailable($username)
{
$stmt=$this->conn->prepare("select user_name from users where user_name=:uname and delet='0'");
$stmt->execute(array(':uname'=>$username));
if($stmt->rowCount()>0)
{
echo "<span style='color:brown;'>Sorry username already taken !!!</span>";
}
else
{
echo "<span style='color:green;'>available</span>";
}
}
Here i type a username..but in useravailable function only else part is working.. I type Existing username it works the else part available message is shown..
Please help me
thanks
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
if(data) {
$(".redbold").html('already this username is there ').show();
$("#username").focus();
}
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
if($_POST)
{
$username = $_POST['name'];
$query = mysql_query("SELECT user_name from users where user_name ='".$username ."' ", $con);
while ($row = mysql_fetch_assoc($query)) {
echo $row['user_name '];
}
}

Categories