Item isn't deleted from database through ajax call - php

I'm running around the issue which I don't really know how to solve - I simply want to remove uploaded file from the database, but I'm failing to do so.
My personal guess now is that my delete_shop_item.php doesn't work or that upload.php loop messes up the deletion process from the database (but that's only my guess).
Ajax:
$(document).on('click', '#rmvBtn', function() { /*press the button to remove selected item*/
del_title = $("#"+ $("#selectOpt").val()); /* select dynamically generated option to remove*/
$.ajax({
type: 'POST',
url: 'delete_shop_item.php',
cache: false,
processData: false,
data: {title:del_title.val()},
success: function() {
$("#" + $("#selectOpt").val()).remove();
$("#selectOpt option:selected").remove();
}
});
delete_shop_item.php
$title = $_POST['title'];
$pdo = new PDO('mysql:host=localhost;dbname=project', 'root', '');
$query = 'DELETE FROM photos WHERE title = :title';
$stmt = $pdo->prepare($query);
$stmt->bindPARAM(':title', $title);
$stmt->execute();
upload.php
<?php $count = 1;
while($data = mysqli_fetch_array($result)) {
if($count === 1) {
echo "<div class='img_container'>";
}
echo "<div class='img_div' id='".$data['title']."'>";
echo "<img src='uploads/" . $data['filename']."'>";
echo "<p class='img_title' >" .$data['title']. "</p>";
echo "<p class='img_desc'>" .$data['photo_description']. "</p>";
echo "<p>" .$data['price']. "</p>";
echo "</div>";
if($count % 5 === 0) {
echo "</div>";
$count = 1;
continue;
}
$count++;
}
?>

try data: {title:del_title} in ajax request

Related

PHP Script running without redirection

I have a database with two tables: accounts and recipes(each have their own ID column).
I have a page that displays all the recipes. I want to enable users to add recipes to their favourites in accounts table. Once user is logged in, $_SESSION['user_id'] is set.
I have script that will add the recipe id to the favourites in accounts table, but I don't know how to run it without redirecting from the page that displays all recipes.
Here is what i have so far:
_view.php
<?php
$result = $mysqli->query("SELECT * FROM recipes");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "Error!";
echo "<div class='error-mess'>" . $_SESSION['message'] . "</div>";
}
else {
while ($row = mysqli_fetch_array($result)) {
$slug = $row['slug'];
$ingr = json_decode($row['ingr']);
$ingr_count= count($ingr);
$id = $row['id'];
echo '<div class="container recipe mb-2">';
echo '<img class="" src="/images/recipes/';
echo $row['img'];
echo '"/>';
echo '<div class="title-cats"><a href = "/recipe_preview.php?slug=' . $slug . '">';
echo $row['title'];
echo '</a></div>';
echo '<h4>Ingredients:</h4><br>';
for($i = 0; $i<$ingr_count;$i++){
$num = $i + 1;
echo $num . '. ';
$ingrs = json_decode($ingr[$i],true);
print_r($ingrs[0]);
echo '<br>';
}
echo '<br><button type="submit" class="btn" name="add">Read More</button>';
//favourites link
echo '<span class="fa fa-heart ml-3"></span>';
echo '</div><hr>';
}
}
_favourite.php
<?php
//relationship
require 'db.php';
$user_id = $_SESSION['user_id'];
//$favourite_id = $_POST['fav'];
$favourite_id = $_GET["id"];
echo $favourite_id;
echo $user_id;
$result = $mysqli->query("SELECT favourites FROM accounts WHERE id ='$user_id'");
if ( $result === null) {//doesnt work
$favs = array();
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
echo 'null';
}
else{
$favs = array();
$result = json_decode($result,true);
array_push($favs, $result);
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
}
$sql = "UPDATE accounts SET favourites ='$new_favs' WHERE id = '$user_id'";
if ( $mysqli->query($sql)){
echo '<div class="error-mess">Recipe sucessfully saved!</div>';
}
else{
echo '<div class="error-mess">NOT</div>';
}
.js -jquery library is there
$(document).ready(function() {
$('#favourite').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
id: $(this).data('id'),
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});

Pass jquery data beween php pages

I have a php class handler that I am using to create html output for my exercise-group.php page. However, this output (an array of items) is called on by using Jquery/AJAX and added to the page. However, there are some data values that are not displayed because they will be passed onto the exercise-single.php page. How can I gather these data values using jquery, load them into a php value and store them into a $_Session variable so the exercise-single.php can display these vars after the user clicks on on href tag. Sorry for the long post but this is the best I can do to explain what im trying to do.
Exercise.class.php
class Exercises {
public $vidSource;
public function displayExercises($result) {
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<div class='media'>" .
"<div class='media-object pull-left'>" .
"<a href='exercise-single.php'><img src='".$row["ImgResource"]."' class='img-responsive' alt='curl'></a>" .
"</div>" .
"<div class='media-body'>" .
"<h4 class='media-heading'><a href='#'>".$row["Exercise"]."</a></h4>" .
"</div>" .
"</div>";
$vidSource = $row["VidResource"];
}
} else {
echo "<img src='https://media.giphy.com/media/cwTtbmUwzPqx2/giphy.gif' class='img-responsive'>";
echo "<h3 class='media-heading'>No workouts exist for this muscle yet.<br>Please try another one.</a></h3>";
}
}
}
?>
ExerciseHandler.php
<?php
include 'Exercises.class.php';
include 'dbconnect.php';
if(isset($_POST['muscle'])){
$muscle =$_POST['muscle'];
$connect = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM exercises WHERE Muscle = '".$muscle."'";
$result = $connect->query($sql);
$exercises = new Exercises();
$exercises->displayExercises($result);
}
?>
loadExercises.js
var muscle_id;
function getMuscle(clicked_muscle){
muscle_id = clicked_muscle;
$.post("ExerciseHandler.php", {
muscle: muscle_id
},
function(data, status){
$("#exercise-list").html(data);
});
}
//Handler
echo $exercises->displayExercises($result);
//Exercise Class
public function displayExercises($result) {
if ($result->num_rows > 0) {
return json_encode(
array(
'status' => 'success',
'data' => $result->fetch_assoc())
);
} else {
return json_encode(
array(
'status' => 'error',
'data' => array(
'url' => "https://media.giphy.com/media/cwTtbmUwzPqx2/giphy.gif",
'class' => 'img-responsive',
'prompt' => 'Please try another one.'
)
)
);
}
}
// Jquery Here
$.ajax({
url : "ExerciseHandler.php",
method : "POST",
success : function(response){
var result = JSON.parse(response);
if(result.status == 'error'){
$('img').attr('src',result[0].url);
$('img').attr('class',result[0].class);
$('h3').text(result[0].prompt);
}else{
$.each(result.data,function(index,value){
// do the html append thing here
});
}
}
});
if you want to access data globally in all page per session you should create session like this in while block like this,
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$_SESSION["name"] = $row["column_heading"];//create session
echo "<div class='media'>" .
"<div class='media-object pull-left'>" .
"<a href='exercise-single.php'><img src='".$row["ImgResource"]."' class='img-responsive' alt='curl'></a>" .
"</div>" .
"<div class='media-body'>" .
"<h4 class='media-heading'><a href='#'>".$row["Exercise"]."</a></h4>" .
"</div>" .
"</div>";
$vidSource = $row["VidResource"];
}
} else {
echo "<img src='https://media.giphy.com/media/cwTtbmUwzPqx2/giphy.gif' class='img-responsive'>";
echo "<h3 class='media-heading'>No workouts exist for this muscle yet.<br>Please try another one.</a></h3>";
}
}
this will work. and don't forget to start session in your php files. remember, you should start session on every page of your php files in which you are going to set or get session. You could do this by simply adding
session_start();

