How to pass data from post to ajax in codeigniter - php

So i have table and trying to do C.R.U.D.
I make for edit form with modal. As my table populate inside of foreach i put my modal inside in table to get correct id of row.
This is my ajax function
$("#uin").click(function(){
var mydata = $("form#update-interview").serialize();
var id = $("#jsonid").val();
console.log(mydata); // it's only for test
$.ajax({
type: "POST",
url: "vacancy/interview/" + id , //process
data: { user_submission_token: $("#session_token").val(),mydata },
dataType: "json",
success: function(msg){
alert("Succeess");
$("#form-content").modal('hide'); //hide popup
},
error: function(){
alert("failure");
}
});
});
From this Ajax Submit im getting output like:
candidate_id=120&vacancy_id=48&stage=Interview&date=&candidate_id=120&vacancy_id=49&stage=Interview&date=&candidate_id=120&vacancy_id=53&stage=Interview&date=&candidate_id=120&vacancy_id=54&stage=Interview&date=&candidate_id=120
and this continues until last ID, so i need to get only 1 candidate_id ,vacancy_id and stage with date.
Its getting all of them because is inside in foreach but if i put my form outside of foreach then how i will get my row ID?
this is my function in controller
public function interview($i)
{
$type=$this->input->post();
$test= json_encode($data= array(
"status" => 1,
"candidate_id" => $this->input->post('candidate_id'),
"vacancy_id" => $this->input->post('vacancy_id'),
"date" => $this->input->post('date'),
"stage" => $type[3],
)
);
var_dump($test);
die();
$this->vacancies->update_interview($data, array("vacancy_id" => $i));
}
from this controller var_dump i got this output {"status":1,"candidate_id":false,"vacancy_id":false,"date":false,"stage":null}
seems my function is not correct also, can i get some advice?
and model side is just this
public function update_interview($i)
{
$this->db->insert("interviews", $i);
}
For any case this is my form its little-bit long
<!-- Update Interview-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<form class="no-error-margin" id="update-interview">
<div class="modal-content">
<div class="modal-body">
<div class="form-group">
<input type="hidden" name='candidate_id' value="<?= $candidate_id; ?>" />
<input type="hidden" name='vacancy_id' id="jsonid" value="<?= $row['id']; ?>" />
</div>
<div class="form-group">
<label class="control-label">Type:</label>
<select id="classinput" tabindex="1" name="stage" class="form-control required">
<option value="Interview">Interview</option>
<option value="Final Interview">Final Interview</option>
<option value="">Rejected</option>
</select>
</div>
<!-- Using DatePicker-->
<div class="date-form">
<div class="control-group">
<label class="control-label" style="margin: 0 30%;padding: 7px;">When The Interview Will Be?</label>
<div class="container">
<div class="row">
<div class='col-sm-6 col-md-offset-3'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input name="date" type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="uin" type="submit" data-dismiss="modal" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
</div>
</div>
<?php echo form_close();?>
</div>
</div>
<!-- End Interview-->
UPDATE:
Okay thanks to Niranjan N Raju
Now i'm getting just 1 result in POST and its correct which is looks like
candidate_id=126&vacancy_id=46&stage=Interview&date=12/03/2015+12:00+AM
So now how to insert this into database? Into candidate_id , vacancy_id , stage and date columns with their values?

this is wrong,
data: { user_submission_token: $("#session_token").val(),mydata },
It should be
data: { user_submission_token: $("#session_token").val(),mydata:mydata },
^ ^
data is always is passed as {key:value,key:value}
But you are passing only key.

$("#uin").click(function(){
var mydata = $("form#update-interview").serialize();
var id = $("#jsonid").val();
mydata.push({user_submission_token: $("#session_token").val()
});
$.ajax({
type: "POST",
url: "vacancy/interview/" + id ,
data: mydata,
dataType: "json",
success: function(msg){
alert("Succeess");
$("#form-content").modal('hide');
},
error: function(){
alert("failure");
}
});
});

Related

I can't pull data other than input with ajax

