Modal receiving wrong data - javascript

I have a list with information from a database, next to each record there is a button to edit the record data. The problem is when I try to send the id of the registry I want to edit, I have always received the same output, the simple word: Array.
This is the table:
<th><?php echo $row_usuario["id_employee"]; ?></th>
<td><?php echo $row_usuario["nome"]; ?></td>
<td><?php echo $row_usuario["email"]; ?></td>
<td>
<a href="#Edit" id="custId" data-toggle="modal" data-id=" '.$row_usuario['id_employee'].'">
<i class="material-icons" style="color:#2A6F46">edit</i>
</a>
</td>
The ajax:
$(document).ready(function(){
$('#Edit').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'list_emp.php',
data : 'rowid='+ rowid,
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
Query part:
//database connection include before this
if($_POST['rowid']) {
$id = $_POST['rowid'];
//here is the problem, i'm not receiving the real id, just the word "Array" and i can't run the query because this
}
Modal:
<div class="fetched-data">Here i want to show the form with the info to be edit</div>
Can someone help me find the error?

next to each record there is a button to edit the record data
so i think you need class instead of id on your edit button
so change your html to this:
<th><?php echo $row_usuario["id_employee"]; ?></th>
<td><?php echo $row_usuario["nome"]; ?></td>
<td><?php echo $row_usuario["email"]; ?></td>
<td>
<a href="#Edit" class="fancyEditButton" data-toggle="modal" data-id=" '.$row_usuario['id_employee'].'">
<i class="material-icons" style="color:#2A6F46">edit</i>
</a>
</td>
and on your ajax:
$(document).ready(function(){
$('.fancyEditButton').on('click', function (e) {
e.preventDefault();
var rowid = $(this).data('id');
$.ajax({
type : 'post',
url : 'list_emp.php',
data : 'rowid='+ rowid,
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});

try this instead
$.ajax({
type : 'post',
url : 'list_emp.php',
data : {rowid: rowid}
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
Like here shown post ajax data to PHP and return data

Related

Ajax request doesn't return a response

I need a little help for my ajax request. I think i don't get the good value but i have tried more methods, without success.
The purpose is when we click on Info client, another array is displayed with more info. But I always have the last id added and not the id's clicked's row.
My HTML :
<div>
<table id="list_client" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
require 'config.php';
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client) : ?>
<tr id="<?php echo $client["id_client"]; ?>">
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client']; ?>);">Info client</button></td>
<td><button type="button" onclick="hide_info(<?php echo $client['id_client']; ?>);">Masquer client</button></td>
<?php endforeach; ?>
</table>
</div>
My JavaScript and Ajax request:
function display_info() {
$("#info").click(function () {
var datas = {
action: "read",
id_client: $("#id_client").val(),
};
$.ajax({
type: "GET",
url: "function.php",
async: true,
data: datas,
dataType: "json",
cache: false,
}).done(function (result) {
console.log("result");
$("#result").text("response : " + JSON.stringify($result));
});
});
}
#result is a div besides the array. (to test)
My PHP function :
function read() {
global $db;
$id_client = $_GET['id_client'];
$client = "SELECT * FROM client WHERE id_client = '$id_client'";
$query = $db->prepare($client);
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch();
echo json_encode($result);
}
I think I am close but no idea what I did wrong.
Issues:
#1 <tr id="<?php echo $client["id_client"]; ?>">
In the above code, how will you dynamically get the id of the client when trying to use it in Javascript?
#2 <td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client']; ?>);">Info client</button></td>
Above code will make all buttons have same id which is info. id needs to unique per HTML element.
#3 id_client: $("#id_client").val(),.
There is no element with id as id_client.
#4 function display_info() { $("#info").click(function () {.
You are attaching an onclick as well as a click event listener which is not required. Do either of them and not both but I would recommend the latter one.
#5 $client = "SELECT * FROM client WHERE id_client = '$id_client'";
You aren't preparing the query here with a placeholder but rather just adding the retrieved id in the query which is very unsafe since we can't trust user input.
#6 You also missed a closing tr tag.
Solution:
For issue #1, no need to attach an id attribute to a tr tag at all.
For issue #2, make info a class name instead of the id and remove onclick as it isn't needed.
For issue #3, we would get the id_client value from the data-id attribute which we will attach to the respective info button.
For issue #4, encapsulating click event listener inside display_info is not needed. We can directly attach the listener.
For issue #5, we will add a placeholder for id_client to properly bind our primitive value inside the query.
For issue #6, we will add a closing tr tag.
Snippets:
Frontend:
<div>
<table id="list_client" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
require 'config.php';
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client):
?>
<tr>
<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>
</tr>
<?php endforeach; ?>
</table>
</div>
<script>
$(".info").click(function(){
var datas = {
action: "read",
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
dataType: "json",
cache: false,
}).done(function(result) {
console.log("result");
$("#result").text("response : " + JSON.stringify($result));
});
});
$('.hide_client').click(function(){
let client_id = $(this).attr('data-id');
// do your thing here
});
</script>
Backend:
<?php
function read() {
global $db;
$id_client = $_GET['id_client'];
$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();
echo json_encode($result);
}
Not sure if that's the error you're having, but
$client = "SELECT * FROM client WHERE id_client = '$id_client'";
should probably read
$client = "SELECT * FROM client WHERE id_client = :id_client";
as the binding of the prepared statement doesn't work otherwise.
Other than that: Can you check which results you get from your select query and if that's the result you expect?
you are giving the clientid over to the function display_info, you don't need to read it out with jquery... just change
function display_info() {
to
function display_info(clientid) {
and change the
var datas = {
action: "read",
id_client: $("#id_client").val(),
};
to
var datas = {
action: "read",
id_client: clientid,
};

Entire database deletes instead of one row

I have been trying to delete a row in my mySQL database on the onclick of a delete button. But instead of the one mySQL row getting deleted, all rows in the database get deleted.
I am targeting just the specific ID, so I am unclear as to why all other ID's are getting deleted.
HTML:
<?php foreach ($movies as $movie) : ?>
<div class="col-4">
<div class="card card-cascade">
<div class="view gradient-card-header purple-gradient">
<h2><?php echo $movie['name']; ?></h2>
<p><?php echo $movie['genre']; ?></p>
</div>
<div class="card-body text-center">
<!-- Delete -->
<a type="button" class="btn-floating btn-small btn-dribbble delbutton" data-toggle="tooltip" data-placement="top" title="Delete" id="<?php echo $movie['id']; ?>"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
</div>
</div>
</div>
<?php endforeach; ?>
JS:
$(function () {
// Tooltips Initialization
$('[data-toggle="tooltip"]').tooltip();
// Delete Movie
$(".delbutton").click(function() {
console.log('watch me')
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "../movieApp/delete.php", //URL to the delete php script
data : {id:info},
success : function() {
console.log("success");
},
error: function () {
console.log("failed");
},
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
PHP:
require 'config/config.php';
require 'config/db.php';
if($_POST['id']){
$id=$_POST['id'];
$delete = "DELETE FROM movies WHERE id=$id";
$result = $conn->query($delete);
}
if (mysqli_query($conn, $sql)) {
mysqli_free_result($result);
mysqli_close($conn);
echo "Worked!";
exit;
} else {
echo "Error deleting record";
}
You set ajax method POST, But Post data format is not correct as per your requirement.
Change your ajax Data like as
//var info = 'id=' + del_id;
var info = {
id : del_id
}
And
$.ajax({
/*...*/
data : info,
/*.../
});
And also check if your id field is string, If integer then change the Query string to -
#$delete = "DELETE FROM movies WHERE id='$id'";
$delete = "DELETE FROM movies WHERE id=$id";
Also change -
#$_POST['info']
$_POST['id']
Because, You didn't set $_POST['info'] anywhere in your code.
Note : And don't forget to console your correct Ajax URL
In your HTML use data-id="<?php echo $movie['id']; ?>" for the tag. Then in your JS you can pick up the value like so: var del_id = $(this).data("id");. I would also inspect element in your browser to see if you are in fact sending an "id" to your PHP script. If you are then possibly you may want to enable error debugging in your PHP script like so: error_reporting(E_ALL);
ini_set('display_errors', 1);. Also wouldn't hurt to change your SQL statement to something like this: $delete = "DELETE FROM movies WHERE id='" . $id . "'";. Good luck with this one doesn't sound too hard.

Simple validation for <td contenteditable="true"> element.

I have a table which consists of data from MYSQL, and whenever I make changes in an element in table, my database will be updated by ajax.
This is my javascript code to send the data in editable row.
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
$("#tabs-1").load(location.href + " #tabs-1");
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
After the function above, saveedit.php will deal with updating the database and it's functional.
Then, this is my table in html and these table elements are editable.
<?php
$result = FUNCTION_TO_RETRIEVE_DATA_FROM_DB;
foreach($result as $k=>$v){
?>
<tr>
<td><?php echo $k+1; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'memberID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["memberID"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'surname', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["surname"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'forename', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["forename"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'address', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["address"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'gradeID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["gradeID"]; ?></td>
</tr>
<?php
}
?>
This code is working, but the question I would like to ask is, how can I validate the data entered by the user into this element? For example, what if I would like to check the initial column, memberID, cannot be longer than 6 characters, or if it is required or not. What I am trying to do is to validate entered data before sending it using AJAX but now but I have no idea how validation can be done in the table element.
Before calling ajax validate your column by putting condition before it.
` function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
$("#tabs-1").load(location.href + " #tabs-1");
if(column == "memberID"){
if(editableObj.innerHTML.length > 6 ) {
alert("cannot be longer than 6 characters");
return false;
}else{
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
}
}`
Before calling the saveToDatabase() function put the desired validation on the entered value like:
var newVal = editableObj.innerHTML;
// Your validation on newVal, if validation successful call the saveToDatabase() function
// Otherwise show an error message and do nothing
Check the passing parameter and only process ajax when your condition is satisfied.
function saveToDatabase(editableObj,column,id) {
//If(editableObj.length > 6) // Case of string Check your other condition.
if(editableObj.toString().length > 6) // in case it is not string.
{
alert(Condition fail);
}
else
{
// Your ajax call -------
}
}
Or :
Check your passing data before calling saveToDatabase function.

Appending action to the last appended row using AJAX

I am using AJAX to send data to server and update the current page with no reloading. I have this script:
$.ajax
({
url: 'insert.php',
type: 'POST',
data: {data1: emp, data2: pos, data3: sal},
dataType: "json",
success:function(data)
{
var emp_n = data.emp_name;
var btn = '<button type="Button" id="del" name="del" class="btn btn-danger">Delete</button></a>';
$("#before_tr").before("<tr><td>"+data.emp_name+"</td><td>"+data.position+"</td><td>"+data.salary+"</td><td>"+btn+"</td></tr>");
},
As you see, I have a delete button that should be added too to the same row. But this button won't be active until I refresh the page. What I want is to append action like this PHP Based code for a delete button of each row:
<tr id="<?php echo $row['id']; ?>">
<td contenteditable><?php echo $row['emp_name'] ?></td>
<td contenteditable><?php echo $row['position'] ?></td>
<td contenteditable><?php echo $row['salary'] ?></td>
<td><button type="Button" id="del" name="del" class="btn btn-danger">Delete</button>
</tr>
<?php } ?>
What I've tried is the following:
$.ajax
({
url: 'insert_with_ajax.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: emp, data2: pos, data3: sal},//Now we can use $_POST[data1];
dataType: "json", //JSON or HTML
success:function(arr)
{
//if(data=="success")
//{
//alert("Data added");
var emp_n = arr.emp_name;
var btn = 'Delete</button>';
$("#before_tr").before("<tr><td>"+arr.emp_name+"</td><td>"+arr.position+"</td><td>"+arr.salary+"</td><td>"+btn+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
//}
},
Where I added this line <a href="delete_id.php?id="'+emp_n+' to the following:
var btn = 'Delete</button>';
When I click on delete button of the last one added using AJAX the page go to delete_id but the link is like this:
delete_id.php?id=
id is equal to empty.
So, What I am working on is like when we add a status on Facebook and you delete it directly with no need for reloading the page. I am trying and I hope that someone could help.
Check your code once again:
'<a href="delete_id.php?id="'+emp_n+'>'
^ - see? you have a closing " here.
This means that no values will be added to your href attribute as it's already closed.
Proper code is:
'<a href="delete_id.php?id='+emp_n+'">'
^ -see? closing " moved after emp_n

PHP Yii- Clicking list then display complete data of list clicked in modal

I've just started working with Yii framework. And I was having a hard time
passing data of list to a modal when clicked. I was already using AJAX.
My modal is in the same view with my list.
So my code basically looks like this..
This is my view:
<div id="view-data" class="modal viewdata-modal fade hide" data-backdrop="true">
<!-- the full data from clicked list -->
</div>
.
.
.
<div>
<!--table--list of something-->
<tr class="odd">
<td class=" "><a onclick="checkData('<?php echo $inbox_list_data['id']; ?>')" data-toggle="modal" data-target="#view-mail" ><?php $list_data['title'];?></td> else echo $msg; ?></a></td>
<td class=" "><?php $date = $list_data['date_updated']; echo date('Y / m / d',strtotime($date));?></td>
</tr>
</div>
Then this is my JS:
function checkData(id) {
$.ajax({
type : 'POST',
url : "/link/data/view",
data : {'id' : id},
});
}
Then in my controller:
public function actionIndex()
{
//getting list from db then render
}
public function actionView()
{
$this->initPage();
Helper_Site::supportMessageJS();
if(isset($_POST['id']))
{
$id = $_POST['id'];
//use the id for getting the data then ...??
}
//I cannot render since i'm passing it to modal and i dont have to refresh the page right?
$this->renderPartial('index', array('data1'=>$data1, 'data2'=>$data2, true, false);
}
So how can i pass my data back to my view? But i'm also not sure of my JS...
Any idea is greatly appreciated. Thanks
You have to update your view container after ajax is done.
function checkData(id) {
$.ajax({
type : 'POST',
url : "/link/data/view",
data : {'id' : id},
}).done(function( data ) {
$("#view-data").html(data);
}
});
}

Categories

Resources