Ajax - Sending and Receiving

I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}

Populating options list with SQL

So I'm currently in the process of trying to populate a select option list with some SQL using ajax and php. I've tried various different pieces of code however I still can't seem to crack it. Here is the ajax from the actual page its self...
$.ajax ({
url:'orderentry_ajax.php',
cache:false,
data: {'request': 'getCounty', 'County': County},
dataType: 'json',
async: false,
success: function(data)
{
$('#errMsg').html(data.errMsg);
if(data.numRecs>0)
{
//divStr = divStr + data.custName + data.contactName + data.contactNumber + data.contactEmail;
countyStr = countyStr + "<select>";
for (var i=0; i<data.dataArray.length; i++)
{
countyStr = countyStr +
"<option value='data.dataArray[i].County'>" +
"Please Select" + data.dataArray[i].County + "</option>";
}
countyStr = countyStr + "</select>";
$('#Countys').html(countyStr);
}
}
//countyStr = countyStr + data.dataArray[i].County +
});
As far as I'm concerned I did a similar exercise except I was populating the options list with another table, I've made the two pieces of ajax and php identical and it still doesnt seem to want to work. Here is the php from the ajax page....
if (trim($request) =='getCounty')
{
//product update
$County = $_REQUEST['County'];
$errMsg = "";
$con = mysqli_connect('127.0.0.1', 'root', 'c0mplex', 'HRDatabase');
//Check if connect..
if (mysqli_connect_errno($con))
{
$errMsg = 'Could not connect to Database.' . mysqli_connect_error();
}
else
{
// passed record for submit
$qryStr = "SELECT * FROM county WHERE `county` = $County";
//echo $qryStr;
$result = mysqli_query($con, $qryStr);
if (mysqli_error($con))
{
//echo (mysqli_error($con));
$errFlg=1;
$errMsg="Error during update, please try again. " . mysqli_error($con);
}
else
{
while ($row = mysqli_fetch_array($result))
{
$County = $row['county'];
$rowing = array();
$rowing['county'] = $County;
$dataArray[] = $rowing;
}
$numRecs = mysqli_num_rows($result);
}
}
mysqli_close($con);
//to test error :
// $errMsg="testing error";
$info ->dataArray = $dataArray;
$info ->numRecs = $numRecs;
$info ->errMsg = $errMsg;
$info ->County = $County;
echo json_encode($info);
//echo $msg;
}
The select option list has an ID on it of 'Countys' just to give a heads up. Any help would be greatly appreciated guys.
Cheers
Replace below line in your ajax code for adding html dymically
countyStr = countyStr + "<option value='" + data.dataArray[i].County + "'>" + "Please Select" + data.dataArray[i].County + "</option>";

