I have written php code to select specific patient info, i used pdo to connect with database, the result of file is json format.
{"success":1,"message":"patient info Available!","patient_info":[{"name":"Nora","gender":"M","email":"NouraSaeed#yahoo.com","Date":"2016-10-17"}]}
but when i wrote js code in intel xdk to display json data ,no output displayed on screen.How can i display the value of success or message in xdk !
<html>
<body>
<?php
require("config.inc.php");
$pid = $_GET["id"];
$query = " SELECT * FROM patient where PatientID=$pid";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
} catch (PDOException $e) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "patient info Available!";
$response["patient_info"] = array();
foreach ($rows as $row) {
$post = array();
$post["name"] = $row["PName"];
$post["gender"] = $row["Gender"];
$post["email"] = $row["email"];
$post["Date"] = $row["BDate"];
array_push($response["patient_info"], $post);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No patient_info Available!";
die(json_encode($response));
}
?>
</body>
</html>
This xdk code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<script type="text/javascript">
function createXHR() {
if (typeof XMLHttpRequest != "undefined")
return new XMLHttpRequest();
else
return new ActiveXObject("Microsoft.XMLHttp");
}
function requestPatientInfo() {
var pid = document.getElementById("pid").value;
var oXmlHttp = createXHR();
oXmlHttp.open("get", "http://localhost/hospital/GetPatientData2.php?id=" + pid);
oXmlHttp.onload = function () {
if (oXmlHttp.readyState == 4) {
if (oXmlHttp.status == 200 || oXmlHttp.status == 304) {
var patients = json.parse(oXmlHttp.responseText);
divPatientInfo.innerHTML = patients.message;
}
else
divPatientInfo.innerHTML = oXmlHttp.statusText;
}//end if
}; //end ready state
oXmlHttp.send(null);
}//end function requestPatientInfo
</script>
</head>
<body>
Enter Patient ID to get All Information
<p>
Patient ID: <input type="number" id="pid"/>
</p>
<input type="button" value="Get Info" onClick="requestPatientInfo();"/>
<div id="divPatientInfo"></div>
<iframe name="hiddenFrame" style="width:0 ; height:0"></iframe>
</body>
</html>
Looks you have not defined divPatientInfo.. change as following
var divPatientInfo = document.getElementById('divPatientInfo');
if(oXmlHttp.readyState==4){
if(oXmlHttp.status==200 || oXmlHttp.status== 304 ){
var patients= json.parse(oXmlHttp.responseText);
divPatientInfo.innerHTML=patients.message;
}
else
divPatientInfo.innerHTML=oXmlHttp.statusText;
}//end if
If not resolved check once ajax response using firebug, if possible paste here so that help more.
Related
I created a function that will view the details of the item once the button View will be clicked, the modal will show up with its data. So far, I have a jQuery code:
function ViewDetails(rr_number) {
$('#hidden_rr_number').val(rr_number);
$.post(base_url('ajax/ajaxViewRR.php'), {
rr_number:rr_number
},
function(data, status) {
var details = JSON.parse(data);
$('#edit_selected_supplier').val(details.supplier_name);
$('#edit_selected_po').val(details.po_number);
$('#edit_selected_category').val(details.category_name);
$('#edit_rr_number').val(details.rr_number);
$('#edit_rr_receipt_number').val(details.receipt_number);
$('#edit_date_received').val(details.date_received);
// Open modal popup
$(".modal_edit_rr").modal("show");
}
);
}
and my PHP code:
if(isset($_POST['rr_number']) && isset($_POST['rr_number']) != "") {
$rr_number = clean(unhex(base64_decode(base64_decode(stripslashes(trim(mysqli_real_escape_string($new_conn, $_POST['rr_number'])))))));
$query = mysqli_query($new_conn, "SELECT * FROM receiving_reports WHERE rr_number = '$rr_number'");
$response = array();
if(mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_assoc($query)) {
$response = $row;
}
} else {
$response['status'] = 200;
$response['message'] = "Data not found!";
}
echo json_encode($response);
} else {
$response['status'] = 200;
$response['message'] = "Invalid Request!";
}
So far, I got the output that I want but the data only displayed in textbox and it won't display with option select. what should I do?
here's my output so far:
I have two tables in my database first one id and the other one text.
I can fetch the data from db like this way
this is index.php file
<?php include "config.php"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<ul>
<?php
$result = $db->query("select * from veri ORDER BY id DESC ");
while ($row = $result->fetch_object()) {
echo '<li id="'.$row->id.'">'.$row->text.'</li>';
}
?>
</ul>
</body>
</html>
I am required to check the database every five seconds if a new item inserted or not.
I am using this code below.But It doesnt work.I have no idea what is wrong ?can you please help and thank in advance
ajax.js file
$(function () {
$ajaxLoad = function () {
var lastid = $("ul li:first").attr("id");
$.ajax({
type: "post",
url: "ajax.php",
data: {"lastid": lastid},
dataType: "json",
success: function (result) {
if (result.error) {
$("#result").html(result);
}
else{
$("ul").prepend(result.data);
}
}
});
}
setInterval("ajaxLoad()",5000);
});
this ajax.php file
<?php
require "config.php";
if ($_POST) {
$lastid = $_POST["lastid"];
if (!$lastid) {
$array["error"] = "something is wrong";
} else {
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows()) {
while ($row = $query->fetch_object()) {
$array["data"]='<li id="'.$row->id.'">'.$row->text.'</li>';
}
} else {
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>
Your setInverval() accepts a callback function as first parameter. You passed a string. It should be:
setInterval(ajaxLoad, 5000);
And also, remove the $ from the $ajaxLoad definition. It's JavaScript, not PHP. In case that you would want to prepend the $ to your variable, you must also use that variable along with the $ like so:
$variable = 5;
console.log($variable); // prints 5 to the console
However, it is absolutely bad practice since you will get confused as to whether you are using PHP or JS.
Here also you did a mistake. As per the current code you may get only last record inserted instead of all new inserted records because you are not concatenating the records. This is one way to solve it:
<?php
require "config.php";
if ($_POST)
{
$lastid = $_POST["lastid"];
if (!$lastid)
{
$array["error"] = "something is wrong";
}
else
{
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows())
{
$new_rows = "";
while ($row = $query->fetch_object())
{
$new_rows .= '<li id="'.$row->id.'">'.$row->text.'</li>';
}
$array["data"]=$new_rows;
}
else
{
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>
I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.
I generated some Json data from Mysql Database with PHP as below:
equipments.php
<?php
require("config.inc.php");
//initial query
$query = "Select * FROM equipment";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Equipment Available!";
$response["equipments"] = array();
foreach ($rows as $row) {
$post = array();
$post["EquipmentId"] = $row["EquipmentId"];
$post["Name"] = $row["Name"];
$post["Ip"] = $row["Ip"];
$post["Brand"] = $row["Brand"];
$post["Location"] = $row["Location"];
//update our repsonse JSON data
array_push($response["equipments"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Equipment Available!";
die(json_encode($response));
}
?>
this returned the following data:
//localhost/equip/equipments.php (on my local apache server)
{
success: 1,
message: "Equipment Available!",
equipments: [
{
EquipmentId: "1",
Name: "UCH-NET",
Ip: "172.16.32.4",
Brand: "Engenius",
Location: "Top of ITD"
},
{
EquipmentId: "2",
Name: "UCH-PHOUSE",
Ip: "172.16.32.5",
Brand: "Mikrotik",
Location: "Top of ITD"
},
{
EquipmentId: "3",
Name: "UCH-SON",
Ip: "172.16.32.9",
Brand: "MIkrotik",
Location: "SON"
},
{
EquipmentId: "4",
Name: "UCH-GERIATRIC",
Ip: "172.16.32.10",
Brand: "Mikrotik",
Location: "Geriatric"
}
]
}
But when i try to use the returned Json like this in my AngularJS application no data is returned in the web page
services.js
'use strict';
var equipServices = angular.module('equipServices', ['ngResource']);
equipServices.factory('Equip', ['$resource',
function($resource){
return $resource( '/equip/equipments.php/');
}]);
equipment.js
function EquipmentsCtrl ($scope, Equip) {
$scope.setActive('equipments');
$scope.sidebarURL = 'partials/equipment.html';
$scope.currentEquipment = null;
$scope.setEquipment = function (EquipmentId) {
$scope.currentEquipment = $scope.equipments[EquipmentId];
};
$scope.equipments = Equip.query();
}
}
index.html
<title>IP Library</title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/controllers/app.js"></script>
<script type="text/javascript" src="js/controllers/equipments.js"></script>
<script type="text/javascript" src="js/controllers/admins.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/services.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.min.css">
</head>
<body>
<div class="container" ng-controller="AppCtrl" >
<h1>IP Library</h1>
<ul class="nav nav-pills">
<li ng-class="equipmentsActive">
<a href="#equipments" >Equipments</a>
</li>
<li ng-class="adminsActive">
Administrators
</li>
</ul>
<div ng-view></div>
</div>
</body>
</html>
Is there something wrong with the way I am calling the php generated Json in my services.js?
Thanks
Use Equip.get() instead of Equip.query() because you are getting from server an object, not an array:
Equip.get(function(result){
if(result.success === 1) // isn't better to return boolean?
$scope.equipments = result.equipments;
// else handle error
});
I am having an issue with my AJAX and MySQL/PHP script.
The first file below, is my javascript file I use to test accessing my server. This file works as far as I know and have tested.
Game = function() {};
var timer;
Game.EncodeURI = function (text) {
return encodeURIComponent(text);
}
Game.DecodeURI = function (text) {
return decodeURIComponent(text);
}
Game.AlterDiv = function(div,data) {
if (Game.ID(div)) {
Game.ID(div).innerHTML = data;
}
}
Game.ID = function(value) {
return document.getElementById(value);
}
Game.ServerRequest = function (url, data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
data = xmlhttp.responseText.split("|");
for (i = 0; i < data.length; i++){
var one = Game.DecodeURI(data[parseInt(i)]);
var two = Game.DecodeURI(data[parseInt(i) + 1]);
var three = Game.DecodeURI(data[parseInt(i) + 2]);
var four = Game.DecodeURI(data[parseInt(i) + 3]);
var five = Game.DecodeURI(data[parseInt(i) + 4]);
}
} else {
return false;
}
}
if (!data) {
data = "";
}
data = data.replace(/: /gi, "=");
data = data.replace(/:/gi, "=");
data = data.replace(/, /gi, "&");
data = data.replace(/,/gi, "&");
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
Game.Action = function (id, seconds) {
clearTimeout(timer);
if (id) {
if (!seconds) {
Game.AlterDiv('message', 'You begin working.');
Game.ServerRequest("action.php", "id: " + id);
} else {
Game.AlterDiv('message', 'You begin working.');
Game.ID('timer').innerHTML = seconds;
if (seconds >= 2) {
seconds -= 1;
Game.ID('timer').innerHTML = seconds;
timer = setTimeout(function(){
Game.Action(id, seconds);
},1000);
} else {
Game.ID('timer').innerHTML = "Finished";
Game.ServerRequest("action.php", "id: " + id + ", x: x"); // Request it, then POST "x" to say timer has counted down.
}
}
} else {
alert("There was an error with your request.\n Please try again.");
}
}
This second file is a basic PHP web page that I use to test the said function.
<html>
<head>
<title>Test</title>
</head>
<body>
<span onClick="Game.Action('1','5');">Start Work</span><br /><br />
<div id="message"></div>
<div id="timer"></div>
</body>
</html>
<script type="text/javascript" src="game.js?<?php echo time(); ?>"></script><!-- the time() stops it cache-ing -->
This third file is my PHP/MYSQL file that I use to connect to the database.
<?php
$mysqli = new mysqli_connect("127.0.0.1", "root", "", "gurstang");
$id = $_POST['id'];
if(isset($_POST['x'])) {
$x = true;
}else{
$x = false;
}
$userid = 1;
$query = "SELECT * FROM `action_info` WHERE `actionid` = '$id'";
if($result = $mysqli->query($query)){
while ($row = $result->fetch_assoc()) {
$action_name = $row['name'];
$basetimer = $row['time'];
$gaineditem = $row['itemid'];
}
$result->free();
}
$query = "SELECT `item`,`plural` FROM `items` WHERE `itemid` = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$gained_item = $row['item'];
$gained_plural = $row['plural'];
}
$result->free();
}
if($x == false){
echo "Action|$id|"5"";
$message = "You have begun working.";
echo "AlterDiv|message|$message";
}
if($x == true){
echo "Action|$id|"5"";
$itemnumber = mt_rand(1,2);
$gainedmessage = "You have gained $itemnumner $gained_item.";
echo "AlterDiv|message|$gainedmessage";
$query = "SELECT `count` FROM inventory WHERE userid = '$userid' AND itemid = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$count = $row['count'];
$add = $count + $itemnumber;
$updatequery = "UPDATE `inventory` SET `count` = '$add' WHERE `userid` = '$userid' AND `itemid` = '$gaineditem'";
$mysqli->query($updatequery);
}
}
else{
$insertquery = "INSERT INTO `inventory` (`userid`, `itemid` ,`count`) VALUES ('$userid', '$gaineditem', '1')";
$mysqli->query($insertquery);
}
}
?>
Those are all 3 of the file currently to run my script. I have an onclick event in the php webpage, and it sends the values to my Javascript function of Game.Action. After testing I have concluded or at least assume that my Javascript function for Game.Action works. After testing my Game.ServerRequest function, I have concluded that there is a change somewhere happening. Although, when I check my server to see if the updates actually happened, nothing happens. It doesn't update the timer div or the message div properly.
So basically my question is, is my issue with PHP/MYSQL or AJAX?
Thanks for your help.