Can'r Fetch data from database using Axios - javascript

I want to fetch data from database but can't get it and when I console print it, is just empty.
Is there something wrong with my code?
function har() {
axios.get(url2, {
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'body-mass-index-bmi-calculator.p.rapidapi.com',
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.error(error);
});
}
This is my my php code
<?php
include 'db.php';
$emparray = array();
$sql = 'SELECT * FROM schedule_list';
$results = mysqli_query($conn,$sql);
while($row = $results->fetch_assoc()){
$emparray[] = $row;
}
$hey = json_encode($emparray)
?>
I just want to get the data from the json encode to javascript without using react or vue, just plain vanilla javascript

You aren't outputting anything in your server code. Try instead to output the results like:
<?php
include 'db.php';
$emparray = array();
$sql = 'SELECT * FROM schedule_list';
$results = mysqli_query($conn,$sql);
while($row = $results->fetch_assoc()){
$emparray[] = $row;
}
echo json_encode($emparray);
?>

Related

Query result in the error response in the JQuery function

I have a problem, clicking in a < tr > of a table I call a javascript function which in turn calls a function in php to get data in a database. The click on the table row works, sql works, and from the console.log command I know there is an answer in reponseText. but it does not work and I get the error back, I'll post the code. I hope you can help me.
file config.php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
file cards.php
<?php
class card
{
private $_db;
function __construct($db){
$this->_db = $db;
}
public function view_card_id($id)
{
$rows = array();
$statement = $this->_db->prepare('SELECT * FROM card_details WHERE card_id = :card_id');
$statement->execute(array(':card_id' => $id));
$numrows = $statement->fetch(PDO::FETCH_ASSOC);
if($numrows < 1) {
$this->error = "Error";
return false;
} else {
$statement->bindColumn("card_id", $cid);
$statement->bindColumn("a", $a);
$statement->bindColumn("b", $b);
$rows[] = array('card_id' => $numrows['card_id'], 'a' => $numrows['a'], 'b' => $numrows['b']);
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$row = array('card_id' => $cid, 'a' => $a, 'b' => $b);
$rows[] = $row;
}
return $rows;
}
}
file index.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
?>
html code ....
<script src="/js/Cards.js" type="text/javascript"></script>
file Cards.js
$('#table-cards tr').click(function() {
var id = $(this).find("a").text();
$.ajax({
type: 'POST',
url: '/classes/cardsFunc.php',
dataType:'text',
data: {functionname: "view_card", id: id },
success: function(response){
//Use response
alert("Server echo: "+response);
console.log(response);
},
error: function(msg){
console.log(msg);
alert("Error: "+msg);
}
});
});
In the Cards.js file, once the $ .ajax function is called, it does not return to success but to error, but in the console.log I see the array of the executed query under the responseText entry.
that is, in the error response, I see the result of the query, which in theory should be in the response of success.
I also tried to use
$.post('/classes/cardsFunc.php', { functionname: 'view_card', id: id }, function(data){
});
but nothing
file cardsFunc.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
thank you for the time you have dedicated to me
I noticed that if I recreate the connection to the db in the file cardsFunc.php, everything works, but I do not understand why, since everything is in the config.php file.
Like this:
file cardsFunc.php
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>

How to login with session using Angular?

login.js
$http({
url: 'http://ipadress/login.php',
method: 'POST',
data: {
'var_id': $scope.form.txt_id,
'var_pass': $scope.form.txt_pass
}
}//http
login.php
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
mysql_connect("localhost","root","password");
mysql_select_db("db");
$data = file_get_contents("php://input");
$dataJsonDecode = json_decode($data);
$var_id = $dataJsonDecode->var_id;
$var_pass = $dataJsonDecode->var_pass;
$sql = "SELECT * FROM user WHERE user_login = '".($id)."' and user_pass = '".md5($pass)."'";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
$resource = mysql_query($sql);
$count_row = mysql_num_rows($resource);
if (!$result) {
$results = '{"results":"not match"}';
} else {
$_SESSION["users_login"] = $result["users_login"];
session_write_close();
if($count_row > 0){
$results = '{"results":"match"}';
} else {
$results = '{"results":"Error"}';
}
}
echo $results;
?>
$http.get('http://ipaddress/data_user.php')
.then(function (response) {
console.log(response.data.results);
$scope.myData = response.data.results;
}, function (error) {
console.log(error);
});
user_data.php
<?php
session_start();
if($_SESSION['users_login'] == ""){
$results = '{"results":"Please Login"}';
echo $results;
}
else{
mysql_connect("localhost","root","password");
mysql_select_db("db");
mysql_query( "SET NAMES UTF8" );
$sql = "SELECT * FROM users WHERE users_login = '".$_SESSION["users_login"]."' ";
$query = mysql_query($sql);
$count_row = mysql_num_rows($query);
if($count_row > 0){
while($result = mysql_fetch_array($query)){
$rows[] = $result;
}
$data = json_encode($rows);
$totaldata = sizeof($rows);
$results = '{"results": '.$data.'}';
}
echo $results;
}
?>
I have problem with login. My $results = please login.
First check what $result["users_login"] contains..
You are getting the please login because you don't have the session data.
I am not sure about your approach, but don't mix php session and Ionic, You can create a kind of API to check user credentials from your ionic App, or else handle it in the ionic app.
Session normally used in websites to pass data through out the page, not for API calls. Think of scenario 10 users access your app simultaneously, How you going to use the Session to verify them?
My advise is, instead of using PHP sessions, you can handle your sessions inside your app using the session storage
Read this. There are plenty of plugin available. OR you can create your as shown here
Good Luck!!

convert php array to js selectpicker array format

This is how I build sql data and send back to ajax call:
(...)
$sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
$result = mysqli_query($conn, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
$data["win_data"] = $rows;
echo json_encode($data);
This is my ajax function to get options for selectpicker from DB:
$.ajax({
type: "POST",
url: ...,
data: ...,
dataType: "json",
success: function(data) {
$("#id_win").selectpicker("val", data.win_data);
// $("#id_win").selectpicker("val", [1,3];
}
});
data.win_data variable should be: [1,3]
but if I do:
console.log(JSON.stringify(data.win_data));
I get:
[{"0":"1","id_option":"1"},{"0":"3","id_option":"3"}]
What is the simplest way to get proper format array for selectpicker?
It is because $row is an array. Look: https://secure.php.net/manual/pt_BR/mysqli-result.fetch-array.php
You have to use like this:
(...)
$sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
$result = mysqli_query($conn, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row['id_option'];
}
$data["win_data"] = $rows;
echo json_encode($data);
forget about mysqli and use PDO, it has everything you need.
$stmt = $pdo->prepare("SELECT id_option FROM options WHERE id_win = ?");
$stmt->execute([$id_win]);
$data["win_data"] = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($data);
this code is 2 times shorter and 100 times more secure

Return echo from php-function to ajax

I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.

Display All Data with PHP AJAX JSON using JQUERY

filePHP.php
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
echo json_encode($json);
}
and index.php
$.post('filePHP.php', function(data){
console.log(data);
},'json');
but this not working, what would solve this problem?
Try this in PHP
$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
array_push($json,$arr);
}
echo json_encode($json);
Read array-push
try something like this , your code will echo json in wrong format whereas below code will give you json array.
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$temp_arr = array();
$temp_arr['id'] => $row['id_kategori'];
$temp_arr['nama'] => $row['nama_kategori'];
array_push($json_arr,$temp_arr);
}
echo json_encode($json_arr);

Categories

Resources