Can't create table in HTML using AJAX and JSON response - javascript

I'm trying to get data from DB with PHP and export it to JSON file, I'm also trying to display it in my HTML file using AJAX but without success.
I tried to use external JS file and calling for it from Success in AJAX and I tried also to write the function into Success part.
What I did wrong ?
<!DOCTYPE html>
<html>
<head>
<title>DataBase Project - Tom Yahav</title>
<link rel="stylesheet" href="include/style.css"/>
<link rel="stylesheet" href="showTable.js"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<header>
<h1>Database - Students</h1>
</header>
<body>
<div id="wrapper">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header"> </div>
<div>
<ul class="nav navbar-nav">
<li>Home</li>
<li class="active">Add/Remove Students</li>
<li>Add/Remove Teachers</li>
<li>Add/Remove Courses</li>
<li>Top 3 Students</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="insertData">
<form class="form-horizontal">
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student ID:</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="" placeholder="Student ID">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="Student name">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student Address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="Student Address">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Student Birth Date:</label>
<div class="col-sm-10">
<input type="datetime" class="form-control" id="" placeholder="Student Birth Date">
</div>
</div>
<div class="rightButtons">
<button type="button" class="btn btn-success">Add</button>
<button type="button" class="btn btn-danger">Erase</button>
<button type="button" class="btn btn-warning">Update</button>
</div>
</form>
</div>
<br>
<br>
<script>
$(function() {
$("#posts").submit(function() {
var txt = $("#txt").val();
var title = $("#title").val();
var dataString = 'txt=' + txt + '&title=' + title;
$("#loader").show();
$("#loader").fadeIn(300).html('<span class="loading">Loading..</span>');
$.ajax({
type: "GET",
url: "jsonStudent.php",
data: dataString,
cache: true,
success: function(html){
$("#loader").after(html);
$("#loader").hide();
}
});
return false;
});
});
</script>
<form method="post" id="posts" action="">
<input type="submit" value="Display Students" name="submit" class="btnSubmit">
</form>
<div id="loader"></div>
<table id="table1">
<thead></thead>
</table>
</div>
</div>
</body>
</html>
And the External JS file is:
function createTableByForLoop(data)
{
var eTable="<table><thead><tr><th colspan='3'>Created by for loop</th></tr><tr><th>Name</th><th>Title</th><th>Salary</th</tr></thead><tbody>"
for(var i=0; i<data.length;i++)
{
eTable += "<tr>";
eTable += "<td>"+data[i]['name']+"</td>";
eTable += "<td>"+data[i]['title']+"</td>";
eTable += "<td>"+data[i]['salary']+"</td>";
eTable += "</tr>";
}
eTable +="</tbody></table>";
$('#forTable').html(eTable);
}
The PHP file:
function printStudents() {
$host="127.0.0.1";
$port=3306;
$user="root";
$password="root";
$dbname="courcessystem";
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$sql = "SELECT * FROM teacher";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$con->close();
}
printStudents();
?>
Thank you!

Given that jsonStudent.php outputs something like:
[
{
"name": "X",
"title": "X",
"salary": 0
}
]
Change the ajax code to something like this:
$.ajax({
type: "GET",
dataType: "json",
url: "jsonStudent.php",
data: dataString,
cache: false, // You don't want to use cache for this
success: function(data){
createTableByForLoop( data );
$("#loader").hide();
}
});
Also, #forTable doesn't exist in the html.

Related

backend not adding books to android app sql

