I have an add feature that runs an insert query (using PDO).
The first insert works accordingly. It's the second run, and every run after that causes the query to duplicate times 2.
I have no idea why this is happening.
The user makes a selection, which populates a datatable (example1). They can then select one of the records (or lanes) which populates another datatable (example2).
Here is the initial onClick event:
$('#example1').on('click', 'tr > .laneClick', function(e){
e.preventDefault();
const dataTable = $('#example1').DataTable();
const rowData = dataTable.row($(this).closest('tr')).data();
let partnerCode = rowData['partner_code'];
let partnerName = rowData['partner_name'];
let groupName = rowData['groupname'];
let lanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
groupName: groupName
}
displayLaneRecords(lanecriteria);
});
Here is the function displayLaneRecords, which displays the second datatable called "example2" after the .laneClick onClick event:
function displayLaneRecords(lanecriteria){
if(lanecriteria == ""){
let data = '';
}
else{
let data = {
lanecriteria: {
partnerCode: lanecriteria.partnerCode,
vesselProfile: lanecriteria.vesselProfile,
salesRep: lanecriteria.salesRep
}
}
}
$.ajax({
url: 'api/getLaneData.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data, textStatus, jqXHR){
var jsonObject = JSON.parse(data);
var table = $('#example2').DataTable({
"data": jsonObject,
"columns": [
// data columns
],
"dom": 'Bfrtip',
"buttons": [
{
text: '<i class="fa fa-plus"></i> Add Lane',
className: 'addLane btn btn-primary btn-sm',
action: function (e, dt, node, config){
// opens the form for processing
$('#addLaneModal').modal('show');
}
}
]
});
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: '+ errorThrown);
return false;
}
}); // end ajaxcall
// here is where the form process will occur
} // end displayLaneRecords();
As you will see, the form process will occur within the displayLaneRecords() function. I had to do this so when the process is complete, I can repopulate the datatable without refreshing.
Here is the form process:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let groupName = $('#addlanegroupname').val();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
groupName: groupName
}
$.post('api/editLane.php', {addlanecriteria:addlanecriteria}, function(data){
if(data.indexOf('Error') > 1){
$('.message').text(data);
$('#errorModal').modal('show');
return false();
}
else{
$('.message').text(data);
$('#messageModal').modal('show');
$('#messageModal').on('hidden.bs.modal', function(){
$("#addLaneModal").modal('hide');
displayLaneRecords(lanecriteria); // call displayLaneRecords to refresh the table
});
}
});
});
The actual PHP process called editLane.php looks like this:
<?php
if(isset($_POST['addlanecriteria'])){
$value = $_POST['addlanecriteria'];
$partnerCode = isset($value['partnerCode']) ? $value['partnerCode'] : '';
$partnerName = isset($value['partnerName']) ? $value['partnerName'] : '';
$groupName = isset($value['groupName']) ? $value['groupName'] : '';
try{
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $dbc->prepare("INSERT INTO table (`partner_code`, `partner_name`, `group_name`) VALUES (:newpartnercode, :newpartnername, :newgroupname)");
$insert->execute([
'newpartnercode' => $partnerCode ,
'newpartnername' => $partnerName ,
'newgroupname' => $groupName
]);
if($insert){
echo "Success: New Lane has been added.";
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
?>
I tried to minimize as much code as I could.
All of the above works without any visible errors. When the form is submitted, a new record is inserted into the table, and the datatable refreshes without the page refreshing.
The problem occurs when the user adds another record - the query duplicates, and instead of inserting 1 record, 2 are inserted. If they add another record, the query will insert 4 records.
What can I try next?
Related
I made a form from many tables from a database, like holiday, service and etc.. tables. Holiday is a datepicker and adds dates with jquery and saves when I click the update button. But deleting is not working like this.
I want to delete some holidays with ajax and check some services and then update all of the form with one "update" button. I want to delete using jquery and send the ID of holiday not from the database, then I click on the update button to delete from the database and update all data.
How do I send the ID of the holiday to the server?
My php code for deleting holiday:
if (isset($_POST["holiday_id"])) {
var_dump($_POST);
$holiday_id = $_POST['holiday_id'];
$userid_office = $_POST['userid_office'];
$deleted_holiday = $db->query("delete from holiday where id='$holiday_id' and
$userid_office='$userid_office' ");
var_dump($deleted_holiday);
if ($deleted_holiday == true) {
echo json_encode(['message' => 'successfully deleted', 'status' => 'success']);
die();
} else {
echo json_encode(['message' => 'can not delete', 'status' => 'error']);
die();
}
}
My ajax code for deleting and updating the form:
$(".delete").on('click', function (e) {
e.preventDefault()
var holiday_id=$(this).data("holiday_id");
$('#holiday_'+holiday_id ).remove()
console.log(holiday_id)
return false;
})
$("#scheduleForm").on("submit", function (e) {
e.preventDefault();
var form_data = $(this).serialize();
var url = window.location.pathname + "?mod=schedule&action=schedule_added&ajax=true";
console.log(form_data)
$.ajax({
url: url,
method: "POST",
data: form_data,
success: function (data) {
data = JSON.parse(data)// important because without it show just string
// console.log(typeof data);
if (data.message != null) {
alert(data.message)
} else {
location.reload();
alert("تغییرات باموفقیت انجام شد.")
}
},
error: function (err, err1, err3) {
console.log(err3);
console.log(err1);
}
})
})
I have a simple messaging system and I am retrieving the messages from the DB using jQuery/AJAX and appending to a table. I wanted pagination for the messages so I opted to use the DataTables plugin (https://datatables.net/).
I am having trouble using this with my dynamically generated data. I also have functions such as "delete message" which would then delete the message and then retrieve the messages again (refresh the table). I am getting the error "cannot re-initialise DataTable".
This is my code so far:
function getmessages(){
$.ajax({
type: "POST",
url: "modules/ajaxgetmessages.php",
dataType: 'json',
cache: false,
})
.success(function(response) {
if(!response.errors && response.result) {
$("#tbodymessagelist").html('');
$.each(response.result, function( index, value) {
var messagesubject = value[3];
var messagecontent = value[4];
var messagetime = value[5];
var sendername = value[2];
var readstatus = value[7];
var messageid = value[8];
if (readstatus==0){
messageheader += '<tr><td><input type="checkbox" class="inboxcheckbox input-chk"></td><td class="sendername"><b>'+sendername+'</b></td><td class="messagesubject"><b>'+messagesubject+'</b></td><td><b>'+messagetime+'</b></td><td class="messageid" style="display:none">'+messageid+'</td><td class="readstatus" style="display:none">'+readstatus+'</td><td class="messagecontent" style="display:none"><b>'+messagecontent+'</b></td></tr>';
} else {
messageheader += '<tr><td><input type="checkbox" class="inboxcheckbox input-chk"></td><td class="sendername">'+sendername+'</td><td class="messagesubject">'+messagesubject+'</td><td>'+messagetime+'</td><td class="messageid" style="display:none">'+messageid+'</td><td class="readstatus" style="display:none">'+readstatus+'</td><td class="messagecontent" style="display:none"><b>'+messagecontent+'</b></td></tr>';
}
});
$("#tbodymessagelist").html(messageheader);
$('#tblinbox').DataTable({
"paging": true,
"ordering": false,
"info": false
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
So how can I essentially, make changes to my table after message deletion or other functions and then "refresh" the table? It also shows Showing 0 to 0 of 0 entries in the footer even though there are entries there.
You must destroy datatable berfore create new instance;
`
$('#tblinbox').DataTable.destroy();
$('#tblinbox').empty();
I want to ask why my codeigniter when add data become error 500 internal server when the save proccess. I dont know anything about this problem please help me all.
This is ajax code in view
function save()
{
$('#btnSave').text('menyimpan...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('edulibs/ajax_add')?>";
} else {
url = "<?php echo site_url('edulibs/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('menambahkan / update data error');
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
And this is my controller
public function ajax_add()
{
$this->_validate();
$data = array(
'nama' => $this->input->post('nama'),
'nim' => $this->input->post('nim'),
'pembimbing1' => $this->input->post('pembimbing1'),
'pembimbing2' => $this->input->post('pembimbing2'),
'subyek' => $this->input->post('subyek'),
'judul' => $this->input->post('judul'),
'tanggal' => $this->input->post('tanggal'),
'tautan' => $this->input->post('tautan'),
);
$insert = $this->edulibs->save($data);
echo json_encode(array("status" => TRUE));
}
In order to use site_url() load url helper in your controller first.like this..
$this->load->helper('url');
OR load helper in application/config/autoload.php
And in success function of your ajax use JSON.parse() to parse your json response into object.Like this
success: function(response)
{
var data = JSON.parse(response);//OR var data = eval(response);
if(data.status) //if success close modal and reload ajax table
{
//code here
}
else
{
//code here
}
I am using Ajax to post the results from a php form to a database using an API. However when the script runs, I am not getting anything in return stating that it was a success or an error. I can log into the database and see that it has added the entry but I am not getting an alert when it saves to the database.
What I would like the script to do is:
-First save to the database (Done)
-Second: Alert the user that the operation was completed successfully or error
-Third: reset the values in the form if success, keep values if error
Here is what I have tried and have so far:
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
$('form#directory-create').on('submit', function (e) {
//stops the submit action
e.preventDefault();
//format the data into javascript object
var data = $(this).serializeArray();
//calls function to create record, passing participant information as arguments
createRecord(data);
});
function resetStudyInfo() {
//resets all form values to default
$('form#directory-create').find('input:text, input:radio, input:email, input:phone').val('');
return true;
}
function createRecord(data) {
//converts into json data format
var myData = JSON.stringify(data);
console.log(myData);
$.ajax({
//setup option for .ajax func
type: "POST",
url: "directory-create-record.php",
data: {
//user_data : contains all the fields and their data
user_data: myData
},
//shows output message on error or success
success: function () {
showSuccess('Study created successfully, you may now add participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
PHP side:
require "RestCallRequest.php";
function insertData($data_from_user){
$status = 2;
$url = "xxxx";
$token = "mytokenishere";
$fname = $data_from_user[0]->value;
$lname = $data_from_user[1]->value;
$title = $data_from_user[2]->value;
$school = $data_from_user[3]->value;
$facultystafftrainee = $data_from_user[4]->value;
$email = $data_from_user[5]->value;
$phone = $data_from_user[6]->value;
$record_id = $lname .'_'. $fname;
# an array containing all the elements that must be submitted to the API
$data = "record_id,f_name,l_name,title,school,facultystafftrainee,email,phone,directory_complete\r\n";
$data .= "$record_id,$fname,$lname,$title,$school,$facultystafftrainee,$email,$phone,$status";
$args = array(
'content' => 'record',
'type' => 'flat',
'format' => 'csv',
'token' => $token,
'data' => $data
);
# create a new API request object
$request = new RestCallRequest($url, 'POST', $args);
# initiate the API request
$request->execute();
$result = $request->getResponseBody();
if($result == '1'){
return 1;
}
}
Any help is greatly appreciated. Thank you
When resetting the form values, you have input:email and input:phone, javascript throws a syntax error as you do not need these values, When you remove them your code should work.... Here is the complete working code
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function resetStudyInfo() {
$('form#directory-create').find('input:text, input:radio').val('');
return true;
}
$('form#directory-create').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray();
createRecord(data);
});
function createRecord(data) {
var myData = JSON.stringify(data);
$.ajax({
type: "POST",
url: "directory-create-record.php",
data: {
user_data: myData
},
success: function () {
showSuccess('Study created successfully, you may now add more participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
I am making a LIVE UPDATE in CodeIgniter and it is almost working.
Just one little issue: When I click the button it also appears my navigation inside the "responds" box which is very strange.
And when I refresh the page it is removed and the record is there.
Here is an image to explain what I mean
Here is the JavaScript:
<script type="text/javascript">
$(document).ready(function() {
//##### Add record when Add Record Button is click #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val() ==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // Post / Get method
url: "<?php echo site_url('admin/dashboard/index'); ?>", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response) {
$("#responds").append(response);
},
error:function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
});
</script>
EDIT:
HERE IS THE CONTROLER
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load libraries
$this->load->library('ion_auth');
$this->load->library('parser');
// Load models
$this->load->model('note_model');
// Load helpers
$this->load->helper('date');
// Set error delimiters
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
}
public function index()
{
// Check if user is loged in
if (!$this->ion_auth->logged_in())
{
redirect('auth/login');
}
else
{
// Create notes object
$notes = new Note_model();
// Order the notes by date post
$notes->order_by('date_post', 'desc')->get();
$recent_notes = array();
foreach ($notes as $note)
{
$single_note = array
(
'id' => $note->id,
'note_text' => $note->note_text,
'date_post' => $note->date_post,
);
array_push($recent_notes, $single_note);
}
// Get the user id as an object
$getinfo = $this->ion_auth->user($this->session->userdata('user_id'))->row();
// Create a new note
$createNote = new Note_model();
$createNote->note_text = $this->input->post('content_txt');
$created = date('Y-m-d H:i:s');
$createNote->date_post = $created;
// Validation rules
$rules = $this->note_model->rules;
$this->form_validation->set_rules($rules);
$data = array
(
'admin_content' => 'admin/dashboard',
'notes' => $recent_notes,
'username' => $getinfo->{'first_name'} . ' ' . $getinfo->{'last_name'},
);
if ($this->form_validation->run() == FALSE)
{
$this->parser->parse('admin/template_admin', $data);
}
else
{
$createNote->save();
redirect('admin/dashboard');
}
}
}
The problem is the action you are calling.
It seems admin/dashboard/index outputs the navigation as well as the data you want to display.
You should post to an action that ONLY displays the data you require, and nothing else