How to get the data from ajax in controller codeigniter - javascript

I have an editable table in my view.. At first, there's no data in the table but the user can add data in the table since it is editable. And there's no exact number of rows in the table since I have also a button that can add new row. I want to get the data that the user have added and save it in the database.
I have this code:
VIEW:
<table class="table " id="memberTB">
<thead><tr><th >First Name</th><th >Middle Name</th><th>Last Name</th></tr></thead>
<tbody>
<tr id="first"><td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td></tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow"><span class="fa fa-plus"> Add new row</span></button>
</table>
<br><button type="button" class="btn" id="savebtn">Save</button> Reset
JS:
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.showbuttons = false;
$.fn.editable.defaults.url = '/post';
$.fn.editable.defaults.type = 'text';
// make all items having class 'edit' editable
$('.edit').editable();
// this is to automatically make the next item in the table editable
$('.edit').on('save', function(e, params){
var that = this;
// persist the old value in the element to be restored when clicking reset
var oldItemValue = $(that)[0].innerHTML;
if (!$(that).attr('oldValue')) {
console.log('persisting original value: ' + oldItemValue)
$(that).attr('oldValue', oldItemValue);
}
setTimeout(function() {
// first search the row
var item = $(that).closest('td').next().find('.edit');
console.log(item);
if (item.length == 0) {
// check the next row
item = $(that).closest('tr').next().find('.edit');
}
item.editable('show');
}, 200);
});
$('#resetbtn').click(function() {
$('.edit').each(function() {
var o = $(this);
o.editable('setValue', o.attr('oldValue')) //clear values
.editable('option', 'pk', o.attr('pk')) //clear pk
.removeClass('editable-unsaved')
.removeAttr('oldValue');
});
});
$('#savebtn').click(function() {
var person = [];
var x=1;
$('tbody tr',$('#memberTB')).each(function(){
for(var i = 0 ; i < cells ; i++)
{
person[x][i]=$(this).find('td').eq(i).text();
}
x++;
});
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: { values: arraylng },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
});
$('#addrow').click(function() {
$('#memberTB > tbody:last').append(' <tr><td><span class="edit"></span></td><td><span class="edit"></span></td><td><span class="edit"></span></td></tr>');
$('.edit').editable();
});
Controller: [inside the test.php]
public function saveData(){
$this->load->model('test_model');
$myArray = $_REQUEST['values'];
echo sizeof($myArray);
}
Whenever I click the save button, there's no response at all.. Where did I go wrong? please help me..
ADDED INFO:
I didn't include my SQL insert statement here because I want to test first if there's data in $myArray if I added data in the table.

Better use this ajax
var arraylng = [3,4,7];
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: {values: JSON.stringify(arraylng)},
cache: false,
success: function (response) {
alert(response);
}
});
arraylng is an array, which doesn't exist in the code. I added it here for debugging.
Suppose you want to send person[] array, you write, data: {values: JSON.stringify(person)}.
Now, the person array may not exist, because of the "i < cells" in for. What is cells?
The word response is just a name, any name, but better avoid 'data'.
In test.php, what is sizeof($myArray)? Just, echo $myArray;
When you click save you must get the $myArray content in an alert.

Related

request ajax doesn't call the good function

