I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
Related
In my web application just I trying to returning JSON data from MySQL database using PHP and AJAX query. This is where I follow a tutorial on internet. In case in my application it shows and error like;
data = "↵↵↵↵Notice: Undefined index: lymph in
C:\xampp\htdocs\Hospital\hospitalwebsite\test_query\fetch_count.php
on line 29
Here is my AJAX Code :-
<script>
$(document).ready(function () {
$('select').material_select();
$('#search').click(function () {
var id = $('#test_list').val();
if (id != '') {
$.ajax({
url: 'test_query/fetch_count.php', // Url to which the request is send
method: 'POST', // Type of request to be send, called as method
data: { id: id },
//dataType:"JSON",
success: function (data) {
$('#success_mes').fadeIn().html(data);
$('#test_info').css('display', 'block');
$('#1').text(data.WBC);
$('#2').text(data.lymph);
$('#3').text(data.Mid);
}
});
} else {
alert('sdsd');
$('#test_info').css('display', 'none');
}
});
});
</script>
Below is the PHP Code :-
<?php
session_start();
require_once "../phpquery/dbconnection.php";
if (isset($_POST['id'])) {
//$id = $_POST['id'];
$stmt = $con->prepare("SELECT * FROM testing_report WHERE testing_report_id = ? AND test_id='7' ");
$stmt->bind_param("s", $_POST['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0);
while ($row = $result->fetch_assoc()) {
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
foreach ($medRecords as $key => $object) {
$data["WBC"] = $object['WBC'];
$data["lymph"] = $object['lymph'];
$data["Mid"] = $object['Mid'];
}
}
}
echo json_encode($data);
}
?>
SQL schema
Really I am appreciating if someone can help me. Thank you
The issue is that your data structure is split over several array elements, something like...
[
{
"WBC": "1"
},
{
"lymph": "5"
}
]
so each loop round the array only has 1 piece of information. This code combines all of that data into 1 set of information using array_merge() and then extracts the data from the result.
I've also added ?? 0 to default the values to 0 if not present, there may be a better default value.
$data = [];
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
$medRecords = array_merge(...$medRecords);
$data["WBC"] = $medRecords['WBC'] ?? 0;
$data["lymph"] = $medRecords['lymph'] ?? 0;
$data["Mid"] = $medRecords['Mid'] ?? 0;
}
JQuery work file if the result be json:
$(document).ready(function(){
$('#search').click( function () {
$.ajax({
url: "https://reqres.in/api/users?page=2",
method: "GET",
success:function(data)
{
console.log("page:", data.page);
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="search">Search</button>
i think you have to add correct header to your result:
<?php
header('Content-Type: application/json');
add this code into first line of your php page. then jQuery know result is json.
I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...
I've got this code
Javascript
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data;
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});
That is trying to get some table numbers, but when this really works it shows me the parameter name and the value, i need only the value, what can i do to get only the value so not the parameter name?
I'm using PHP as database connector.
PHP Code
<?php
include('base.php');
$data = array();
$result = mysql_query('SELECT table_number FROM waiters_assigned ORDER BY id',$connect);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
} else {
echo "0 results";
};
echo json_encode($data);
mysql_close($connect);
?>
The result is this one: {"table_number":"3"} what i need is just: 3
Firstly, please dont use mysql_query you should have a look at PDO or at the very least mysqli, for security and because it is deprecated.
As for returning just the number, update your while to return the field you desire:
while($row = mysql_fetch_assoc($result)){ $data[] = (int)$row['table_number']; }
When looking at your PHP i believe you're actually getting [{"table_number":"3"}], as you're json_encodeing an array.
The reason updating your PHP is better than updating your Javascript is that you appear to be returning an array of objects currently, when you actually want to return an array of numbers. Doing things the JS way you'll need to cycle through the response, parseInt on the strings, and strip the object down to a number. Far easier and more efficient to just send the correct data.
In your php code use mysqli or pdo extension because mysql extension is deprecated.
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data.table_number;//outputs 3
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});
It's very simple:
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data ? "" + response.data.table_number : "";
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});
I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.
I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});