I have a modal I opened with Ajax and I can pull the information from the database. My problem is this: I can only pull data into the input. Any div, p tags or ckeditor etc. I can't pull data into it. What can I do about this? In the meantime, I do not have problems withdrawing data from the database. I can pull the data. I'm looking at Console. But I can only pull it into the input.
index.php
<div class="modal fade edit" id="edit-modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title pl-3" id="exampleModalScrollableTitle">Edit Test</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="text-white">×</span>
</button>
</div>
<form method="post" id="frmedit" enctype="multipart/form-data">
<div class="modal-body pre-scrollable">
<input type="text" name="id" id="id" class="form-control">
<p id="asd"></p>
<div class="form-group form-float mt-3">
<div class="form-line">
<input type="text" class="form-control" name="title" id="title">
<label class="form-label">Title</label>
</div>
</div>
<div class="form-group form-float">
<label class="form-label">CKeditor</label>
<textarea name="test1"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn bg-grey waves-effect" data dismiss="modal">Close</button>
<input type="submit" id="update" class="btn bg-purple waves-effect" value="Save">
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click' , '.bn-edit' ,function(){
var id = this.id;
console.log("id:"+id+",type:test");
$.ajax({
type: "GET",
url: "read.php?id="+id+"&type=test",
success:function(response){
$("#edit-modal").modal('show');
$.each(response, function(key, value) {
console.log("key:"+key+",value:"+value);
})
$("#title").val(title);
$("#test1").html(test1);
$("#asd").val(asd);
$("#id").val(id);
}
});
});
});
function loaddata() {
$.ajax({
url: 'read.php',
type: 'post',
data: {"type":"test_all"},
success:function(response){
$("#container").html(response);
}
});
}
$(function () {
CKEDITOR.replace('test1');
CKEDITOR.config.height = 125;
});
read.php:
$id = $_REQUEST["id"];
switch($_REQUEST["type"]) {
case "test":
if(isset($_REQUEST["id"])) {
$result = $conn->read("test", " id='$id' ", "", "", "");
if(!empty($result)) {
$responseArray["title"] = $result[0]["title"];
$responseArray["asd"] = $result[0]["asd"];
$responseArray["test1"] = $result[0]["test1"];
$responseArray["id"] = $result[0]["id"];
echo json_encode($responseArray);
}
}
break;
case "test_all":
$result = $conn->verioku("id,title,asd", "test", "id");
break;
default:
break;
}
The problem solved. I added just this code:
CKEDITOR.instances.ic_ozet.setData(response.ic_ozet);
Thank you so much for your comments.
$(document).on('click' , '.bn-edit' ,function(){
var id = this.id;
console.log("id:"+id+",type:test");
$.ajax({
type: "GET",
url: "read.php?id="+id+"&type=test",
success:function(response){
$("#edit-modal").modal('show');
$.each(response, function(key, value) {
console.log("key:"+key+",value:"+value);
})
$("#title").val(title);
CKEDITOR.instances.test1.setData(response.test1);
$("#asd").html(asd);
$("#id").val(id);
}
});
});

ajax form submission + modal

So the problem when I click on submit it gives me this + no data is inserted into the db :
Screen shot of modal
I don't see any errors in the console.
my ajax code :
<script type="text/javascript">
$(document).ready(function () {
$("#lmao").on("submit", function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#add_data_Modal .modal-header .modal-title').html("Result");
$('#add_data_Modal .modal-body').html(data);
$("#submitForm").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#lmao").submit();
});
});
</script>
my form + modal :
<div id="add_data_Modal"class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add mew course</h4>
</div>
<div class="modal-body">
<div class="block-content block-content-narrow">
<form id="lmao"class="js-validation-courses form-horizontal push-10-t" data-async data-target="#add_data_Modal" action="add_c.php" method="post">
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_title" name="course_title" >
<label for="material-email">course title</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_cord"name="course_cord" >
<label for="material-email">Course cord</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_hours"name="course_hours" >
<label for="material-email">hours </label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="text" id="course_price" name="course_price" >
<label for="material-email">price</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<button class="btn btn-sm btn-primary" name="add_course" id="submitForm" type="submit">Add course</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
I have the add query in a separate file called add_c.PHP
so I have tried several answers from a lot of questions but I didn't manage to get something useful.
The PHP code in add_c.php :
Php code - pastebin
My knowledge is very small about ajax so I appreciate any help.
I tried your code, and the php file retrieves this post array
Array ( [course_title] => test [course_cord] => tet [course_hours] => tet [course_price] => tt )
your php code:
if(isset($_POST['add_course'])) {
add_course nevers gets posted, so it will never come into the if. Another issue is your form gets submitted twice the way you build it.
Change the button type into button, not submit. You already have a event listener on the button ;)
<button class="btn btn-sm btn-primary" name="add_course" id="submitForm" type="button">Add course</button>

