Pass values using JSON via Ajax Call - javascript

I am beginner on JSON. In my web application I am trying convert the table values into JSON and pass to another page using ajax call.
Below is my ajax query which I tried to convert the table values and pass to prescription.php page to save the records. There are two different separate java script variables which need to sent to the above page.
<script>
$(document).ready(function () {
$(document).on('click', '#submit', function () {
var getapt = $('#getapt').val();
var getpid = $('#getpid').val();
var ids={
'getapt': getapt,
'getpid': getpid,
}
var modess = $('#rows tr').map(function() {
let $tr = $(this);
return [{
"medname": $(this).find('.med_name').val(),
"morning": $(this).find('.morning').val(),
"noon": $(this).find('.noon').val(),
"night": $(this).find('.night').val(),
}]
console.log(modess);
});
var ids = JSON.stringify(ids);
var medical = JSON.stringify(modess);
$.ajax({
url: "adminquery/prescription.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{
index1: medical,
index2: ids
},
dataType:'json',
cache: false,
contentType: false,
processData: false,
async: false,
//contentType: "application/json; charset=utf-8",
})
});
});
</script>
Here is my prescription.php page
<?php
session_start();
require_once "../auth/dbconnection.php";
// if (isset(json_decode($_POST["data"])) {
$medical = json_decode($_POST["data"]);
if($stmt = mysqli_prepare($conn,"INSERT INTO prescription (apt_id,user_id,p_id, med_records,date) VALUES (?, ?, ?, ?, ?)")){
$user_id = $_SESSION['user_id'];
mysqli_stmt_bind_param($stmt, "sssss", $user_id);
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// }else{
// echo "now records";
// }
mysqli_stmt_close($stmt);
?>
Here is my HTML codes.
<form method="post" id="prescriptionn" enctype="multipart/form-data">
<div class="table-responsive">
<table class="table table-bordered mb-0" id="medical">
<thead>
<tr>
<th>Medicine Name</th>
<th>Morning</th>
<th>Noon</th>
<th>Night</th>
<th> <button type="button" name="add" id="add" class="btn btn-success btn-xs">
+ </button> </th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
<br><br>
<div align="center">
<input type="hidden" value="<?php echo $row['apt_id'] ?>" id="getapt"
name="getapt" class="btn btn-primary">
<input type="hidden" value="<?php echo $row['p_id'] ?>" id="getpid" name="getpid" class="btn btn-primary">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="Enter Prescription">
</div>
</div>
</form>
But nothing happen when I submit the button. Please give me some suggestions to improve my code may highly appreciated.

Following Method show how to send HTML table data using jQuery Ajax and save in Database. Hope this will help.
function storeTblValuesSpecial(x)
{
var TableData = new Array();
$('#'+x+''+' tr').each(function(row, tr){
TableData[row]={
"columOne" :$(tr).find('td:eq(1)').text()
, "columTwo" : $(tr).find('td:eq(2)').text()
, "columThree" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function storeTblValuesAjax(y) {
var TableData;
TableData = JSON.stringify(storeTblValuesSpecial(y));
$.ajax({
type: "POST",
url: '../yourFile.php',
data: {
"pTableData" : TableData
},
success: function(msg){
alert('Success');
}
});
}
<table id="table1" class="table table-dark" border="1">
<thead>
<tr>
<th scope="col">columOne</th>
<th scope="col">columTwo</th>
<th scope="col">columThree</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" class="btn-danger" id = "delete" onclick="storeTblValuesAjax('table1')" >Save Table</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
From PHP File once the Post Request Sent through Ajax Call
<?php
session_start();
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);
// Decode the JSON array
$records = json_decode($tableData,TRUE);
$sizeOfArray = sizeof($records);
for($test = 1; $test < $sizeOfArray; $test++)
{
$columOne= str_replace(",","",$records[$test]['columOne']);
$columTwo= str_replace(",","",$records[$test]['columTwo']);
$columThree= str_replace(",","",$records[$test]['columThree']);
/* From Here a general SQL Insert query , pass $columOne , $columTwo , $columThree as the insert values, the loop will continue until the entire table is saved */
}

Related

Unable to fetch data from database using ajax function Laravel

I am trying to fetch data from the database using ajax call, but my function in jquery is not working for fetching the data and I am getting an error "data is not defined". I don't know what goes wrong. I am trying to fetch all data from the database table and display it on the screen Here is my controller
<?php
namespace App\Http\Controllers;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
use Illuminate\Support\Facades\Validator;
class SearchPatient extends Controller
{
function action(Request $request)
{
if ($request->ajax())
{
$query= $request->get('query');
if ($query != '')
{
$data = DB::table('patients')->first()
->where('patientid','like','%'.$query.'%' )
->orWhere('fname','like','%'.$query.'%')
->orWhere('lname','like','%'.$query.'%')
->orWhere('contactno','like','%'.$query.'%')
->orWhere('gender','like','%'.$query.'%')
->orWhere('cnic','like','%'.$query.'%')
->orWhere('city','like','%'.$query.'%')
->orWhere('address','like','%'.$query.'%')
->get();
}
else
{
$data = DB::table('patients')->first()
->orderBy('created_at', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>
'.$row->patientid.'
</td>
<td>
'.$row->fname.'
</td>
<td>
'.$row->lname.'
</td>
<td>
'.$row->cnic.'
</td>
<td>
'.$row->gender.'
</td>
<td>
'.$row->address.'
</td>
<td>
'.$row->contactno.'
</td>
<td>
'.$row->city.'
</td>
<td>
'.$row->created_at.'
</td>
</tr>
';
}
}
else
{
$output='
<tr>
<td align="center" colspan="5">
No Data Found
</td>
</tr>';
}
$data = array(
'table_data' => $output,
'table_data' => $table_data
);
echo json_encode($data);
}
}
}
Here is my ajax function
$(document).ready(function() {
fetch_patients('');
function fetch_patients(query = '')
{
$.ajax({
URL:"/action",
method: 'GET',
data: {query:query},
dataType: 'json',
success: function(data)
{
$('tbody').html(data.table_data);
$('total-patient-records').text(data.total_data);
}
})
}
$(document).on('keyup', '#searchpatient', function(){
var query = $(this).val();
fetch_patients(query);
})
});
Here is my route
Route::get('/action', [SearchPatient::class, 'action'])->name('action');
Route:: get ('/SearchPatient',function(){
return view ('SearchPatient');
});
Here is my blade file
<div class="container box">
<h3 align="center">Search Patient</h3><BR>
<div class="panel panel-default">
<div class="panel-heading">
Search Patient Data
</div>
<div class="panel-body">
<input type="text" name="searchpatient" id="searchpatient" class="form-control" placeholder="Search Patient">
</div>
<div class="table-responsive">
<h3 align="center">Total Data : <span id="total-patient-records"></span></h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Patient ID</th>
<th>Name</th>
<th>CNIC</th>
<th>Gender</th>
<th>Address</th>
<th>Contact No</th>
<th>City</th>
<th>Last Visit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
You have error in your code, double key 'table_data' and undefined variable $table_data
//Jquery
var data = {
"_token": $('input[name=_token]').val(),
query:query
};
$.ajax({
URL:"/action",
method: 'GET',
data: data,
dataType: 'json',
success: function(data)
{
$('tbody').html(data.table_data);
$('total-patient-records').text(data.total_data);
}
})
//controller
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json(['data' => $data]);
var url = '{{ route('get_products') }}';
var data = {
"_token": $('input[name=_token]').val(),
};
$.ajax({
type: "get",
url: url,
data: data,
success: function(response) {
alert(response.data);
}
});
<------ controller ------>
public function get_products()
{
$data = DB::table('products)->get();
return response()->json(['data' => $products]);
}
here is the issue in the document-ready method the data variable is used but Never initialize before using it.
The solution in to pass fetch_patients('') an empty string in your method, instead of data (an undefined variable)

PHP / AJAX checkbox values

I'm trying to get all checked checkbox values and parse them to my php functin using AJAX.
I use foreach to try and get each id of the checked checkbox's.
My problem is that when I try and update the database, it doesn't return '1' which I echo upon success.
When I take my foreach code out, it works.
My delete button is :
<form class="form -dark" id="form-inline" method="POST">
<div class="btn-group">
<button type="button" onclick="deleteSelectedTokens()" class="btn -dark" style="margin-left: 5px;" title="Delete all selected tokens"><i class="fa fa-trash"> </i></a>
</div>
</form>
My checkbox html/php code is :
<table class="table -dark -striped">
<thead>
<tr>
<th style="text-align: center;"><input type="checkbox" id="selectall"/></th>
<th style="text-align: center;">Token</th>
<th style="text-align: center;">Date/Time Generated</th>
<th style="text-align: center;">Status</th>
<th style="text-align: center;">Durbaility</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$username = $_SESSION['username'];
$token_result = mysqli_query($con, "SELECT id, token, used, time_generated, durability FROM tokens WHERE user_id = '$username' ORDER BY used");
if(mysqli_num_rows($token_result) > 0) {
while($token_row = mysqli_fetch_array($token_result)) {
$result = array($token_row['durability']); $sub_struct_month = ($result[0] / 30) ; $sub_struct_month = floor($sub_struct_month); $sub_struct_days = ($result[0] % 30); $sub_struct = "<i>".$sub_struct_month."</i> month(s) <i>".$sub_struct_days."</i> day(s)";
echo '
<tr style="text-align: center;">
<td>
<center><input type="checkbox" id="checkedTokens" class="checkbox" value='.($token_row['id']).'></center>
</td>
<td>
'.$token_row['token'].'
</td>
<td>
'.($token_row['time_generated']).'
</td>
<td>
'.($token_row['used'] == "0" ? "<span class='label label-primary'><i class='fa fa-check'></i> Valid </span>" : "<span class='label label-primary'><i class='fa fa-fa fa-times'></i> Used </span>").'
</td>
<td>
'.$sub_struct.'
</td>
';
} }else{ ?>
<tr>
<td colspan="12" style="padding: 30px;">
<div class="alert -dark">
<div class="alert-icon _text-danger">
<i class="fa fa-exclamation-circle"></i>
</div>
No tokens in your account
</div>
</td>
</tr>
<?php } ?>
</tr>
</tbody>
Notice I need to use foreach to get each check checkbox value so I can remove the selected ones when I press the delete button.
My AJAX send to PHP function is :
<script>
function deleteSelectedTokens() {
var selectedTokens = document.getElementById("checkedTokens").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: selectedTokens
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
I think the problem is the Javascript... when I get the value of the checkboxes and post them, i think it's only getting 1 value inside the checkedTokens id.
My php receive code (this is not the problem) :
$username = $_SESSION['username'];
$selectedTokens = mysqli_real_escape_string($con, $_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
My console.log has not errors. Like I said, i think it's the javascript code for getting the value of my checkbox's not getting all the values.
You can send json of checked items:
<script>
var selectedTokens = [];
$('#checkedTokens:checked').each(function(key, value){
selectedTokens.push($(value).val());
});
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: JSON.stringify(selectedTokens)
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
</script>
And your php code mysqli_real_escape_string give only string we should convert json to get array:
$selectedTokens = json_decode($_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
In html it is not allowed to assign the same id to multiple tags. (As already mentioned in the comments.)
If you place your checkboxes on a <form id="some_id">, and give every checkbox a unique name and id, you can use the function $('#some_id').serialize() to get the data of the form and post it to the server.

Refresh table after ajax POST based on search criteria

All,
I have a modal that contains a table with results from a PHP query using PHP include, the problem is as the modal is loaded when the page if first opened, I appear to be unable to use an AJAX post later on to refresh the table based on a textbox variable.
Here is my code
HTML
<div class="modal-content">
<div class="modal-header">
<span class="close">x</span>
</div>
<div class="modal-body">
<div id="divSearchResultsTable">
<table class="tblSearchResults" id="tblSearchResults">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Home</th>
<th>Mobile</th>
<th>City</th>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<?php
include("sql_search.php");
?>
<tbody>
</table>
</div>
<div id="divSearchResultsButtons">
<input type="button" class="btnOpen" id="btnOpen" name="btnOpen" value="Open" disabled="true"/>
&nbsp
<input type="button" class="btnClose" id="btnClose" name="btnClose" value="Close"/>
</div>
</div>
</div>
JavaScript
$(function(){
$('#btnSearch').click(function(e){
var modal = document.getElementById('modal');
var value = $("#txtSearch").val();
$.ajax({
type : "POST",
url : "sql_search.php",
data : {value:value},
success : function(output) {
alert(output);
modal.style.display = 'block';
modal.focus();
}
});
});
});
PHP (sql_search.php)
$value = (isset($_POST['value']) ? $_POST['value'] : null);
if ($value == null){
$sql = "SELECT * FROM helpdesk";
}
else{
$sql = "SELECT * FROM helpdesk WHERE ID = $value";
}
$result = mysqli_query( $conn, $sql);
while( $row = mysqli_fetch_array($result))
{
echo '<tr>';
echo '<td>'.$row['ID'].'</td>' . '<td>'.date("d/m/Y g:i:s A", strtotime($row['DateCreated'])).'</td>' . '<td>'.$row['Priority'].'</td>' . '<td>'.$row['Company'].'</td>' . '<td>'.$row['Name'].'</td>' . '<td>'.$row['Subject'].'</td>' . '<td>'.$row['Name'].'</td>';
echo '</tr>';
}
The result I am getting is every database item returned. I've used alert(output) in my AJAX success to confirm the varible is actually being passed, so I think I now just need to work out how to get the table to update.
Any advice?
Thanks
Don't include your PHP file in html, but assign an id to the element where you'd like to have its output. Then in Javacsript, populate the content with the data returned by AJAX call.
<div class="modal-content">
<div class="modal-header">
<span class="close">x</span>
</div>
<div class="modal-body">
<div id="divSearchResultsTable">
<table class="tblSearchResults" id="tblSearchResults">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Home</th>
<th>Mobile</th>
<th>City</th>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody id="modalContent">
<!-- note, no content and tbody has an ID -->
<tbody>
</table>
</div>
<div id="divSearchResultsButtons">
<input type="button" class="btnOpen" id="btnOpen" name="btnOpen" value="Open" disabled="true"/>
&nbsp
<input type="button" class="btnClose" id="btnClose" name="btnClose" value="Close"/>
</div>
</div>
</div>
And the javascript code:
$(function(){
$('#btnSearch').click(function(e){
var modal = document.getElementById('modal');
var value = $("#txtSearch").val();
$.ajax({
type : "POST",
url : "sql_search.php",
data : {value:value},
success : function(output) {
alert(output);
$('#modalContent').html(output); // <------
modal.style.display = 'block';
modal.focus();
}
});
});
});
BTW, your PHP code is unsafe as it uses its parameter directly in SQL query without validation or type casting (SQL injection) and outputs data from database without escaping html (stored HTML/Javascript injection). Consider using PDO with parameters - http://php.net/manual/en/pdostatement.bindparam.php and wrap database output values into htmlspecialchars() call

Display ajax response in Table

display.html :
<div id="display_result" style="display: none"><table class="table">
<p style="float: right;" >Select All<input type="checkbox" class="allcb" data-child="chk" checked/> </p>
<thead>
<tr>
<th>Die No</th>
<th> Status </th>
<th> Location </th>
<th>Select</th>
</tr>
</thead>
<tbody>
</table>
<div id ="issue_button">
<input type="submit" id="submit" class="btn btn-success " value="Recieve" style="width: 150px;"></div>
</div>
Ajax:
var data = JSON.stringify($("#form").serializeArray());
// alert(data);
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: 'POST',
data: {
list: data
},
url: 'die_recieving_process.php',
success: function(data) ){
$('#display_result').html(data);
}
});
die_recieving_process.php
while($fetch = mysql_fetch_array($query))
{
if($fetch[1] == "Table Rack" )
{
echo '<tr class="success"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] </td> </tr>';
}
else
{
echo '<tr class="warning"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] checked </td> </tr>';
}
}
Hi friends in display.html I have to display the result processed in die_recieving_process.php . In ajax i've sent all the value to die_recieving_process.php and after fetching the result i've to display the result in display.html
First in you Javascript, you have 2 errors:
Your code overrides existing contents of div, which is the whole table...
And you have one unnecessary bracket in success function declaration
So change this:
success: function(data) ){
$('#display_result').html(data);
}
To this:
success: function(data) {//remove unnecessary bracket
$('#display_result tbody').html(data);//add data - to tbody, and not to the div
}
By the way, using $.post() you can write your javascript code shorter, like this:
var data = JSON.stringify($("#form").serializeArray());
$.post('die_recieving_process.php',{list:data},function(responseData){
$('#display_result tbody').html(responseData); //added to tbody which is inside #display_result
$('#display_result').show();
});
Second you need to close your tbody tag inside the table
Create html table with empty body tags and body id = tBody for example:
<table>
<caption>Smaple Data Table</caption>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
Use the jquery ajax to load json data in the created table after load button is clicked assuming that my json file is storing userData like userName, age, city:
$('#btnLoadAll').click(function () {
$.ajax({
url: "url/data.json",
dataType: 'json',
success: function (resp) {
var trHTML = '';
$.each(resp, function (i, userData) {
trHTML +=
'<tr><td>'
+ userData.userName
+ '</td><td>'
+ userData.age
+ '</td><td>'
+ userData.city
+ '</td></tr>';
});
$('#tBody').append(trHTML);
},
error: function (err) {
let error = `Ajax error: ${err.status} - ${err.statusText}`;
console.log(error);
}
})
});
If you do not see result, try to remove style="display: none" in display.html

Ajax and PHP return data to table cell

New to PHP/MySQL here and I have been trying to learn some Ajax.
I want to return some JSON (one figure e.g 12345) to a $variable and echo this variable in in a single table cell. (There may be better ways to do this however I just want to know how it's done - if at all possible!)
So far I can retrieve the JSON figure and display it within a <div id="result"></div> using the code below, so I know the request works - I'm just stuck at passing the variable part.
My response (in Chrome) looks like this;
My code so far is;
chartAjax.php
<form method="post" id="search">
<input type="text" id="date" name="date">
<input type="submit" value="Submit">
</form>
<div id="result"></div> <!-- this successfully displays the figure on submit -->
<table id="datatable" class="table">
<tbody>
<tr>
<th>Data</th>
<td>{NEED TO echo the $result here}</td> <!-- stuck here -->
</tr>
</tbody>
</table>
monthConn.php
<?php
/* set header type to json */
header('Content-Type: application/json');
/* array to pass back data */
$data = array();
/* get date from form submit */
if (isset($_POST['date']) && !empty($_POST['date'])){$date = $_POST['date'];}
/* Create a prepared statement */
$stmt = $conn -> prepare("SELECT count(*) FROM transactions WHERE TimeStamp >= ?");
/* Bind parameters */
$stmt -> bind_param("s", $date);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($data);
/* fetch values */
$stmt->fetch();
/* close conn */
$stmt->close();
echo json_encode($data);
?>
My JS (contained within chartAjax.php page above)
<script>
$(document).ready(function() {
$('#search').submit(function(event) {
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
ajaxRequest= $.ajax({
url: "monthConn.php",
type: "post",
data: values,
success: function(response, data) {
if(data == "success") {
$("#result").html(response); //add response to results div
}
},
});
});
});
</script>
Apologies if the code/methodology is very amateur, any help or suggestions would be welcome!
Try this
add this (AS count)
$stmt = $conn -> prepare("SELECT count(*) AS count FROM transactions WHERE TimeStamp >= ?");
then apply this
//just incase you want to return more than 1 value in the future
return json_encode(array('count' => $data));
then in your
if(data == "success") {
var return_data = $.parseJSON(response);
$("#datatable").html(return_data['count']);
}
<table id="datatable" class="table">
<tbody>
<tr>
<th>Data</th>
<td id="response"></td>
</tr>
</tbody>
</table>
you are selecting an element with id result to show your response, please update the td id
<form method="post" id="search">
<input type="text" id="date" name="date">
<input type="submit" value="Submit">
</form>
<table id="datatable" class="table">
<tbody>
<tr>
<th>Data</th>
<td id="result">{RETURNED JSON FIGURE HERE}</td> <!-- stuck here -->
</tr>
</tbody>
</table>

Categories