I have a trouble with my request AJAX. When I click on it, in the process, it calls an other php function which I don't need for this request (function switch, change statut).
http://www.noelshack.com/2022-31-1-1659342824-undefined-index.png
This line with error corresponds to another function.
My HTML :
<table id="list_client_pris" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client) :
?>
<tr id="tr1">
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="info">Info client</button></td>
<td><button type="button" class="hide_client" data-id="<?php echo $client["id_client"]; ?>">Masquer client</button></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="switch">Change statut</button></td>
</tr>
<?php endforeach; ?>
</table>
3 buttons call each their ajax's request.
The conflict is between the first button (class info) and the last, (class switch)
Why ?
The buttton class' info call a function which correspond to the error showed, but which is not called with the last button.
My JS , request for the first button, info:
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "POST",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
});
PHP corresponding function :
function read()
{
global $db;
$id_client = $_POST['id_client']; **(error showed)**
$query = $db->prepare("SELECT *,FROM client WHERE id_client = :id_client");
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
return ($result);
}
My other ajax's request for button switch :
$(".switch").click(function () {
var datas = {
cmd :' id_client_statut',
id_client: $(this).attr('data-id_statut'),
};
console.log(id_client);
$.ajax({
url: 'function.php',
type: 'POST',
data: datas,
done: function (click_result) {
console.log(click_result);
if (click_result.statut=2){
//transfer to libre
$('#tr2').append($('#tr1').html());
$('#tr1').html('');
}
}
}
);
});
Corresponding php function :
function change_statut(){
global $db;
$id_client_statut = $_POST['id_client'];
$query=$db->prepare(" UPDATE alarme INNER JOIN client_alarme ON client_alarme.id_alarme = alarme.id_alarme
INNER JOIN client on client.id_client=client_alarme.id_client
SET id_statut = 2
WHERE client.id_client= :id_client");
$query->bindValue(':id_client', $id_client_statut, PDO::PARAM_INT);
$query->execute();
$click_result = $query->fetch(PDO::FETCH_ASSOC);
return ($click_result);
}
My php function to distinguish :
if (isset($_POST['cmd'])){
if ($_POST['cmd'] == 'id_client_statut') {
change_statut();
}
else if ($_POST['cmd'] == 'id_client') {
read();
}
}
I don't really see why the first button would call the wrong function, but there is a problem with the way you setup the button events: via the onclick you are just binding the event handlers.
In function d_info() you currently just tell what should happen when the button .info is clicked. Idem for function change_statut().
So currently you have to click the buttons twice. First to bind the event and again to trigger the event (the second time it will also rebind the event).
You should get rid of the onclick attributes and bind the button events via the document ready event.
$( document ).ready(function() {
$(".switch").click(function () {
//...
});
$(".info").click(function () {
//...
});
});
In your Request you write :
$(".info").click(function () {
var datas = {
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: {cmd :' id_client', datas},
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
But the line data: {cmd :' id_client', datas}, gives you a new object witch is :
data: {
cmd :' id_client',
datas: {
id_client: $(this).attr('data-id'),
}
},
Now you can easily understand why your php gives you an error while reading $id_client = $_GET['id_client']; **(error showed)** as the real path to your value is $id_client = $_GET['datas']['id_client'];
But why using this kind of syntax while you have create datas in order to prepare ajax data object ?
The simpliest way to correct the error is to replace all object argument in the datas :
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
Hope it's helpfull ;)
Happy coding

How to insert multiple values to database table using php?

Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);

how can I delete the row from datatable in UI,though i could successfully delete from server using Ajax call

I have a data table and in each row I have a button Delete.
ON click of Delete i am making an ajax call and deleting the row from server by passing the id.
But on success of ajax call the row is not getting deleted in the table from UI.
Below si the code.
I have rendered the column for Delete
{
"data": "Action","orderable": false, "render": function(data, type, row) {
userSignum=readCookie("userSignum");
var userIDMGroups=readCookie("nfvDBGroups");
var userIDMGroupsArray=userIDMGroups.split(';')
if((jQuery.inArray(userIDMGroups,userIDMGroupsArray ) !== -1)&&(row['signumId'] == userSignum) )
{
return '<button class="btn btn-action deleterecord" id="'+row.id+'">Delete</button>'
}
else
{
return '<button class="btn btn-action deleterecord" id="'+row.id+'" disabled="disabled">Delete</button>'}
}
}
Below si the ajax call
$("#searchTable tbody").on("click", ".deleterecord", function () {
var table = $('#searchTable').DataTable();
var recordId=$(this).attr("id");
// var $row = $(this);
if(recordId!=null){
$.ajax({
type: 'POST',
url: config.vnfURL + 'vnf/delete',
dataType: "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify({"id" : recordId }),
processData: false,
success: function(response, textStatus, jqXHR) {
// table.row( $(this).parents('tr') ).remove().draw();
//$(recordId).remove();
table.row($(this).parents('tr')).remove().draw(false);
alert("record deleted");
if(jqXHR.status == "200"){
className = "alert-success";
msg = "Record has been deleted Successfully.";
} else {
className = "alert-danger";
msg = "Something wrong, please try again after sometime.";
}
$("#infoDiv").addClass(className).show();
$("#infoDiv>center>p").html(msg);
setTimeout(function() {
$("#infoDiv").removeClass(className).hide();
$("#infoDiv>center>p").html("");
// window.location = "/resources/search.html";
}, 7000);
},
please help
The reason is that this within AJAX success callback refers to XHR object, so you may assign const tr = table.row($(this).closest('tr')) outside of success callback and then do tr.remove().draw() upon successful deletion server-side.
p.s. also, note that I have used closest('tr') rather than parents('tr') as it is less error prone, since the latter may return array if your button happen to have multiple <tr> parents
Add this line on success call back of ajax
table.row( $(this).parents('tr') ).remove().draw();

How to get the data-value of selected td

I want to get a data value from the clicked td, which opens a modal with the informations of the user.
When I select all users, everything works fine..
But when I want to search a specific user (table is not displayed until you search for a user), the modal shows not the right data..
I created a JS array with the usernames and put it in my data value. The innerHTML from the column is the first- and last name of the user.
The problem is that when I click on the name the modal shows the information from the FIRST user in my array (grouped by lastname ASC)
I'm using the DataTables plugin. Here's a short example of my drawCallback function:
"drawCallback": function(settings) {
var api = this.api();
var rows = api.rows({
page: 'current'
}).nodes();
var last = null;
api.column(0, {
page: 'current'
}).data().each(function(group, i) {
if (last !== group) {
var groupName = api.row(i).data();
$(rows).eq(i).before(
'<tr class="group"><td style="font-weight: bold;" data-value="'+groupName[0]+'" data-toggle="modal" data-target="#profileModal" class="tdPerson" colspan="1">'+group+'</td><td colspan="5"></td></tr>'
);
last = group;
}
});
}
Here's my AJAX request:
$('.table').on('click', '.tdPerson', function(event) {
id = $(this).attr('data-value');
$.ajax({
url: "getData.php",
data: {
type: "getPersonModal",
data: id
},
type: "POST",
success: function(data) {
$('#profileModalContent').html(data);
}
});
});

How to update data in SQL for an html table row using Input Button, in JS or C#?

I have a datatable in C# and I am converting it to html table like below.
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder html = new StringBuilder();
html.Append("<table id='example' class='table table-striped table-bordered' cellspacing ='0' width ='100%' font size='8' aria-hidden='true'>");
//add header row
html.Append("<thead>");
html.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
html.Append("<td>" + dt.Columns[i].ColumnName + "</td>");
html.Append("<td>" + "Action" + "</td>");
html.Append("</tr>");
html.Append("</thead>");
//add rows
for (int i = 0; i < dt.Rows.Count; i++)
{
html.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
html.Append("<td><input type=\"button\" value=\"Delete\" onclick=\"deleteRow(this)\"/></td>");
html.Append("</tr>");
}
html.Append("</table>");
return html.ToString();
}
This is showing a table in my aspx page like below:
Name City Quantity Action
A X 5 Delete
B Y 10 Delete
C Z 15 Delete
When I click "Delete" button for a row, the function below works and the row is gone from the result table.
<script>
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
</script>
What I want is that, in addition to the current process, I need to run a SQL query to update IsRemoved flag for this data in my SQL Server 2014 table.
The query I need to run: Update MyTable set IsRemoved=1 where Name='A' and City='X'
I could not manage to run it in JavaScript function, and could not find a way to execute another function in C# after the JS function. OnClientClick is not working since it is not an asp:Button, and when I try to use asp:Button instead of input element, it does not show it on the screen.
How can I change data in DB here for such an example? Please note that I am trying not to use a GridView. Any help would be appreciated.
EDIT: By using Ajax, how can I send paramaters from my ajax call to c#:
I am trying:
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
data: JSON.stringify({ name: **<nameshouldcomehere>**, city:**<cityshouldcomehere>** }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
I can't find how to set name and city dynamically based on the row clicked the delete button, any tips?
In your .cs page create a WebMethod which will mark the Database entry as IsRemoved=1 as:
[System.Web.Services.WebMethod]
public static string DeleteRowFromDB(string name,string city)
{
var status = "0";
//Your code to mark `IsRemoved=1` for the selected entry goes here and set the `status` variable as status="1" if the DB command successed.
return status;
}
And then create a function with an ajax call to invoke the created WebMethod and remove the row from HTML if the status is true as:
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
var cells = row.getElementsByTagName("td");
var reqData = JSON.stringify({ name: cells[0].innerText, city:city=cells[1].innerText });
//now make a call to the `WebMethod` via `ajax`.
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
contenttype: 'application/json; charset=utf-8',
data: reqData,
datatype: 'json',
success: function (response) {
if(response === "1") {
row.parentNode.removeChild(row);
}
else
{
//do other stuff
}
},
error: function (error) {
//handle the error
}
});
}
Note: if the response variable in the ajax success function doesn't have the desired value try to look for its response.d property value.

Categories

Resources