How to save a page with html5 webstorage?

I have the following page, which works with MySQL, PHP and AJAX
if I click a NAME (id="orderN") it gives me back the result of the consult, which orders the names descending or ascending.
Is there any way that if you refresh(F5) the page, the result is saved as it was before closing, (ASC or DESC)?
I heard about cookies and HTML5 Storage, which is better than cookies.
if you can do it with either of them, let me know please
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
</head>
<body>
<table>
<tr><th>Name</th></tr>
</table>
<?
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "SELECT NAME
FROM STUDENTS";
$query = mysql_query($consult);
echo "<div id='DivConsult'><table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['NAME'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
<script>
$(document).ready(function() {
var contName = 0;
$('#orderN').click(function() {
contName++;
if (contName % 2 !== 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=ASC",
success: function(data) {
$('#DivConsult').html(data);
}});
}
if (contName % 2 == 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=DESC",
success: function(data) {
//alert(data);
$('#DivConsult').html(data);
}});
}
});
});
</script>
</body>
AJAX:
<?php
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "";
if (isset($_POST['tipOrder'])) {
if ($_POST['tipOrder'] == 'ASC') {
$consult = "SELECT NOMBRE
FROM STUDENTS ORDER BY NAME ASC";
}
if ($_POST['tipOrder'] == 'DESC') {
$consult = "SELECT NAME
FROM STUDENTS ORDER BY NAME DESC";
}}`
$query = mysql_query($consult);
echo "<table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['Name'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
You can do it but just saving a container (any div, span or even body) as
localStorage.variableName = document.getElementById("id");
And then you can access by using
if(Storage!=="undefined" && localStorage.variableName!=null)
now you can set value as
container.val = localStorage.variableName

Categories