Gallery delete album with ajax fails on second - php

I've created a gallery where the user delete an album via ajax, my problem is that when i click the "delete" button it works the first time, everything runs fine and the folder and pictures gets deleted, but when i move on to the second album and try to delete it, ajax gives me success BUT nothing gets deleted! the error: function doesnt give me an error either (in console) the ajax runs like normal...
Here is the button(form) that triggers ajax
<form action='' method='post'>
<input type='hidden' id='album' name='album' value='$albid'>
<center><input type="submit" class="javagalleryAlbumDeleteBtn" name="createAlbum" value="Delete Album"></center>
</form>
Here is the js file containing ajax
// CHECK THAT DOCUMENT IS READY
$(document).ready(function() {
// This is the button we are looking for.
$('.javagalleryAlbumDeleteBtn').click(function() {
// Get values from form
var album = $("#album").val();
// Put the vars in a string
var dataString = 'album='+album;
$.ajax({
type: "POST",
url: "../gallery/deleteAlbum.php",
data: dataString,
cache: false,
success: function(data){console.log(data);},
error: function(jqXHR, textStatus, errorThrown) {console.log(textStatus, errorThrown););
}// End success
}); // End ajax
return false; // avoid to execute the actual submit of the form.
}); // End #login click
}); // End document ready
Here is the deleteAlbum.php file
$getalbumid = $_POST['album'];
$sql = mysql_query("SELECT gallery_address FROM users_galleries WHERE gallery_id = '$getalbumid'") or die(mysql_error());
list($galaddress) = mysql_fetch_row($sql);
if(mysql_num_rows($sql)){
// delete the pictures in the DB
mysql_query("DELETE FROM pictures WHERE picalbum = '$getalbumid' AND picowner = " . $_SESSION['id'] . "")or die(mysql_error());
// delete the album from the DB
mysql_query("DELETE FROM users_galleries WHERE gallery_id = '$getalbumid' AND gallery_userid = " . $_SESSION['id'] . " LIMIT 1")or die(mysql_error());
// Function that deletes all content in folder and the folder
folderDelete($galaddress);
} // end delete

At first - your HTML page can't contain elements with same id, so in form :
<form action='' method='post'>
<input type='hidden' id='album' name='album' value='$albid'>
<center><input type="submit" class="javagalleryAlbumDeleteBtn" name="createAlbum" value="Delete Album"></center>
</form>
try to change on class. And in JS:
// Get values from form
var album = $(this).closest('form').find('.album').val();
this will help you with sending correct value of album ID to server side.
Second thing - look at MySQL injection article - http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

Related

update database from html form using ajax

I would like some help with ajax. I would like to update a php file which will update a database. I have a form which send the selected check box to a php file which then updates the data base. I would like to do this with ajax but I am struggling with this. I know how to update <div> Html elements by ajax but cannot work this out.
HTML script
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
var boiler = document.getElementByName("boiler").value;
var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function() {
alert("ok");
}
});
}
</script>
</body>
</html>
PHP updateDB.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="14Odiham"; // Mysql password
$db_name="heating"; // Database name
$tbl_name = "test";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
// Insert data into mysql
$sql = "UPDATE $tbl_name SET boiler=$boiler WHERE id=1";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
<?php
//close connection
mysql_close();
header ('location: /ajax.php');
?>
I would like this to update with out refreshing the page.
I just want some suggestion and first your html page code should like-
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form" id="form_id">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
// it's like cumbersome while form becoming larger so comment following three lines
// var boiler = document.getElementByName("boiler").value;
// var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
//var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
// instead of type use method
method: "POST",
url: "updateDB.php",
// instead dataString i just serialize the form like below this serialize function bind all data into a string so no need to worry about url endcoding
data: $('#form_id').serialize(),
cache: false,
success: function(responseText) {
// you can see the result here
console.log(responseText)
alert("ok");
}
});
}
</script>
</body>
</html>
Now i am turning to php code:
You used two line of code right in php
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
$_GET is used in get method and $_POST for post method, thus you are using post method in ajax and above line of code should be like
$boiler = (isset($_POST['boiler'])) ? 1 : 0;
$niamh = (isset($_POST['niamh'])) ? 1 : 0;
Update:
As well as fixing the dataString, stop the form from being submitted so that your function is used:
<form name="form" onsubmit="return false;">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
The ajax call should handle returned data from updateDb.php.
Update the php file to send data back to the server, revert to $_POST instead of $_GET and remove the header call at the bottom:
if($result){
$data['success'=>true, 'result'=>$result];
} else {
$data['success'=>false];
}
echo json_encode($data);
// die(); // nothing needed after that
Update the ajax call to handle the response and fix your dataString with '&' between params (This is why you are not getting your params properly).
var dataString = 'boiler=' + boiler + '&niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function(data) {
var json = $.parseJSON(data);
if(json.success){
// update the page elements and do something with data.results
var results = data.results;
} else {
// alert("some error message")'
}
}
});
}
document.getElementByName not a javascript function, try document.getElementById() instead
You can do this
<form name="form" onsubmit="myfunction()">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<input type="submit" value="Update"/>
</form>
Javascript:
function myFunction() {
var boiler = document.getElementById("boiler").value;
var niamh = document.getElementById("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
// i dont practice using url string in ajax data as it can be compromised with a quote (') string, instead i am using json
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: {
boiler: boiler,
niamh: niamh
},
cache: false,
}).done(function() {
alert('success');
}); // i do this because some jquery versions will deprecate the use of success callback
}
And you are getting to a post so change the $_GET in you php file to $_POST

