How to fetch data to jquery dataTable with form submit - javascript

I am inserting data with jquery Ajax using form submit, And fetching data to dataTable after form submit, following code giving DataTables warning: table id=mainTable - Requested unknown parameter '1' for row 0, column 1. . . . .
var mainTable = $('.mainTable').DataTable();
$('#Form').submit(function(e) {
e.preventDefault();
var form = $(this).serialize();
$.ajax({
url: "result.php",
type: "post",
data: form
}).done(function (data) {
mainTable .clear().draw();
mainTable .rows.add(data).draw();
}).fail(function (jqXHR, textStatus, errorThrown) {
});
});
HTML
<div class="content">
<!-- form start -->
<form method="post" id="Form">
<input type="text" name="id">
<input type="text" name="name">
<input type="text" name="class">
<button type="submit">submit</button>
</form>
<table id="mainTable" class="mainTable table table-striped">
<thead>
<tr>
<th>Roll No</th>
<th>Name</th>
<th>class</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
PHP
$id = $_POST['group_id'];
$rollno = $_POST['roll_no'];
$name = $_POST['name'];
$class = $_POST['class'];
$insert = "insert into students (roll_no,group_id,name,class) values(:roll_no,:id,:name,:class)";
$insert = $db->prepare($insert );
$insert ->bindParam(':roll_no',$rollno);
$insert ->bindParam(':id',$id );
$insert ->bindParam(':name',$name);
$insert ->bindParam(':class',$class);
$insert ->execute();
$fetch = "SELECT roll_no,name,class FROM students where group-id=:id";
$fetch = $db->prepare($fetch );
$fetch ->bindParam(':id',$id);
$fetch ->execute();
$output = array('data' => array());
while($row = $fetch ->fetch(PDO:: FETCH_OBJ)) {
$id = $row->roll_no;
$name = $row->name;
$class = $row->class;
$output['data'][] = array( $id,$name,class);
} // /while
echo json_encode($output);

Moved from comment
The root cause is simply because jQuery ajax() doesn't parse the JSON response from result.php. The easiest solution is to parse it inside done():
data = JSON.parse(data);
mainTable.rows.add(data.data).draw();
Another solution is to properly return JSON header in result.php. Line data = JSON.parse(data) in done() should also be omitted:
header('Content-Type: application/json');
echo json_encode($output);

Related

Live data search using ajax. How to display another query when input is empty [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am trying to create a live search using ajax, jquery, php and mysql.
The user enter some inputs, it send the search to form_livesearch.php. I got that part worked. Else if the input is empty, then display other query. (I need help with this part)
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
$(document).ready(function(){
$("#live_search").keyup(function(){
var input = $(this).val();
if(input != ""){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
} else {
// If the input field is empty
// How display another php query here?
}
});
});
Here is the php and mysql I am trying to display when the input field is empty.
<?php
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(!$result){
die("Query Failed " . mysqli_error($db));
}
if(mysqli_num_rows($result) > 0){
?>
<h3>Policies</h3>
<ul>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<li><?php echo $s_name?> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>
<?php
}
?>
</ul>
<?php
}
?>
form_livesearch.php:
if(isset($_POST['input'])){
$input = $_POST['input'];
//to prevent from mysqli injection
// x'='x
$input = stripcslashes($input);
$input = mysqli_real_escape_string($db, $input);
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE '%{$input}%' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(mysqli_num_rows($result) > 0){?>
<table class="table table-bordered table-striped mt-4">
<!--
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
-->
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<tr>
<td style="font-size: 14px;"><?php echo $s_name;?> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You should handle this stuff in the PHP file. and by the way, the input can not be empty as you put the ajax in keyup event.
it just happened when the user use the backspace to delete what he search.
So the form_livesearch.php PHP file should be something like this.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$output = "";
if(isset($_POST['input'])){
$input = $_POST['input'];
if(!empty($input)){
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$input = "%$input%"; // prepare the $input variable
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE ? ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $input); // here we can use only a variable
$stmt->execute();
}else{
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->execute();
}
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows > 0){
if(empty($input))
$output = '<table class="table table-bordered table-striped mt-4"><tbody>';
else
$output = '<h3>Policies</h3><ul>';
while($row = $result->fetch_assoc()){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
if(empty($input))
$output .= '
<tr>
<td style="font-size: 14px;">' . $s_name .' <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>';
else
$output .= '<li>' . $s_name . ' <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>';
}
if(empty($input))
$output .= '</tbody></table>';
else
$output .= '</ul>';
echo $output;
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You can use a separate file to handle 2 types but as they are all about products it's better to have one file.
It's a good practice to return the data and let the frontend build the HTML output but if you want to build HTML in the PHP file, it's better to wrap them in a string.
Also, use the prepare statement of MySQLi to prevent SQL injection. take a look at this example for more information.
And the html file should be something like this:
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// will execute once the page load
getData();
$("#live_search").keyup(function(){
let input = $(this).val();
getData(input);
});
});
function getData(input = ''){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
}
</script>