Assigning a unique id on different modal content PHP

I have a table which is being populated by book information using a while loop to fetch and display the results. The table consist of Book information and an Action Column which handles some functions like adding of quantity and deduction of quantity , etc..
Each button on the Action Column is using a modal to show the needed contents
like text boxes.
So my main problem right now is the contents of the modal only works on the first data of the table. I don't know if I'm missing something here or im doing it wrong. Any help would be great! (Im using ajax to insert data)
I can update this post if you need the php code on binding data on the table.
HTML code for the modal
<!-- ADD STOCK QUANTITY -->
<div class="modal fade" id="addqty<?php echo $bookisbn;?>" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content ">
<div class="modal-header">
<h3 style="text-align: center;">Add Stock/s
</h3>
</div>
<div class="modal-body">
<!-- <form role="form" id="add_stock_form" name="add_stock_form"> -->
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<label for="book_isbn1" class="form-label">Book ISBN
</label>
<input type="text" class="form-control text-center" id="book_isbn_as" name="book_isbn_as" value="<?php echo $bookisbn;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<input type="hidden" class="form-control" id="book_title_as" name="book_title_as" value="<?php echo $booktitle;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input type="number" class="form-control text-center" id="currentstock_as" name="currentstock_as" value="<?php echo $bookquantity;?>" readonly>
<label for="currentstock" class="form-label">Current Stock/s
</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input min="0" class="form-control text-center" type="text" id="book_quantity_as" name="book_quantity_as" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" required>
<label for="book_quantity_as" class="form-label">Enter Stock
</label>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btn_add_stock" name="btn_add_stock" class="btn btn-success waves-effect">
<i class="material-icons">add
</i> ADD
</button>
<button type="button" class="btn btn-danger waves-effect" data-dismiss="modal">
<i class="material-icons">clear
</i> CLOSE
</button>
</div>
</div>
</div>
</div>
<!-- END OF ADD STOCK QUANTITY -->
Ajax Script
// //add quantity
$(document).on("click", "#btn_add_stock", function() {
var getbookisbn = $("#book_isbn_as").val();
var getbooktitle = $("#book_title_as").val();
var getbookquantity = $("#book_quantity_as").val();
var getcurrentquantity = $("#current_stock_as").val();
var whatprocess = "ADDBOOKQUANTITY";
if (validationaddquantity == 1) {
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: {
getbookisbn: getbookisbn,
getbooktitle: getbooktitle,
getbookquantity: getbookquantity,
whatprocess: whatprocess
},
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Quantity Added',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
/////REFRESH DATATABLE
$("#datatables").load(window.location + " #datatables");
$('#book_quantity_as').val("");
});
} else if (getdata == "ERROR") {
swal({
title: 'Sorry...',
text: "You cannot perform that action right now",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
fetch_data();
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).catch(swal.noop)
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
} else if (validationaddquantity != 1) {
swal({
title: 'Oops..!',
text: 'You must enter a value to proceed',
type: 'warning',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).catch(swal.noop)
}
});
on.show.bs.modal function trigger call you must re-assign value your row data (via ajax or get by td value on a table then post )to modal element input (i see is hidden input).
So every time call a modal your content data is shown based on click row table.
Maybe can solve ur problem..

bootstrap modal insert form submit won't reset to add another entry

I am using php mysql to insert to the database and that was working, however the bootstrap modal won't let me submitting another item. The button still says inserting and the last inserted data is still showing in the inputs.
I want to insert multiple times as this becomes part of a larger edit form.
This is put outside of the edit form submit button:
<div id="add_data_Modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add A New Item</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<input type="hidden" name="job_id" id="job_id" value="<?php echo $job_id;?>">
<input type="hidden" class="form-control" id="job_mat_qty" name="job_mat_qty" value="1" />
<div class="form-group">
<label for="job_mat_desc" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea class="form-control editors" id="job_mat_desc" name="job_mat_desc" autocomplete="off" placeholder="Enter item title and / or description" />
</textarea>
</div>
</div>
<div class="form-group">
<label for="job_mat_cost" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<div class="input-group input-group"> <span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" class="form-control calculate invoice_product_price txt" autocomplete="off" id="job_mat_cost" name="job_mat_cost" aria-describedby="sizing-addon1" placeholder="0.00" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10"> </div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="insert" id="selected" value="Insert" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
$(document).on('click', '.delete-rows', function(){
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this Item?")) {
$.ajax({
type: "POST",
url: "job_remove_material_new.php",
data: ({
id: id
}),
cache: false,
success: function(html) {
$(".delete_mem" + id).fadeOut('slow');
}
});
} else {
return false;
}
});
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
$(function () {
$(document).on("hidden.bs.modal", "#add_data_Modal", function () {
$('#insert_form')[0].reset();
});
});
}
});
Sorry I have no clue how to add this code correctly for this forum so please be kind....
Thanks
You should try like this
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
//$('#insert_form')[0].reset();
$('#insert_form input[type="text"],textarea').val(''); // here is change
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
In my case it will work successfully so I hope it will help you