Upload image using jquery

I have a working php code to upload image in the database. Is it Possible to transform it to jquery? If so, what do I need to do? I am new to jquery btw. Thanks
This code works just fine. But I need to do it in jquery.
<form action = 'upload.php' method = 'post' enctype="multipart/form-data">
<input type="file" name="image" > <br>
<input type= 'submit' value = 'Add' id = 'Add' name = 'Add'>
</form>
<?php
if(isset($_FILES['image']))
{
$target_Path = "images/";
$target_Path = $target_Path.basename($_FILES['image']['name'] );
move_uploaded_file( $_FILES['image']['tmp_name'], $target_Path );
$name = $_FILES['image']['name'];
}
if(isset($_POST['Add']))
{
if($_POST["Add"] == "Add")
{
$add = "Insert Into img(path) Values('$name')";
$up = mysql_query($add);
$status = "Upload success!";
print '<script type="text/javascript">';
print 'alert(" '.$status.' ")';
print '</script>';
}
}
<form action='upload.php' method='post' enctype="multipart/form-data" id="formupload">
<input type="file" name="image"/> <br>
<input type='submit' value='Add' id='Add' name='Add/>
</form>
You need to first setup a callback for the submit event of the form.
$("#formupload").on("submit", upload_image);
JQuery selectors work a lot like CSS; $("#formupload") selects the element whose id is formupload.
on is used to register a handler for an event.
Here, we are setting up a handler(the upload_image function) for the submit event of the element whose id is formupload.
Make an AJAX call to the php script.
function upload_image(event){
event = event || window.event;
// Prevent the default form action i.e. loading of a new page
if(event.preventDefault){ // W3C Variant
event.preventDefault();
}
else{ // IE < 9
event.returnValue = false;
}
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData($('#formupload')[0]),
success : function(data){
// Show success message
},
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false
});
}
You can prevent the default action of form submission, which is to load the POST response, which is what the first few lines of the function is doing.
An AJAX call is made using $.ajax which is the jQuery utility for performing an AJAX call.
The url property is to be filled by that of your PHP script.
Since it is a file upload, specify the HTTP method as POST.
The data property is the payload of the POST request, which is the content of the file you are trying to upload.
You can specify the success callback using the success property, which is the function that will be called on completion of the file upload.
You can make an ajax call instead to submit a form. You can use something like this as well:
https://blueimp.github.io/jQuery-File-Upload/
Although, you still need to have your php code in order to store the file in your server

Show DIV with AJAX in PHP After Saving Data to Mysql

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

Update MySQL table with button without refreshing page using ajax

I am trying to update a value in a database without refreshing the page using AJAX. I am completely new to AJAX but I have have managed to create a function after searching for answers on Stackoverflow but I am unable to make it work.
One the main page...
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "del_reason.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
The button (which is in a form)
<input type="button" name="delete_pos" value="Delete" class="delRow_pos"
onClick="UpdateRecord(<? echo $row['reasonID']; ?>);"/>
The contents of del_reason.php
$var = #$_POST['id'] ;
$sql = "UPDATE gradeReason SET current = 0 WHERE reasonID = $var";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
//added for testing
echo 'var = '.$var;
The database connection is ok because other functions on the same page connecting to the database work fine and so do other jquery functions but when the button is clicked the alert says the record is upodated but it isn't
The MySQL query on the del_reason.php failed because it needed it's own MySQLi connection to the database.
As soon as I added it the script worked

'Was this review helpful?' button PHP Jquery Ajax

I am building a review system with php jquery and ajax. I have written the following code already for the 'Was this review helpful?' button:
<input type='button' value='Yes' onClick = 'myCall()'
style='background-color:#556B2F;color:white;padding:2px; cursor:pointer'
name='help' />
<input type='hidden' id='randomdirectory' value='$g' name='ids'/>
$g is the variable I assigned to the id of the review which is stored in a database. The ajax script is this:
<script>
function myCall() {
var ids = $('#randomdirectory').val();
var self = this;
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('#ques1').hide();
}
});
}
and the code in the "rev.php" file is this:
<?php
include 'includes/db.php';
$q = $_POST['ids'];
if ($q != ""){
$result = mysql_query("SELECT * FROM table where id='$q'");
while($row = mysql_fetch_array($result))
{
$finalproduct = $row['numberofhelpfulvotes'];
$finalproduct1 = $finalproduct + 1;
}
mysql_query("UPDATE table SET numberofhelpfulvotes='$finalproduct1' WHERE id ='$q'");
}
?>
The problem is when I have multiple reviews on the page. When you click any of the "Yes" buttons on any of the reviews, the first review displayed gets the vote added to it, not the actual review where the button was clicked. Also when the button and text is hidden after the ajax call, the first review button and text is hidden, not the review where the button was clicked. Also a black line appears on the bottom of the page.
Any solutions to these problems will be greatly appreciated.
Thanks for all reply's. I ended up doing this which works perfectly for me:
<script>
$(function() {
$(".button").click(function() {
var ids = (this.id);
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('.' + ids).hide();
}
});
});
});
</script>
and this as the html:
<div class='$g'><font size='2' color='black'>Was this review helpful?</font> <input type='submit' value='Yes' onClick = 'myCall()' style='background-color:#556B2F;color:white;padding:2px; cursor:pointer' name='help' id='$g' class='button' /><input type='hidden' id='randomdirectory' value='$g' name='ids'/>
The php stayed the same, but I am going to update it to make it more secure.

Categories