display data from database using ajax,mysql,php - 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);
}

Related

Edit multiple values in ajax

I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}

json ajax php mysql

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>

Using AJAX to return JSON from PHP

Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.

php jquery iterate php array in success function

I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.
In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});
change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,
You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";

How to bring json and html data in one ajax call

I have a two jquery function to bring ratings and comments separately from two files which is working fine.
Now i want to do it in a single ajax call, i am trying to merge two function together this way but its not working.
jquery
function get_review(){
$.ajax({
type: "POST",
url: '../review.php',
data: {value1:value1, value2:value2, value3:value3},
dataType: 'json',
cache: false,
success: function(data)
{
var x = data[0];
var rating = (x-0.5)*2
var y = (20 * rating)+40;
$('#urating').css("backgroundPosition","0%" +(y)+ "px");
$('#comments').html(data);
}
});
};
PHP
$find_data = "SELECT * FROM $tablename WHERE table_name='$table' AND product_id='$id' ORDER by id DESC";
$query = mysqli_query($connection, $find_data);
$find_data2 = "SELECT * FROM $tablename2 WHERE id='$id'";
$query2 = mysqli_query($connection, $find_data2);
$row2 = mysqli_fetch_assoc($query2);
header('Content-type: application/json');
echo json_encode($row2);
?>
<?php while($row = mysqli_fetch_assoc($query)):?>
<div class="comment-container">
<div class="user-info"><?php echo $row['user_name']; ?></div>
<div class="comment"><p><?php echo $row['quick_comment']; ?></p></div>
</div>
<?php endwhile;?>
Please see and suggest any possible way to do it.
Thanks.
Try to encode whole response to JSON object!
Something like:
$response = array(
'success' => true,
'object' => $yourobject_or_array,
'html' => '<b>Bla bla</b>'
);
echo json_encode($response);
die();
JS:
function(response) {
var res = false;
try {
res = jQuery.parseJSON(response);
} catch(e) {}
if (res && res.success) {
// Use res.object and res.html here
}
}

Categories