Error fetching data with ajax - javascript

I am trying to edit some data using boostrap and ajax, however when I run the code an error occurs.
The error is on the line
onclick="editUser('.$row->id.');"
How do I fix this?
My JavaScript code is
function edit(id) {
$.ajax({
url : "<?php echo site_url('edit')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="name"]').val(data.name);
$('[name="id"]').val(data.id);
$('[name="name"]').focus();
$('#edit').modal('show'); // show bootstrap modal when complete loaded
},
error: function (jqXHR, errorThrown)
{
alert('Error ajax');
}
});
}
My HTML code is
<?php
$no = 1;
foreach ($user as $row) {
?>
<tr>
<td><?php echo $no; ?></td>
<td><?php echo $row->nik; ?></td>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->name; ?></td>
<td align="center">
<span class="glyphicon glyphicon-pencil"></span>
</td>
<?php $no++; }?>

You have a bit of php/javascript soup. Your href value needs to be enclosed in php tags. Change:
onclick="editUser('.$row->nik.');"
to
onclick="editUser('<?php echo $row->nik;?>');"

An addition to the hairmot's answer:
You would also like to escape any characters that would interfere with the html:
onclick="editUser('<?php echo htmlspecialchars($row->nik) ?>');"

Related

Delete from database using javascript

I have a page containing a database table with all the rows and columns.
What I am trying to do is to select all the rows I want and then delete them when I click on the button.
This is what I've done so far in the table.php page:
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<button id="button_apaga" type="button" onclick="delete()" > DELETE </button>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td><input type="checkbox" name="check" id="checkbox" /></td>
</tr>
<?php } ?>
</table>
<?php }
else{
echo "0 resultados";
} ?>
JavaScript Page (home.js):
function delete(id){
var check = document.getElementById('checkbox');
if(check.checked) {
// sql query
}
My question is how can I do que sql query considering it's in a different page. Can I just open php and put the query inside?
Also how can I receive all the IDs from the selected rows to the function?
Thank you in advance.
One approach would be to use AJAX. For the purpose of condensing the code, I'm going to also incorporate jQuery into this solution. I am also going to change your checkbox to an individual button link for the sake of making this a bit less code. A solution to delete multiple at the same time could work similarly to this, but since you're using AJAX most likely this is going to be easier for your users.
Modify table.php
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row" class="palavras_row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td>Delete</td>
</tr>
<?php } ?>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1"></script>
<script type="text/javascript">
(function($) {
$(document).on('click', '.palavras_row a.palavras_delete', function() {
var _id = $(this).attr('data-id');
var _row = $(this).parent().parent();
$.ajax({
url: 'delete.php',
data: {
idpalavras: _id
},
type: 'POST',
dataType: 'json',
success: function(__resp) {
if (__resp.success) {
_row.remove(); // Deletes the row from the table
}
}
});
});
})(jQuery);
</script>
Create a new file in the same folder as your table.php and name it delete.php
<?php
$idpalavras = filter_input(INPUT_POST, 'idpalavras', FILTER_SANITIZE_NUMBER_INT);
$success = false;
if ($idpalavras) {
include "config.php"; //connection to database
$funcao="delete from palavras where idpalavras = " . $idpalavras;
$result=mysqli_query($link, $funcao);
$success = true;
}
header('Content-Type: application/json');
echo json_encode(array('success' => $success));
The solution above sends a simple command to your PHP backend where the delete query can be run by PHP. You cannot run a mysql command directly from javascript since that is frontend code.
This code is a functional solution, but it is abbreviated; a more complete solution would have more detailed handling of potential errors (either via AJAX or processing your delete query). It should also have some security on your delete.php to make sure unauthorized users aren't able to delete records without the proper permission to do so.

displaying data from the database that can be removed from the php page with a checkbox using ajax,

