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.
Related
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);
}
});
}
I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database
This is the view page code in code Igniter.
I am able to populated the second drop down(worker Id) but the problem is, only first data is being fetched. As it has more than 50 worker, only 1 worker id is being fetched.
$(document).ready(function() {
$('#name_of').change(function() {
var Worker_id = $('#name_of').val();
$.ajax({
type:'POST',
data:{data:Worker_id},
dataType:'text',
url:"<?php echo base_url(); ?>supply_chain/get_filtered_names_for_time_card",
success:function(result) {
result = JSON.parse(result);
$('#Worker').empty();
for(i in result) {
$('#Worker').append("<option value='"+result[i]['Worker_id']+"'>"+result[i]['Worker_id']+" "+result[i]['Worker_name']+"</option>")
}
}
});
});
});
This is the Controller function for above View through which I am trying to get all workers related to that required company name.
public function get_filtered_names_for_time_card() {
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data['companyNameOptions'] = [$companyName[$i]];
break;
}
}
echo json_encode($data['companyNameOptions']);
}
It would be a much better idea to make the query select only the row you want but your problem with the code you have written is you over writing the data each time round your loop
Also once you find a company_name you want you terminate the for loop with a break so you will only ever add one to the resulting $data array
public function get_filtered_names_for_time_card()
{
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data['companyNameOptions'][] = $companyName[$i];
// note here ^^
//break;
}
}
echo json_encode($data['companyNameOptions']);
}
Also the $data array does not need to have a sub array so above code can be written more simply and clearly as
public function get_filtered_names_for_time_card()
{
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data[] = $companyName[$i];
}
}
echo json_encode($data);
}
And in your javascript, if you are returning JSON then tell the ajax call that you are doing that and you can forget about the JSON.parse()
$(document).ready(function(){
$('#name_of').change(function(){
var Worker_id = $('#name_of').val();
$.ajax({
type:'POST',
data:{data:Worker_id},
//dataType:'text',
dataType:'json',
url:"<?php echo base_url(); ?>supply_chain/get_filtered_names_for_time_card",
success:function(result)
{
//result = JSON.parse(result);
$('#Worker').empty();
for(i in result){
$('#Worker').append("<option value='"+result[i]['Worker_id']+"'>"+result[i]['Worker_id']+" "+result[i]['Worker_name']+"</option>")
}
}
});
});
});
I'm trying to make a login page that validates the users input data. If "username" and "password" does not match in the database he would receive a warning.
I'm a total newbie when it comes to this, so the code I have now is a combination of different tutorials.
my signin.php looks like this:
header('Content-Type: application/json')
$data = array(); // array to pass back data
if(!empty($_POST["action"]))
{
if($_POST["action"] == "signin")
{
...all the SQL code here...
if(!empty($result))
{
foreach ($result as $row)
{
...some SQL code here...
$data["success"] = true;
$data["message"] = "Success!";
}
}
else
{
$data["success"] = false;
$data["message"] = "Error!";
}
echo json_encode($data);
}
}
Now I want this json data to be used in a jquery submit function that uses ajax to get the data from signin.php:
<script>
$("#login-form").submit(function(event) {
$.ajax({
type : 'POST',
url : 'signin.php',
data : { 'action': 'signin' },
dataType : 'json'
}).done(function(data) {
console.log(data.success);
if(!data.success)
{
alert("ERROR");
}
else if (data.success)
{
alert("SUCCESS");
}
});
event.preventDefault();
});
</script>
How can I see if the update, after JQuery post, is succesfull?
JQuery code:
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(){
});
}
});
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
$this->mgl->mgl_check_paid($code, $id);
}
CI model:
function mgl_check_paid($code, $id){
$q = $this->db->select('*')->from('ad')->where('id_ad', $id)->where('code', $code)->get();
$q_r = $q->row();
if ($q->num_rows() != 0 && $q_r->paid == 0) :
$data['paid'] = 1;
$this->db->where('id_ad', $id);
$this->db->update('ad', $data);
return TRUE;
else :
return FALSE;
endif;
}
I need to check if update is successful and show appropriate message.
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
// could also return a json or whatever info you want to send back to jquery
echo ($this->mgl->mgl_check_paid($code, $id)) ? 'yes' : 'no';
}
Jquery
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(data){
// display the data return here ... simple alert
//$('.result').html(data); // display result in a div with class='result'
alert(data)
});
}
});
You may also want to read more # http://api.jquery.com/jQuery.ajax/ (if you want to do better error checking like failure)
First of all, mad props, I <3 CI and jQuery. Secondly, you need to echo in order to return data to your jQuery post.
Gimmie 5 to fix something at work and i'll edit this answer with more detail.