i have made an ebook android app everything works fine but the backend code of admin age which is written in php and javascript .the admin has a function to add book known as savebook the "savebook" function is not working please help me guys....every time i try to add a book i it just shows a failed message but when i add the book to the database manually via phpmyadmin it works here is the code to that function
the problem is in last function (what is think) but stil i would appreciate if you guys find some other mistake in the code the whole website is working but this only function is not working the app in on android platform the backend is done using codeigniter and the app is linked to a database which maintains the details of book
<?php
$this->load->view('admin/comman/header');
?>
<div class="clearfix"></div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumb-->
<div class="row pt-2 pb-2">
<div class="col-sm-9">
<h4 class="page-title">Add Book</h4>
<ol class="breadcrumb">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item">Books</li>
<li class="breadcrumb-item active" aria-current="page">Add Book</li>
</ol>
</div>
<div class="col-sm-3">
<div class="btn-group float-sm-right">
Books List
</div>
</div>
</div>
<!-- End Breadcrumb-->
<div class="row">
<div class="col-lg-10 mx-auto">
<div class="card">
<div class="card-body">
<div class="card-title">Add Book
<form id="edit_video_form" enctype="multipart/form-data">
<div class="form-group">
<label for="input-1">Book Name</label>
<input type="text" required value="" class="form-control" name="input_name" id="input-1">
</div>
<input type="hidden" name="id" value="">
<div class="form-group">
<label for="input-3">Book Cost</label>
<select name="select_cost" required class="form-control" id="purpose">
<option value="0">Free</option>
<option value="1">Paid</option>
</select>
</div>
<div class="form-group" id="business" style="display:none">
<label for="input-1">Book price</label>
<input type="text" required value="" class="form-control" name="input_price" id="input-1" placeholder="Enter Book Price">
</div>
<div class="form-group">
<label for="input-2">Book Category</label>
<!-- DropDown -->
<select name="select_category" required class="form-control">
<option value="">Select Category</option>
<?php $i = 1;
foreach($categorylist as $cat) { ?>
<option required value="<?php echo $cat->cat_id; ?>"><?php echo $cat->cat_name; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-2">Book Author</label>
<!-- DropDown -->
<select name="select_author" required class="form-control">
<option value="">Select Author</option>
<?php $i = 1;
foreach($authorlist as $cat) { ?>
<option value="<?php echo $cat->a_id; ?>"><?php echo $cat->a_title; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-1"> Book Cover Poster</label>
<input type="file" required class="form-control" name="input_bookcover" id="input-1" placeholder="select Book Cover image"
onchange="readURL(this,'showImage')">
<input type="hidden" name="input_bookcover" value="">
<p class="noteMsg">Note: Image Size must be less than 2MB.Image Height and Width less than 1000px.</p>
<img id="showImage" src="<?php echo base_url() . 'assets/images/placeholder.png'; ?>" height="100" width="100" alt="your image"/>
</div>
<div class="form-group">
<label for="input-1"> Upload Sample Book</label>
<input type="file" required class="form-control" name="input_sample_book" id="input-1" placeholder="select Sample Book">
<input type="hidden" name="input_sample_book" value="">
</div>
<div class="form-group">
<label for="input-1"> Upload Full Book</label>
<input type="file" required class="form-control" name="input_full_book" id="input-1" placeholder="select Full Book">
<input type="hidden" name="input_full_book" value="">
</div>
<div class="form-group">
<label for="input-1">Book Description</label>
<textarea cols="40" rows="5" style="height: 150px" type="text" required value="" class="form-control" name="input_description"
id="input-1"></textarea>
</div>
<div class="form-group">
<button type="button" onclick="savebook()" class="btn btn-primary shadow-primary px-5">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$this->load->view('admin/comman/footerpage');
?>
<script type="text/javascript">
$('#purpose').on('change', function () {
if (this.value === '1') {
$("#business").show();
} else {
$("#business").hide();
}
});
function savebook() {
var wallpaper_title = jQuery('input[name=wallpaper_title]').val();
if (wallpaper_title == '') {
toastr.error('Please enter Book Name');
return false;
}
$("#dvloader").show();
var formData = new FormData($("#edit_video_form")[0]);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>index.php/admin/savebook',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (resp) {
$("#dvloader").hide();
if (resp.status == '200') {
document.getElementById("edit_video_form").reset();
toastr.success(resp.msg, 'success');
setTimeout(function () {
location.reload();
}, 500);
} else {
toastr.error(resp.msg);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#dvloader").hide();
toastr.error(errorThrown.msg, 'failed');
}
});
}
</script>
here is the database code
enter code here
public function savebook(){
$input_name = $_POST['input_name'];
$input_description = $_POST['input_description'];
$input_price = $_POST['input_price'];
$select_category = $_POST['select_category'];
$select_author = $_POST['select_author'];
$select_cost = $_POST['select_cost'];
$is_feature = "yes";
$b_status = "enable";
$fa_id = $_POST['select_author'];
$input_bookcover=$this->imageupload($_FILES['input_bookcover'],'input_bookcover', FCPATH . 'assets/images/book');
if (isset($_FILES['input_sample_book']) && !empty($_FILES['input_sample_book']['name'])) {
$input_sample_book=$this->fileupload($_FILES['input_sample_book'],'input_sample_book', FCPATH . 'assets/images/book');
}
if (isset($_FILES['input_full_book']) && !empty($_FILES['input_full_book']['name'])) {
$input_full_book=$this->fileupload($_FILES['input_full_book'],'input_full_book', FCPATH . 'assets/images/book');
}
$data = array(
'b_title' => $input_name,
'b_description' => $input_description,
'is_paid' => $select_cost,
'sample_b_url' => $input_sample_book,
'b_url' => $input_full_book,
'b_price' => $input_price,
'fcat_id'=> $select_category,
'b_image' => $input_bookcover,
'is_feature' => $is_feature,
'b_status' => $b_status,
'fa_id' => $fa_id,
'b_date' => date('Y-m-d h:i:s')
);
$res_id=$this->Adminmodel->add_book($data);
if($res_id){
$res=array('status'=>'200','msg'=>'Book added successfully.','id'=>$res_id);
echo json_encode($res);exit;
}else{
$res=array('status'=>'400','msg'=>'fail');
echo json_encode($res);exit;
}
}