guys, I am doing a project in PHP where I should display in a page data from the database and remove from the page(not database) if I checkbox them using ajax. any source or link that could help me understand better this? thank you!!
p.s all I've done so far is deleting the data from the page and database at the same time
while($row = mysqli_fetch_array($result))
{
<tr id="<?php echo $row["id"]; ?>" >
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["surname"]; ?></td>
<td><input type="checkbox" name="id[]" class="delete" value="<?php echo $row["id"]; ?>" /></td>
**deleting method **
$.ajax({
url:'delete.php',
method:'POST',
data:{id:id},
success:function() {
for(var i=0; i<id.length; i++){
$('tr#'+id[i]+'').css('background-color', '#ccc');
$('tr#'+id[i]+'').fadeOut('slow');
If you're not deleting from the database then using AJAX isn't needed at all; use a javascript event listener that is triggered by a "delete selected" button or by the checkboxes themselves to remove the row from the table

How to use jQuery POST instead of html form to delete table entry

I am trying to delete the table entry without opening the .php file using jQuery post.
The whole thing works without problems when I just use the usual html post form.
The alert(data) does not trigger, it only adds ".../?player_id_del=1" or whatever ID click into the URL.
What am I doing wrong?
Here is some of my index.php, i get the whole data from a database:
<table class = "table table-hover">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr>
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<form id="del-form">
<div>
<input type="number" id="player_id_del" name="player_id_del" value="<?php echo htmlspecialchars($player["PLAYER_ID"]); ?>" />
</div>
<div>
<button type="submit" id="submit-btn" class="btn btn-danger">Delete</button>
</div>
</form>
<script>
$("#submit-btn").click(function(){
$.post("deletePlayer.php", $("#del-form").serialize() , function(data) {
alert(data);
});
});
</script>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
Here is my deletePlayer.php:
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
echo "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
echo "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
?>
Thank You in advance for any help!
By default jQuery's click event reload the document so, you should try using,
$("#submit-btn").click(function(e){
e.preventDefault();
e.stopPropagation();
});
Also instead of $.post, try using $.ajax
There are many issues in your code
E.g IDs for form and delete input button are repeating (id of element should not be same it should be unique),
The following code is the tested and working.
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
$response = array();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
$response["success"] = 1;
$response["id"] = $player_id;
$response["message"] = "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
$response["success"] = 0;
$response["message"]= "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
echo json_encode($response);
?>
<table class = "table table-hover" id="mPlayersTabel">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr id= "<? echo $player["PLAYER_ID"]; ?>">
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<div>
<button type="submit" player-id="<? echo $player["PLAYER_ID"]; ?>" class="btn btn-danger" >Delete</button>
</div>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
<script>
$(document).ready(function(){
$(".btn-danger").on("click touchend" , function(){
var id = $(this).attr("player-id");
$.ajax({
url: 'deletePlayer.php',
type: 'POST',
data: {
player_id_del: id
},
dataType: 'json',
success: function (response) {
//Add this line and try
response = JSON.parse(JSON.stringify(response));
alert(response['message']);
switch (response['success']) {
case 1:
$("#mPlayer" + response['id']).remove();
break;
}
}
});
});
});
</script>

Display progress of a long mysql query using php

Im trying to display the progress percentage of a long mysql query using php
I have button to make the filter in my database , that runs a js function that calls using ajax a php file
function show(){
$.ajax({
url:"backend.php",
type:"POST",
beforeSend:function(){
$("body").addClass("loading");
},
success:function(data){
$("tbody").html(data);
$("body").removeClass("loading");
}
});
}
and i have a loading div
<div class="mod">
<h1>Progress : <input type="text" id="percents"></span>
</div>
on my backend file , i fetch the result using foreach loop on tbody
inside that tbody , i increment a $counter then calculate the percentage using
$percent = ($conteur/$total) * 100;
Now, when i write javascript code inside the loop , like alert or console.log it works perfectly and display the percentage progress
while($row1=mysql_fetch_array($rs1)){
$conteur++;
$percent = ($conteur/$total) * 100;
$cust_perc=$percent;?>
<script>document.getElementById("percents").value = <?php echo $cust_perc ?>+" %";</script>
<tr>
<th>Centrale</th>
<td><?php echo $row1[5];?></td>
<td><?php echo $row1[0];?></td>
<td><?php echo $row1[1];?></td>
<td><?php echo $row1[2];?></td>
<td><?php echo ($row1[4]/1000)." T"; $tonnage+=($row1[4]/1000);
$tonnage_roch+=($row1[4]/1000);?></td>
<td>-</td>
<td><?php echo $row1[3];?></td>
<td>-</td>
<td><?php echo $row1[6];?></td>
<td><?php echo $row1[7];?></td>
<td>-</td>
<td>-</td>
</tr>
<?php
} ?>
but when i try to make change in my loading div input , mytable looks endomaged and no changes done !!
can someone has an idea please ?
Logically it will go like this:
$('#percents').val('<?php echo $percent; ?>');
but the information you provided in question is very less to be sure.

Why can I not get the parent of an element from content loaded by Ajax?

With this code, the ajax html is loaded fine and the click event triggers but when I try to get the form parent of the clicked button it seems to fail. The output from the alert is 'undefined'. How can I get the form data?
$( "#offertable" ).load( "offer-get.php", function() {
//$('#loadingDiv').hide();
$("#offertable").on('click', '#submit', function(event){
alert($(this).parents('form:first').attr("action"));
//event.preventDefault(); // this will prevent from submitting the form
//$(this).prop('disabled',true);
var postData = $(this).parents('form:first').serialize();
var formURL = $(this).parents('form:first').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert("Offer updated successfully");
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("Failed to update offer");
}
});
return false;
});
} );
I've tried using the submit event on the form (which would give me form object that I can get the data from);
$("#offertable").on('submit', '#updateoffer', function(event){
But it never fires.
EDIT: Form returned from offer-get.php
<tr>
<form action="offer-update.php" id="updateoffer" name="updateoffer" method='post'>
<input type="hidden" name="pendingofferid" value="<?php echo $record['pendingofferid'] ?>">
<input type="hidden" name="offerid" value="<?php echo $record['offerid'] ?>">
<input type="hidden" name="oldpaused" value="<?php echo $record['paused'] ?>">
<input type="hidden" name="oldpayout" value="<?php echo $record['payout'] ?>">
<td><?php echo $record['offerid']; ?></td>
<td><img src="<?php echo $record['picture']; ?>" height="50" width="50"></td>
<td><?php echo $record['name']; ?></td>
<td><?php echo $record['trackinglink']; ?></td>
<td><?php echo $record['country']; ?></td>
<td><?php echo $record['device']; ?></td>
<td>
<?php if ($approved) : ?>
<input type="number" name="payout" min="0" step="0.01" value="<?php echo $record['payout']; ?>">
<?php else: echo $record['payout']; ?>
<?php endif; ?>
</td>
<td>
<?php if ($approved) : ?>
<select name="status" class="form-control required" >
<option value="Live" <?php if(!$paused) echo 'selected="selected"'; ?> >Live</option>
<option value="Paused" <?php if($paused) echo 'selected="selected"'; ?> >Paused</option>
</select>
<?php else: echo 'Pending'; ?>
<?php endif; ?>
</td>
<td>
<?php if ($approved) : ?>
<button type='submit' name='submit' id='submit' class='btn btn-userid'>Update</button>
<?php endif; ?>
</td>
</form>
</tr>
Obviously this is not the whole code, don't want to release clients sensitive information but this should be enough. This part is looped for each result from the DB query. So there are multiple forms with same ids. If I use different ids for each form, I'm not sure how I'd get the event to fire otherwise since the number of rows isn't known until the data is returned.

Categories

Resources