What is wrong here?
My PHP/HTML (The only part that matters):
if(isset($_POST['submit']))
{
$date = date('Y-m-d', strtotime(str_replace("-","/",$_POST['dateOfEntry'])));
$username = $_POST['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px"><input type="button" name="edit" value="Edit"></td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td>'.$row['Date'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['TypeOfDowntime'].'</td>';
echo '<td>'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
My Ajax/Javascript:
$(document).ready(function()
{
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id':'del_id'},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
My PHP (on an external script: machineEntryLogEdit.php):
include('connServer.php');
$deleteID = $_POST['del_id'];
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_connect($connection, $query);
if(isset($result))
{
echo "YES";
}
else
{
echo "NO";
}
?>
I have searched around and around for solutions but no avail. The only things it does is delete the record from the HTML table, but not from the database, causing the supposed-to-be-deleted row to reappear after refresh. I am still very new to AJAX (in fact I just learned it myself today) and still reading the documentations and forums. Thanks.
This should be data: {'del_id': del_id} remove quotes so it react as a variable, not just a single string. And one more thing, your delete query does not execute cause you're using :
$result = mysqli_connect($connection, $query);
Should be mysqli_query like the one you did on selecting data's part:
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_query($connection, $query);
It looks to me like you didn't pass the submit variable in your data. If you want to include a form you need to pass the data, right now the server is receiving only one parameter, del_id
Related
I have a table of Data which is pulled via SQL into DataTables. I want to use AJAX to run an SQL query which deleted the row based on $id = $row["id"];.
Index.php:
$link = mysqli_connect("localhost", "bradlyspicer_root", "", "bradlyspicer_ResellerDB");
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
echo 'success';
echo $id;
} else {
echo 'fail!';
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
Functions.php:
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
echo 'success';
} else {
echo 'fail!';
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
Custom.js:
$( ".delbtn" ).click(function(){
var itemID = $(this).attr("itemID");
console.log(itemID)
$.ajax({
url:"functions.php", //the page containing php script
data: { id: itemID}, // itemID passed as id
type: "POST", //request type
success:function(result){
alert(result);
},
error: function() {
alert('Error occured');
}
});
});
I can't find where I pass the $id in the button from Index.php to Functions.php, any explanation would be appreciated.
Update: Since updating the script and trying to Debug, I'm not getting much of a response from the error which outputs:
fail!Error: .
Index.php:
Add a delete button identifier class delbtn and a data attribute that carries this row's id data-itemID
<?php
while($row = mysqli_fetch_array($dataTablesResult)){
$id = $row["id"];
echo '
<tr>
<td>
<button type="button" data-itemID="'.$id.'" class="delbtn btn btn-danger" >Remove</button>
</td>
</tr>
';
}
?>
Functions.php:
Capture $_POST['id'] sent by ajax
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
}
Custom.js:
Run the jQuery function when a button with .delbtn class is clicked. Capture and store the row id from data attribute as $(this).data("itemID"). Then send the data using data: { id: itemID} within ajax request
$(".delbtn").click(function(){
itemID = $(this).data("itemID");
$.ajax({
url:"functions.php", //the page containing php script
data: { id: itemID}, // itemID passed as id
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
i think if you change this line :
mysqli_stmt_bind_param($stmt, "s", $id);
to this is one:
mysqli_stmt_bind_param($stmt, "i", $id);
it may works
I have this php page with javascript ajax which calls another php file. But every time it calls, it refreshes the page.
I tried these two codes but still it keeps refreshing after calling the `php file:
e.preventDefault();
//and
return false;
But still it keeps redirecting/refreshing to the same page. I don't even have redirecting headers in php file I'm calling.
This is my HTML
<div class="col-md-3 col-sm-6 col-6 ad-image">
<label for="file1">
<img id="blah1" src="http://placehold.it/500" alt="..." class="img-thumbnail">
<input type="button" value="Remove Photo" style="margin-top: 5px;" class="btn btn-danger btn-sm" id="image-remove-btn-1">
<small id="textCount" class="form-text text-center bold">Thumbnail</small>
</label>
</div>
Here's my javascript
$("#image-remove-btn-1").click(function (e) {
e.preventDefault(); //doesn't work still page keeps refreshing
$('#blah1').attr('src', 'http://placehold.it/500');
var userId =<?php echo $userId ?>;
var adId =<?php echo $adId ?>;
deletePhoto('blah1', userId, adId); //this is the function with ajax
$(this).hide();
return false; //doesn't work still page keeps refreshing
});
Here's the deletePhoto() function:
function deletePhoto(imgeName, userid, adId) {
$(document).ready(function () {
$.ajax({
url: 'includes/remove-ad-image-inc.php',
dataType: 'text', // what to expect back from the PHP script, if anything
data: {
userId: userid,
adId: adId,
imgeName: imgeName
},
type: 'post',
success: function (php_script_response) {
alert(php_script_response); // display response from the PHP script, if any
}
});
});
}
This is my php remove-ad-image-inc.php I am calling through above ajax
<?php
include_once './dbConnection.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$userId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "userId"));
$adId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "adId"));
$imgeName = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "imgeName"));
if (isset($userId) && isset($adId) && isset($imgeName)) {
$sql = "SELECT * FROM adimage WHERE adimageno=? AND adid=? AND userid=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "error!";
} else {
mysqli_stmt_bind_param($stmt, "sii", $imgeName, $adId, $userId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$ImageId = $row['adimageid'];
}
$fileName = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "*";
$fileInfo = glob($fileName);
$fileExt = explode(".", $fileInfo[0]);
$fileActualExt = $fileExt[1];
$file = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "." . $fileActualExt;
array_map('unlink', glob($fileName));
$sql = "UPDATE adimage SET adimagestatus=1 WHERE adimageid='$ImageId';";
mysqli_query($conn, $sql);
exit();
}
}
Can someone please help me with a solution?
I have this strange issue, happening to my PHP script, On page load the AJAX script runs and also after the second time the AJAX script runs it works and sends data to PHP, but i seem to not understand why the PHP script doesn't process the incoming POST request the second time it is sent in when i clean the input text box and type again, i get a blank response.My code for more expatiation.
index.php :
<input type="text" onkeyup="searchmedia(this)" placeholder="Search for seller with UNIQUE ID or Name.">
<div id="resut" style="margin-top:-24px!important;">
//where the ajax result is returned
</div>
<div style="margin-top:-24px!important;" id="normal">
//bla bla data here
</div>
<div id="hui" style="display:none;"><img src="../ajax5.gif">
</div>
<script>
function searchmedia(e) {
var tuq = $(e).val();
if (tuq == "") {
$('#resut').hide();
$('#normal').show();
$('#hui').hide();
} else {
$('#normal').hide();
$('#hui').show();
$.ajax({
type: 'POST',
url: 'sellersmessageajax.php',
data: {tuq: tuq},
timeout: 5000,
cache: false,
success: function (r) {
//console.log(r);
$('#resut').html(r);
$('#normal').hide();
$('#hui').hide();
},
error: function () {
alert("Could not search, reload the page and try again.");
$('#normal').show();
$('#hui').hide();
}
});
}
}
</script>
sellersmessageajax.php :
<?php include('../connect.php'); ?>
<?php
if (isset($_POST['tuq']))
{
$term = $_POST['tuq'];
$term = mysqli_real_escape_string($con,
$term); //WHEN I ALERT HERE THE SECOND TIME I SEE THE INPUT TEXT DATA THAT CAME IN BUT PLEASE CHECK AFTER THE **FOREACH**
$condition = '';
$query = explode(" ", $term);
foreach ($query as $text)
{
$condition .= "name LIKE '%" . mysqli_real_escape_string($con,
$text) . "%' OR reign_uniqeer LIKE '%" . mysqli_real_escape_string($con, $text) . "%' OR ";
}
//WHEN I ALERT HERE I GET NOTHING
$condition = substr($condition, 0, -4);
$zobo = "ORDER BY name";
$sql_query = "SELECT * FROM sellers_login WHERE " . $condition . $zobo;
$result = mysqli_query($con, $sql_query);
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$v_ida = $row['id'];
$v_namea = $row['name'];
$v_reign_uniqeera = $row['reign_uniqeer'];
?>
<div style="border-bottom:0.1px solid #eee;padding-bottom:20px;margin-top:20px;">
<a class="zuka" title="<?php echo $v_ida ?>" id="<?php echo $v_ida ?>"
style="color:#666;text-decoration:none;outline:none!important;cursor:pointer;">
<b style="color:blue;"><?php echo $v_namea ?></b>
<br/>
<div style="height:auto;max-height:30px;">
<b>UNIQUE ID :</b> <b style="color:red;"><?php echo $v_reign_uniqeera ?></b>
</div>
</a>
</div>
<?php
}
}
else
{
?>
<h1 class="zuka" style="text-align:center;margin-top:20%;"> No result found.</h1>
<?php
}
}
?>
Second time after clearing the data result set to hide. second time data is returning but it's hide
Add this line in ajax success block
$('#resut').show(); // Add this line
you are sending the var tuq wrongfully. Try this:
data : {"tuq": tuq}
I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here
now the code for the php :
comment.php
$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');
$sql = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
$row_count = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
array_push($arr , $row);
}
mysqli_close($con);
echo json_encode($arr);
And the ajax to retrieve data is: script.js
function refreshComment() {
requestData = $("#photo_id_comment").serialize();
$.ajax({
url: "http://localhost/udemy/app_php/includes/comment.php",
type: "get",
data: requestData,
dataType: "text",
success : function (data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
/* $('#author_comment').html(item.author);
$('#chat_box').html(item.body);*/
});
},
error: function (http, status, error) {
alert('Some error occurred :'+error);
}
});
return false;
}
setInterval( refreshComment , 5000 );
And the html where the data is not display is: photo.php.
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 id="author_comment" class="media-heading"></h4>
<p id="chat_box"></p>
<p class="text-info">This is post at: </p>
</div>
</div>
Please try this one,
$sql = "SELECT * FROM comments WHERE photo_id = " . $database->escape_string($photo_id) ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)){
$arr[] = $row;
}
echo json_encode($arr);
and change ,
dataType:'json' instead of dataType:'text'
in script.
change dataType:text to dataType:JSON
EDIT
use this instead of $.each
for(var i = 0;i < data.length ; i++)
{
/*access data as data[i].orfeas*/
}
PHP
$array = array();
$i = 0;`
foreach($res as $r){
$array[$i] = $r;
$i++;
}
header('Content-Type:Application/json');
echo json_encode($array);
EDIT2
USE Header to help jQuery to identify the response type and then jQuery will parse the JSON and you can access it by using a loop above mentioned
in your script.js file make change on success function of ajax:-
success : function (data) {
$.each($.parseJSON(data), function(key,item){
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
});
}