Unable to Retrive Ajax Response in some Records

I am using onclick jquery event to append ajax response in modal box.My purpose is to display a form with auto Filled Data in modal box that comes from ajax Response according to id from mysql database.But it is not dispaying form for some users.
my code for above explained is here
Jquery code:
$(document).on("click",".edit_recent_member_form",function(e){
e.preventDefault();
$("#overlay").addClass("load_show");
$("#formModal .modal-body").html("");
var edit_recent_member_form="edit_recent_member_form";
var mem_id=$(this).attr("mem_id");
var datastring="edit_members_form="+edit_recent_member_form+"&mem_id="+mem_id;
//alert(datastring);
$.ajax({
url:"modules/my_members/edit_member_form.php",
type:"post",
dataType:"json",
data:datastring,
}).done(function(data){
var html=data["html"];
//alert(html);
$("#formModal .modal-body").append(html);
$('#formModal').modal({
show:true
//backdrop:'static'
});
/////
$(".mi-multiup").dropzone({ url: "modules/my_members/ajax.php?var=edit_profile_pic" ,acceptedFiles : ".jpeg,.jpg,.png,.gif,.JPEG,.JPG,.PNG,.GIF" });
var sendingHandler = function(file, xhr, formData) {
formData.append('mem_id',mem_id);
//formData.append('img_name', $(".img_name").val());
//formData.append('img_desc', $(".img_desc").val());
};
$('.mi-multiup').each(function() {
Dropzone.forElement(this).on('sending', sendingHandler);
});
//////
$("#overlay").removeClass("load_show");
});
});
Ajax code:
if(isset($_REQUEST['edit_members_form']))
{
$mem_id=$_REQUEST['mem_id'];
$html='<div class="panel panel-default">
<form class="form-horizontal form-border">
<div class="alert alert-success successbox">
Selected Record is Saved Successfully.
</div>
<div class="alert alert-danger dangerbox"></div>
<div class="panel-heading">
Edit Member
</div>
<div class="panel-body">
<div class="form-group">
<label class="control-label col-md-2">Login</label>
<div class="col-md-10">
<input type="text" class="form-control user_login" placeholder="" value="'.get_edit_member_detail($mem_id,"user_login",$page).'">
</div><!-- /.col -->
</div><!-- /form-group -->
<div class="form-group">
<label class="col-lg-2 control-label">Category</label>
<div class="col-lg-10">
<select class="form-control chzn-select category">
<option>None selected or enter new category</option>
'.get_category_detail($mem_id,$page,"none").'
</select>
<input type="text" class="form-control" name="newcategory" value="" placeholder="Enter a new category" size="28" />
</div><!-- /.col -->
</div><!-- /form-group -->
<div>Upload Image</div>
<div class="form-horizontal form-border" style="display:none;">
<h3>Click on area to upload new image</h3>
<div class="dropzone mi-multiup"></div>
</div>
</div>
<div class="panel-footer">
<div class="text-right">
<button class="btn btn-sm btn-success update_member_info" mem_id='.$mem_id.'>Update Member Information</button>
</div>
</div>
</form>
</div><!-- /panel -->';
$list = array('html' =>$html);
echo json_encode($list);
}
and it is the code whose onclick all work should be done
<td>
<i class="fa fa-user-md fa-lg"></i></td>
please any solution.
May be this solution. Add this code in ajax calling
url:"modules/my_members/edit_member_form.php",
type:"post",
dataType:"json",
data:datastring,
async: false

Categories