Error In Displaying Data Records from Database on the console in Json Data format using Ajax in php

I am trying to display database records to my console in json format but i can't see why my request in json format is not being displayed on my console. There is no error also to guide me where i made a mistake. can someone help me. I use the MVC framework for writing my code. I want to retrieve horse names based on race number from the race table in the database.
here is my home.php
<div class="box-body">
Start creating your amazing application!
<table class="table table-bordered table-striped dt-responsive tables" width="100%">
<thead>
<tr>
<th style="width:10px">#</th>
<th>id</th>
<th>Race Number</th>
<th>Horse Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$users = ControllerUsers::ShowallUsersCtr();
foreach ($users as $key => $value) {
echo '
<tr>
<td>'.($key+1).'</td>
<td>'.$value["id"].'</td>
<td>'.$value["racenumber"].'</td>
<td>'.$value["horsename"].'</td>';
echo '<td>
<div class="btn-group">
<button class= "btn btn-primary btnAddRace" RaceNumber="'.$value["racenumber"].'" data-toggle="modal" data-target="#editUser">Add Horse - Race 1</button>
</div>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
here is my javascript file code named users.js
$(document).on("click", ".btnAddRace", function(){
var RaceNumber = $(this).attr("RaceNumber"); // capture the race number from database to the console
console.log("RaceNumber",RaceNumber);
var data = new FormData();
data.append("RaceNumber",RaceNumber);
$.ajax({
url: "ajax/users.ajax.php",
method: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(answer){
console.log("answer", answer); // bring from the database whatever we asked for
}
});
});
And here is my Ajax file users.ajax.php
<?php
require_once "../controllers/users.controller.php";
require_once "../models/users.model.php";
class AjaxUsers{
public $RaceNumber;
public function ajaxEditUser(){
$item = "racenumber";
$value = $this->RaceNumber; // value what is selected from the table
$answer = ControllerUsers::ctrShowUsers($item, $value); // ask for the controller to show me the race table
echo json_encode($answer);
}
}
if (isset($_POST["RaceNumber"])) { // if the variable race number comes with information, we can execute all of this
$edit = new AjaxUsers();
$edit -> RaceNumber = $_POST["RaceNumber"];
$edit -> ajaxEditUser();
}
here is my user controller and model methods
static public function ctrShowUsers($item, $value){
$table = "race";
$answer = UsersModel::MdlShowUsers($table, $item, $value);
return $answer;
}
static public function MdlShowUsers($table, $item, $value){
$stmt = Connection::connect()->prepare("SELECT * FROM $table WHERE $item = :$item");
$stmt -> bindParam(":".$item, $value, PDO::PARAM_INT);
$stmt -> execute();
return $stmt -> fetch();
$stmt -> close();
$stmt = null;
}
Database Picture is here
enter image description here

How to access array in if statement?

I have an admin panel for an application. For this admin panel, the admin has the option to select a user from a dropdown list. When the user is selected, I use an AJAX call to grab the users data and store it in a variable called $result. Now when I try to access $result outside of the if statement in my HTML file, it is not recognized. What are the possible ways I can access this variable?
HTML file (AJAX call)
$(document).ready(function(){
$('#user').change(function() {
var user_id = $(this).val();
$.ajax({
url: 'adminNew.php',
method:'POST',
data: {user_id : user_id},
success: function(data) {
alert(user_id);
}
});
});
});
Php file (if statement)
if (isset($_POST["user_id"])) {
if ($_POST["user_id"] != '') {
$sql = "SELECT * FROM user_data WHERE user_id ='".$_POST["user_id"]."'";
}
$result = mysqli_query($connect, $sql);
}
HTML file (table)
<tr>
<tbody id="expBody">
<?php
if ($result != ''){
while($row1 = mysqli_fetch_array($result)) {
echo '
<tr id = '.$row1["id"].'>
<td> '.$row1['user_id'].'</td>
<td> '.$row1['name'].'</td>
<td> '.$row1['email'].'</td>
<td> '.$row1['city'].'</td>
<td> '.$row1['state'].'</td>
<td> '.$row1['zip'].'</td>
';
}
}
?>
</tbody>
</tr>
Your PHP code needs to send something back to the ajax request
i have seen this done as below before
if (isset($_POST["user_id"])) {
if ($_POST["user_id"] != '') {
$sql = "SELECT * FROM user_data WHERE user_id ='".$_POST["user_id"]."'";
}
$result = mysqli_query($connect, $sql);
echo $result;
die;
}
you can load the new table into your #expBody via jquery:
$('#user').change(function() {
var user_id = $(this).val();
$("#expBody").load("yourphpfile.php?userid="+userid);
});
and in your phpfile you actualy "make" the table out of the result..
<?php
$userid = $_GET["userid"];
// make your db query
if ($result != ''){
while($row1 = mysqli_fetch_array($result)) {
echo '
<tr id = '.$row1["id"].'>
<td> '.$row1['user_id'].'</td>
<td> '.$row1['name'].'</td>
<td> '.$row1['email'].'</td>
<td> '.$row1['city'].'</td>
<td> '.$row1['state'].'</td>
<td> '.$row1['zip'].'</td>
';
}
}
?>
that way, this table will be put into your div!

How to delete row after i select the row and press the button

Screenshot
<?php
if(isset($_GET['View']) && $_GET['View']=="HistoryEntry"){
echo '
<h2>History Of Entries</h2>
<table id="table" class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Date In</th>
<th scope="col">Date Out</th>
<th scope="col">Rfid</th>
<th scope="col">Plate #</th>
</tr>
</thead>
<tbody>';
global $connection;
$query = "SELECT * FROM history_entries";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>
<th scope="row">'.$row['Entry_ID'].'</th>
<td>'.$row['Date_in'].'</td>
<td>'.$row['Date_out'].'</td>
<td>'.$row['Acc_rfid'].'</td>
<td>'.$row['Plate_num'].'</td>
</tr>';
}
echo ' </tbody>
</table>
<center>
<button>Delete</button>
</center>
<div class="line"></div>';
}
?>
?>
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
});
$("#Sample").click(function() {
var value = $(".selected th:first").html();
value = value || "No row Selected";
});
As you can see this my codes, i already know how to select the row and get the ID but cant pass the ID "value" to php in order to do the delete function in database. can i use here $.POST function here? or is it better to use GET function here but i think it wouldn't be secure.
This is how you can do it without get param :
1/ Your FRONT :
HTML (just an example)
<table>
<tr id="row_id">
<td>Data 1</td>
<td>Data 2</td>
...
</tr>
...
</table>
<button id="delete_row" type="button">Delete</button>
JS / jQuery
var current_row_id = "";
// You select the row
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
current_row_id = $(this).attr("id"); // Here you get the current row_id
});
// You delete the row
$("#delete_row").on("click", function() {
$.ajax({
type: "POST",
url: "delete.php",
data: {"id" : current_row_id }, // You send the current_row_id to your php file "delete.php" in post method
dataType: 'json', // you will get a JSON format as response
success: function(response){
// you do something if it works
},
error: function(x,e,t){
// if it doesn't works, check the error you get
console.log(x.responseText);
console.log(e);
console.log(t);
}
});
});
2/ Your BACK
PHP "delete.php" file
<?php
$id = $_POST['id']; // You get the 'current_row_id' value
// Now you do your DELETE request with this id :
$sql = "DELETE ... WHERE id = :id";
etc...
$result = array(); // You can prepare your response and send information about what you did
$result['row_deleted'] = $id;
$result['message'] = "The row with id = " . $id . " was deleted with success";
$result['type'] = "success";
//etc....
echo json_encode($result); // You send back a response in JSON format
3/ Back to the FRONT
Your ajax call, the success part :
success: function(response){
// You can display a success message for example using your response :
alert(response.message); // You will get 'The row with id = {the row id} was deleted with success' here for example
},
Is it what you are looking for?
here is a simple Ajax request
var data = {
rowId: 1
};
$.ajax({
type: "POST",// GET|POST
url: 'delete.php', // Where you want to send data like url or file
data: data, // this is what you want to send to server, in this case i send data with id = 1 to server
dataType: 'json' // here we say what data type we want "json"
success: function(response) {
alert(response);
}, // this is the callback were u will get response from your server
});
delete.php here is how u can handle this ajax
$rowId = htmlspecialchars($_POST['rowId']);
if ($rowId) {
global $connection;
$query = "DELETE FROM history_entries WHERE Entry_ID = " . $rowId;
$result = mysqli_query($connection, $query);
$response = array(
'success' => true
);
echo json_encode($response);
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
Hope this will help you to understand how to use Ajax

how should i put data fetched from ajax call in hidden div box

i am working on a project and come across a module.
page1
user have to search from search bar which will take him to page 2.
page2
On page 2 all fetched results will get displayed to user in div's. Each result has a checkbox associated with it.
when i click on add to compare check box ,ajax call is executed and fetched selected result should appear in hidden div.
my problem is it is only shows first result in hidden div and not working with another result.
My code of page 2
<script type="text/javascript">
$(document).ready(function()
{
var check = $('#compare').val();
$("#compare").change(function() {
if(this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').html(data);
}
});
$("#compare_box").show();
}
else
{
$("#compare_box").hide();
}
});
});
</script>
</head>
<body>
<?php
$query = $_GET['search_bar'];
$query = "call fetch_data('$query')"or die(mysqli_error($conn));
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result))
{
$id = $row['course_id'];
$title = $row['course_title'];
$description = $row['course_description'];
$course_url = $row['course_url'];
$video_url = $row['course_video_url'];
$fee = $row['course_fee'];
$duration = $row['course_duration'];
$start_date = $row['course_start_date'];
$university = $row['university_name'];
$course_provider = $row['course_provider_name'];
$instructor = $row['instructor_name'];
$_SESSION['result'][$id] = Array('id'=> $id,'course_title' => $title,'course_description'=> $description,'course_url' => $course_url,'video_url' => $video_url,'fee' => $fee,'course_duration'=>$duration,'start_date'=>$start_date,'university' => $university,'course_provider'=>$course_provider,'instructor'=>$instructor);
?>
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
<?php
}
?>
page3 compare.php
<?php
session_start();
include 'includes/dbconfig.php';
$check = $_POST['value'];
$sql = "SELECT * from course_info_table where course_id = '$check' " or die(mysqli_error($conn));
$result = mysqli_query($conn,$sql);
$index = 0;
while($row = mysqli_fetch_array($result))
{
$title = $row['course_title'];
?>
<?php
}
echo json_encode($title);
?>
You can change
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">
to
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">
^you can only have one unique 'id' value in your html doc, which means your first id="compare" will work fine and others with id="compare" will be ignored by the DOM tree
Reference:
http://www.w3schools.com/tags/att_global_id.asp

Categories

Resources