Get multiple php data via json ajax with the same name - php

I'm working on a live search and i need to transfer php data to ajax using json, but the problem is i can't pass an array contain 2 or more identical values, this is the php code:
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
}
}
}
}
?>
And this is the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data){
$('#feedback').html(json_data.name);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
So, if my array contain 2 or more identical names ajax wont get any data back, I hope someone have an answer.

You should create array with all results in your search function and then in ajax response loop results to get all names and print it separated by comma.
Search function
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
$results = []; //<!---
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json; //<!---
}
}
}
echo json_encode($results); //<!---
}
}
?>
Ajax
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var names = [];
$.each(json_data, function(index, element) {
names.push(element.name)
})
$('#feedback').html(names.join(','));
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>

Change this:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
To:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json[] = array('img' => $img, 'name' => $name, 'username' => $username);
}
echo json_encode($json);
Inside your response for jQuery, retrieve your json data by looping it. Make sure to use var obj = jQuery.parseJSON( json_data ); before looping

Related

How to send and recieve multivariables to php using json and array

I want to send some data from a form to a PHP file using jQuery. I've searched and I noticed I have to send the data as JSON and receive multiple variables as an array. However I'm Completely confused it's not working.
<input id="username" type="text" class="inputBox">
<input id="password" type="password" class="inputBox">
<button id="submitLogin" class="submitLogin">login</button>
<div id="test"></div>
<div id="test1"></div>
$(document).ready(function() {
$("#submitLogin").click(function() {
var superuser = $("#username").val();
var superpass = $("#password").val();
$.ajax({
type: "POST",
url: 'http://localhost/mainclinic/controllers/login/login.php',
dataType: 'application/json',
data: {
loginid: superuser,
loginpass: superpass
},
cache: false,
success: function(result) {
$('#test').html(result[0]);
$('#test1').html(result[1]);
}
})
})
})
<?php
include "../config.php";
if (!$db)
{
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$username = mysqli_real_escape_string($db, $_POST['loginid']);
$password = mysqli_real_escape_string($db, $_POST['loginpass']);
$sql = "SELECT id FROM superusers WHERE docid = '$username' and doccpass = '$password'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0)
{
$array = array(success, $username);
echo json_encode($array);
}
else
{
$array = array(failed, nousername);
echo json_encode($array);
}
}
?>
Change This section to this:
$.ajax
({
type:"POST",
url:'http://localhost/mainclinic/controllers/login/login.php',
dataType: "json",
data:{loginid:superuser,loginpass:superpass},
cache: false,
success:function (result) {
$('#test').html(result.status);
$('#test1').html(result.result);
}
})
And Php code like this:
if(mysqli_num_rows($result) > 0)
{
$array = array('status' => 'success', 'result' => $username);
echo json_encode($array);
}else
{
$array = array('status' => 'failed', 'result' => 'nousername');
echo json_encode($array);
}

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);
}

PHP Send data back to AJAX

I'm trying to get data from my database using ajax and php, but whenever I try to get it I get an error with ajax. Here is my code:
HTML
Here is my code where I request the php file.
<body>
<div id="wrapper">
<h2>Coffe Shop</h2>
<p class="bold">Drink orders:</p>
<ul class="orders">
</ul>
<p class="bold">Add an order:</p>
<p>Drink: <input type="text" id="name"/><input type="submit" id="submit"/></p>
<button id="refresh">CLICK ME</button>
</div>
<script>
$(function (){
$("#refresh").on("click", function() {
$.ajax({
type: "GET",
url: "data.php",
dataType: "json",
success: function(names){
$.each(names, function(name){
alert(name);
});
},
error: function(){
alert("error");
}
});
});
});
</script>
</body>
PHP
Here is my PHP file
<?php
$conn = mysqli_connect("localhost:8080", "root", "", "test1")
or die("Error with connection");
$sql = "SELECT ime FROM users;";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$names = array();
while($row){
$name = array(
"name"=> $row['ime']
);
$names[] = $name;
}
echo json_encode($names);
You have an infinite loop in your PHP. You're just fetching one row, and then looping over that same row. Since you never change $row in the loop, it never ends. It should be:
while ($row = mysqli_fetch_assoc($result)) {
$name = array('name' => $row['ime']);
$names[] = $name;
}
Once you fix that, the JSON you'll be sending will look like:
[{"name": "Some name"}, {"name": "Another name"}, {"name": "Fred"}]
In your Javascript, you're not accessing the name property. Change
alert(name);
to:
alert(name.name);
Or you could change the PHP so it just sends an array of strings instead of objects:
while ($row = mysqli_fetch_assoc($result)) {
$names[] = $row['ime'];
}

Explode Data from MySQL and pass the value with json_encode

i am really new in explode and implode. I want to explode data from my database and enter the value to array so i can pass it to my HTML page with json_encode
This is my PHP file
<?php
session_start();
include "config.php";
$zzz = array();
$pass = array();
$idacara=mysql_real_escape_string($_GET["id"]);
$mysql = ("select kategori from acara where id_acara='$idacara'");
$result=mysql_query($mysql);
if (!empty($result))
{
while ($row=mysql_fetch_array($result))
{
$temp = explode(",",$row['kategori']);
$count = count($temp);
for($i=0;$i<$count;$i++)
{
$zzz=$pass[$i];
}
$fetchkategori[] = array
(
'kategori' => $zzz
);
}
}
mysql_close($con);
header('Content-Type:application/json');
echo json_encode($fetchkategori);
?>
This is my Ajax in HTML File
var arrKategori=new Array();
$.ajax({
url: host+'/skripsi3/phpmobile/kategori.php',
data: { "id": getacara},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
if (arrKategori.indexOf(item.idkat)<0)
{
$("fieldset").append('<input type="radio" name="radiokategori" class="required" id="'+item.idkat+'" value="'+item.idkat+'" required><label for="'+item.idkat+'">'+item.kategori+'</label>').trigger("create");
arrKategori.push(item.idkat);
}
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
Thank You Before and Have a nice day :D
Well, first of all, do not use mysql_* functions. Instead use use mysqli_* or PDO functions.
You have to declare $fetchkategori[] outside the first if block in following way
$fetchkategori = array();
After that inside while loop, store the array in the following way.
$fetchkategori[] = array
(
'kategori' => $zzz
);
Your code will work.
Here is a complete solution using mysqli
config.php
$mysqli = new mysqli('mysql_hostname', 'mysql_username', 'mysql_password', 'mysql_database');
PHP file
<?php
session_start();
include "config.php";
$zzz = array();
$pass = array();
$fetchkategori = array();
$idacara=$_GET["id"];
//preparing query
$stmt = $mysqli->prepare("select kategori from acara where id_acara=?");
$stmt->bind_param('i', $idacara);
$stmt->execute();
$stmt->store_result();//add this line
$stmt->bind_result($kategori);
if ($stmt->num_rows>0)
{
while ($stmt->fetch())
{
$temp = $kategori;
$count = count($temp);
for($i=0;$i<$count;$i++)
{
$zzz=$pass[$i];
}
$fetchkategori[] = array
(
'kategori' => $zzz
);
}
}
mysqli_close($mysqli);
header('Content-Type:application/json');
echo json_encode($fetchkategori);
?>

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