I have Form validation function in my page but it is not working

I have 3 field first input for image title select for year and input type file for the image. But I want to check image title insert or not while the update button is press. I am using form validation but it's not working.
My code:
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/admin/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<div class="content-wrapper">
<section class="content-header">
<h1><u>Heading </u></h1>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i> Home Content</li>
<li class="active"> Topic </li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 col-lg-12">
<h3 class="page-header"></h3>
</div>
<div class="col-lg-offset-1 col-md-12 col-sm-12 col-xs-12 col-lg-10">
<div class="col-md-12">
<div class="box box-primary">
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">Add Gallary Images</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<form id="add_gallary_form" method="post">
<div class="form-group">
<label>Image Title</label>
<input type="text" class="form-control" name="img_title" id="img_title" placeholder="Enter your Image Title" dir="" autocomplete="off" required>
</div>
<div class="form-group">
<label>Year</label>
<select class="form-control" name="year" id="year" required>
<?php
foreach(range(1950, (int)date("Y")) as $year) {
echo "\t<option value='".$year."'>".$year."</option>\n\r";
}
?>
</select>
</div>
<div class="form-group">
<label>Image</label>
<input type="file" id="upload_image" name="upload_image" class="col-md-8 form-control" multiple />
<div class="form-group">
<div class="col-md-12" id="uploaded_images" ></div>
</div>
</div>
<div class="box-footer">
<button type="submit" id="btn-insert" class="btn btn-success col-lg-8 col-md-offset-2">Insert</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="<?php echo base_url();?>assets/admin/assets/jquery/jquery-3.2.1.min.js"></script>
<script src="<?php echo base_url();?>assets/admin/bootstrap/js/bootstrap.min.js"></script>
<script src="<?php echo base_url();?>assets/admin/plugins/fastclick/fastclick.js"></script>
<script src="<?php echo base_url();?>assets/admin/dist/js/app.min.js"></script>
<script src="<?php echo base_url();?>assets/admin/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<script src="<?php echo base_url();?>assets/admin/dist/js/demo.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/admin/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
<script>
$("#add_gallary_form").validate({
rules:{
"img_title":{
required: true,
},
},
messages:{
"img_title":{
required: "Please Enter Image Title",
},
},
});
</script>
<script type="text/javascript">
$("#btn-insert").click(function(e){
e.preventDefault();
var img_title = $('#img_title').val();
var year = $('#year').val();
if ( $('#upload_image').val() =='') {
alert("Please Select Image File");
}else{
var files = $('#upload_image')[0].files;
var error = '';
var formData=new FormData();
formData.append('img_title',img_title);
formData.append('year',year);
for (var count = 0; count <files.length; count++) {
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if (jQuery.inArray(extension,['gif','png','jpg','jpeg'])== -1) {
error += "Invalid " + count +" Image File "
}else{
formData.append("files[]",files[count]);
}
}
if (error=='') {
$.ajax({
url: "<?php echo base_url();?>admin_controllers/WebsiteContentController/insertImage",
type: "POST",
data: formData,
contentType:false,
cache:false,
processData:false,
beforeSend: function(){
$('#uploaded_images').html("<div style='margin: auto; text-align: center;'><img src='<?php echo base_url();?>/assets/images/uploads/loader.gif'><label class='text-success' align='center'>Uploading...</label></div>");
},
success: function(data)
{
$('#uploaded_images').html(data);
alert('Image successfully added')
setTimeout(function(){location.reload();},1000);
}
});
}else{
alert(error);
}
}
});
</script>
My data is directly inserted without check form validation.
I do not know where I am wrong in my code.
How to validate my image title.
Add the following code just below this var img_title = $('#img_title').val();
if(img_title=="")
{
alert("Enter Image title");
return false;
}
You can do validation in the btn-send button click event.
Try this when you click submit button it works
<script type="text/javascript">
$(function () {
$("#btn-insert").click(function () {
var img = $('#img_title').val();
if(img == ""){
alert("Enter the image name");
return false;
}
return true;});
});
</script>
use this code it will be check img_title variable not null and empty also check undefined.
i hope it's works for you
if(img_title)
{
alert("Enter Image title");
return false;
}

How ajax work in dynamically generated div

I am doing sales of product in which I use AJAX to capture data based on a selection from a dropdown to another one. When I dynamically create a field it works only once i want it to work N number of time.
Here is my HTML & PHP Code:
<div class="row col-md-12 mrg-top-20">
<h4 class="card-title" style="color:#ff0033">Sales Details</h4><br>
<div class="col-md-12"></div>
<div class="row col-md-12" data-duplicate="add">
<div class="col-md-4">
<label>Select <strong>Installation Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="ins_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker">
</div>
</div>
</div>
<div class="col-md-4" id="sel_dynamic">
<div class="form-group">
<label>Select <strong>Manufacturer</strong></label>
<select name="manu" id="manu" class="form-control" style="width:100%">
<option disabled="disabled" selected="selected">Select Manufacturer</option>
<?php
$data = mysqli_query($conn,"SELECT * FROM manufacturer_details");
while($itemcat = mysqli_fetch_array($data))
{
?>
<option value="<?php echo $itemcat['MANUFACTURER_ID']; ?>"><?php echo $itemcat['MANUFACTURER_NAME'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Select <strong>Modal</strong></label>
<select name="modal" id="modal" class="form-control" style="width:100%">
<option value="" selected disabled="disabled">Select Modal...</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Ser<strong>ial</strong></label>
<input type="text" name="serial" placeholder="Enter Serial No" class="form-control">
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC Start Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC End Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_edate" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
</div>
<div>
<input type="button" id="add" data-duplicate-add="add" class="btn btn-info" value="+"/>
</div>
<div >
<input type="button" data-duplicate-remove="add" class="btn btn-info" value="-"/>
</div>
</div>
Here is My Js Script to Call Ajax Each Time
<script type="text/javascript">
$(document).ready(function()
{
$("#sel_dynamic").on("change","#manu",(function() //just try to use on change
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>
Here is my Ajax File
<?php
include('script/db.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysqli_query($conn,"select * from modal_details where MANUFACTURER_ID='".$id."'");
?>
<option selected disabled="disabled">Select Modal Name</option>
<?php
while($row = mysqli_fetch_assoc($sql))
{
$id = $row['MODAL_ID'];
$data = $row['MODAL_NAME'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
Whenever I create a new field dynamically my AJAX is not working.
Try this :
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','#manu',function()
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>
The comments made it clear that you are duplicating your form. I think you have duplicate IDs on your page and your jQuery event will not work anymore. An ID may only occur once.
Take a look here:
Clone form and increment
Add the class to select as shown below:
<select name="manu" id="manu" class="form-control manuClass" style="width:100%">
And use the below script
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','.manuClass',function()
{
var id = $(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$(this).parent().parent().next().children().children("#modal").html(html);
}
});
});
});
</script>

I want to display data from database.if we newly add a form data ,i want to append the new post on display without refresh using codeigniter

I have a show and hide div. That is an add form. I want to display all data from the table on the bottom of the form. If form is opened or not, the data must be displayed. When we add new post, that must append on the top of displayed data without refresh.
My view
<div class="slidingDiv" style="display:none">
<div class="row">
<div class="col-xs-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Requirement Item</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php echo validation_errors(); ?>
<?php
$attributes = array('id' => 'myForm');
echo form_open_multipart(base_url().'moderator/Requirement/add_employee_data',$attributes); ?>
<div class="box-body">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<div class="row">
<div class="col-xs-12">
<label for="txttitle">Requirement Title (Product/Service) : </label>
</div>
<div class="col-xs-12">
<input type="text" name="txtService" class="form-control" id="txttitle" placeholder="Requirement Title (Product/Service) : " value="" required>
</div>
</div>
</div>
</diV>
<div class="col-xs-6">
<div class="form-group">
<div class="row">
<div class="col-xs-8">
<label for="txtquantity">Estimated Quantity : </label>
</div>
<div class="col-xs-4">
<label for="txtquantity"></label>
</div>
<div class="col-xs-8">
<input type="text" name="txtQuantity" class="form-control" id="txtquantity" placeholder="Estimated Quantity" value="
" required>
</div>
<div class="col-xs-4">
<select class="form-control" name="txtunit" required="required">
<option value="">----Select------</option>
<?php
foreach ($units as $name) {
echo ' <option value="' . $name->id . '">' . $name->name . '</option>';
}
?>
</select>
</div>
</div>
</div>
</diV>
<div class="col-xs-12">
<div class="form-group">
<div class="row">
<div class="col-xs-12">
<label for="txtdetails">Requirement Details : </label>
</div>
<div class="col-xs-12">
<textarea class="textarea" name="txtRequirement" placeholder="Requirement Details" id="txtdetails" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;">
</textarea>
</div>
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label for="sbUser">Expiry of Requirement : </label><br>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input id="thedate" type="text" name="txtBidclosing" class="form-control" required="required"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<input type="button" class="button" value="submit" />
</form>
</div>
</div>
</div>
</div>
<div id="sort">
<br>
</div>
Ajax code
<script>
$(document).ready(function(){
$(".button").click(function(){
$.ajax({
type:"POST",
url: "<?php echo base_url() ?>moderator/Requirement/add_employee_data",
data:$("#myForm").serialize(),
success: function (dataCheck) {
//alert(dataCheck);
$('#sort').append(dataCheck);
//window.location.reload();},
});});});
</script>
Model
public function add_employee_data($data){
$this->db->insert('jil_requirementdetail',$data);
$id = $this->db->insert_id();
$this->db->select('*');
$this->db->from('jil_requirementdetail');
$this->db->where('rqmd_id',$id);
$result = $this->db->get()->result();
return $result;
}
On your model
public function add_employee_data($data){
$this->db->insert('jil_requirementdetail',$data);
$id = $this->db->insert_id();
$this->db->select('*');
$this->db->from('jil_requirementdetail');
// $this->db->where('rqmd_id',$id); // get all data
$this->db->order_by('rqmd_id','DESC');
$result = $this->db->get();
if($result->num_row() > 0)
{
echo json_encode(['status'=>'pass','data'=>$result->result()];
}else{
echo json_encode(['status'=>'fail']);
}
}
On Ajax Success
<script>
$(document).ready(function(){
$(".button").click(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>moderator/Requirement/add_employee_data",
data: $("#myForm").serialize(),
success: function(dataCheck){
//alert(dataCheck);
var res = JSON.parse(dataCheck);
if(res.status=='pass')
{
var user_data = res.data;
var html = '';
var length = user_data.length;
for(var i = 0; i < length; i++)
{
//your html
html += '<div>' + user_data[i].name + '</div>'; //add your html structure as you want
}
$('#sort').append(html);
},
}
});
});
});
</script>

Form is not submitting in ajax returned html data from php

There are three files
1.street_master.php 2.street.php 3.streetdelete.php
street_master.php has form for adding new street(streetname,streetcode) when submit is pressed using ajax call new street is added and and the street list from the database are printed in table format( with individual delete option delete is done by streetdelete.php file ) on the same page that is street_master.php .but delete option is not working. actually form is not submitting which redirect to streetdelete.php
streetmaster.php
<html>
<?php include 'conf.php'; ?>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="jquery-1.12.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function showUser()
{
var n1=document.getElementById('scode').value;
var n2=document.getElementById('sname').value;
var n3=document.getElementById('desc').value;
var n4=document.getElementById('ward').value;
if (n1 == null || n1 == "" )
{
alert('fill street code ');
}
else if( n2 == null || n2 == "" ) {
alert('fill street name');
}
else
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
var q="?v1="+n1;
q+="&v2="+n2;
q+="&v3="+n3;
q+="&v4="+n4;
xmlhttp.open("GET","street.php"+q,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<center>
<h2>Street Master</H2>
</CENTER>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2">Street code </label>
<div class="col-sm-1">
<input type="number" class="form-control" name="scode" id="scode" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"> Street name</label>
<div class="col-sm-2"> <input type="text" class="form-control" name="sname" id="sname" required> </div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"> Description</label>
<div class="col-sm-2"> <input type="text" class="form-control" name="desc" id="desc" > </div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="ward num"> Ward No </label>
<div class="col-sm-2">
<select name="ward" id="ward" class="form-control">
<option value="">chose the ward</option>
<?php
$s="select WardNo from ward";
$result=$con->query($s);
while($row = $result->fetch_assoc())
{
echo "<option value='$row[WardNo]'> ward $row[WardNo]</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"> </div>
<div class="col-sm-2"> <input type="button" class="form-control" value="submit" onClick="showUser()"> </div>
</div>
</form>
<div id="txtHint"></div>
</body>
</html>
street.php
<?php
$q =$_GET['v1'];
$q1 =$_GET['v2'];
$q2 =$_GET['v3'];
$q3 =$_GET['v4'];
/
include 'conf.php';
if($con)
{
$sql="insert into areacodemaster values('$q','$q1','$q3')";
$con->query($sql);
$s="select * from areacodemaster";
$result=$con->query($s);
echo "
<head>
<link rel='stylesheet' href='scroll.css'>
<script src='scroll.js'></script>
</head>
<body><center>
<table class='scroll'>
<thead>
<tr>
<th>Street_code</th>
<th width='70%'>Street_Name</th>
<th>Ward_Number</th>
<th>delete</th>
</tr>
</thead> ";
echo "
<tbody> ";
while($row = $result->fetch_assoc())
{
echo "
<tr>
<form action='streetdelete.php' method='post'>
<td>".$row['Areacode']."</td>
<td>".$row['Areaname']."</td>
<td>".$row['WardNo']."</td>
<td><input type='hidden' name='ac' value='$row[Areacode]'>
<td><input type='submit' value='Delete'></a></td>
</form>
</tr>";
}
echo "
</tbody>
</table></center>
</body> ";
}
?>
streetdelete.php
<?php
$g=$_POST['ac'];
include 'conf.php';
$sq="delete from areacodemaster where Areacode='$g'";
$con->query($sq);
echo "<script type='text/javascript'>alert('Deleted'); </script>";
?>
but if we run street.php alone form is submitting to streetdelete.php
Your whole code is in a mess and it need to be more organized,
The basics mistakes you have done:
1- You are adding new page each time new street is being shown, and that because you are mixing the server side page with the search page and to fix that you have to separate them, so a page for searching and another for showing.
2- It's better to have one core Ajax function to deal with all requests and then you can process the searching actions and deleting actions through Ajax, in this case you will not need to use a form for deleting and the problem will be solved, OR since you are including Jquery to your project then there is no need to have your own Ajax core function because Jquery has done that for you so you can call an Ajax request any place you want with your preferred parameters.
So your code will be as follow:
First page: streets.php (the main page which shows existing streets)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="jquery-1.12.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function deleteUser(streetCode){
$.ajax({
type: "POST",
url: "deletestreet.php",
data: {ac: streetCode},
success: function( msg ){$("#" + streetCode ).remove();alert("Deleted");}
});
}
function showUser(){
var n1 = $("#scode").val();
var n2 = $("#sname").val();
var n3 = $("#desc").val()
var n4 = $("#ward").val();
if (n1 == null || n1 == "" ){
alert('fill street code ');
}
else if( n2 == null || n2 == "" ){
alert('fill street name');
}
else{
$.ajax({
type: "POST",
url: "searchstreet.php",
data: {v1: n1, v2: n2, v3: n3, v4: n4},
success: function( msg ){$("#txtHint").html(msg);}
});
}
</script>
</head>
<body>
<center><h2>Street Master</h2></center>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2">Street code</label>
<div class="col-sm-1">
<input type="number" class="form-control" name="scode" id="scode" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Street name</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="sname" id="sname" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Description</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="desc" id="desc" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="ward num">Ward No</label>
<div class="col-sm-2">
<select name="ward" id="ward" class="form-control">
<option value="">chose the ward</option>
<?php
$s="select WardNo from ward";
$result=$con->query($s);
while($row = $result->fetch_assoc()){
echo "<option value='$row[WardNo]'> ward $row[WardNo]</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"> </div>
<div class="col-sm-2">
<input type="button" class="form-control" value="submit" onClick="showUser()">
</div>
</div>
</form>
<div id="txtHint"></div>
</body>
</html>
Page 2: searchstreet.php
<?php
$q = $_GET['v1'];
$q1 =$_GET['v2'];
$q2 =$_GET['v3'];
$q3 =$_GET['v4'];
include 'conf.php';
if($con){
$sql = "insert into areacodemaster values('$q','$q1','$q3')";
$con->query($sql);
$s = "select * from areacodemaster";
$result=$con->query($s);
echo "
<center>
<table class='scroll'>
<thead>
<tr>
<th>Street_code</th>
<th width='70%'>Street_Name</th>
<th>Ward_Number</th>
<th>delete</th>
</tr>
</thead>
<tbody>";
while($row = $result->fetch_assoc()){
echo "
<tr id='".$row['Areacode']."'>
<td>".$row['Areacode']."</td>
<td>".$row['Areaname']."</td>
<td>".$row['WardNo']."</td>
<td><input type='button' value='Delete' onclick=deleteUser('".$row['Areacode']."')></td>
</tr>";
}
echo"
</tbody>
</table>
</center>";
}
deletestreet.php
<?php
$g = $_POST['ac'];
include 'conf.php';
$sq = "delete from areacodemaster where Areacode='$g'";
$con->query($sq);
?>

Categories