I have a jquery delete statement and it's only deleting the NEWEST upload on my files (using mysql) Say I had "file uploaded first", "file uploaded second", "file uploaded last(newest file)". If I click "file uploaded first or second", it deletes the newest (file uploaded third).
$(document).on('click', '.del', function(){
var sid = $(this).next('.hiddenVid').val();
$.ajax({
type: "GET",
url: "delete.php",
data: {id:sid}
});
return false;
});
this is your error ->
var sid = "$vid";.
It will only produce the ID for the latest item that you put in.
Add an item to your echo statement so you can reference it later in the click function.
Add a reference to the vid in a hidden input.
Change this
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button></form></td>";
To this:
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button><input type='hidden' class='hiddenVid' value='".$vid."'/></td>";
Change your click function to reference the real sid now.
$(function(){
$(".del").click(function(){
var row = $(this).parent();
var sid = $(this).next('.hiddenVid').val();
alert(sid);
$.ajax({
type: "GET",
url: "delete.php",
data: {id:sid}
});
return false;
});
});
If you want to return the rows after the update, you'll need to spit the data back to be printed, based on the above method you use to retrieve the rows and return them, you could reuse it.
$id = mysql_real_escape_string($_REQUEST['id']);
$DB->Query("DELETE FROM `files` WHERE `id`='$id'");
if(TRUE == (unlink("uploads/$id")):
$DB->Query("SELECT * FROM `files` WHERE `author`='$username'");
$file = $DB->Get();
$obj = new stdClass();
$i = 0;
foreach($file as $key => $value){
$n = $value['name'];
$vid = $value['id'];
$date = "<td>".$value['date']."</td>";
$fname = "<td><a id='$vid' href='download.php?id=$vid'>$n</a></td>";
$option = "<td><form method='POST'><button type='submit' name='del' class='del'><i class='icon-remove'></i></button></form></td>";
$size = "<td>".filesize("uploads/".$vid."/".$value['name'])." bytes</td>";
$obj->$i = $files = "<tr>".$fname.$size.$date.$option."</tr>";
$i++;
}
echo json_encode($obj);
endif;
Now we need to change the click handler to expect a dataType and replace the existing data in the table.
$(function(){
$(".del").click(function(){
var row = $(this).parent();
var sid = $(this).next('.hiddenVid').val();
alert(sid);
$.ajax({
type: "GET",
url: "delete.php",
dataType: 'json',
data: {id:sid},
success: function(data){
$('table').empty();
$.each(data, function(i,obj){
$('table').append(obj);
}
}
});
return false;
});
});
Related
jquery:
$("input[name='flag']").on('change', function() {
event.preventDefault();
var tablerow = $(this).closest('tr');
var id = $(this).attr('id');
var flagvalue;
if($(this).prop('checked') == true) {
tablerow.css({'background-color':'rgba(175,0,0,0.2)'});
flagvalue = 1;
}
else {
tablerow.css({'background-color':'rgba(175,0,0,0)'});
flagvalue = 0;
}
alert(flagvalue);
$.ajax({
url: "../php/insert.php",
method: "get",
data: {"flagvalue":flagvalue,"id":id},
dataType: "text"
success:function(data)
{
$('#ohmygod').html(data); //it doesnt echo anything from here :(
}
});
});
php:
$insertMessage = "";
$bendera = filter_input(INPUT_POST, 'flagvalue', FILTER_SANITIZE_SPECIAL_CHARS);
$id = $_POST['id'];
if(!empty($bendera)) { //also doesn't work if change it to isset
$insertMessage = "Reached the php part";
$updateflag = "UPDATE sintok SET flag='$bendera' WHERE id='$id'";
mysqli_query($connection, $updateflag);
}
echo $insertMessage;
html:
<div id="ohmygod"></div>
include another php into html file:
<input value='.$row['id'].' type=checkbox name=flag id=flag '.$tick.'>
I have one checkbox which consist of two values, 0(unchecked) and 1(checked). From above code I don't see any changes except for the background-color of the row once the user has checked the checkbox button. But it didnt update the database.
My question is, what is the correct syntax to update the data instantly from checkbox selection.
I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.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: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.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: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}
I am using jquery, php and json to store and update the clicks on a single download button. It's working flawlessly but now I need to be able to store and update the clicks from multiple download buttons and display them individually.
Can you guys give me a hand with this?
What I have so far is:
jQuery:
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
$.ajax({
url: "downloads.php",
success: function(response) {
if (response = 'success') {
// The counter file has been updated in the background, but we should update the results on screen to tell the user
var count = $('.small').html();
$('.small').html(parseFloat(count) + 1);
// Then redirect so that file can download
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
}
});
return true;
});
$.ajax({
url: "get-downloads.php",
success: function(data) {
var data = JSON.stringify(data, null, 4);
var data = $.parseJSON(data);
$('.small').html(data.count);
}
});
downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'] = $json['count'] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
get-downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
header('Content-Type: application/json');
echo json_encode($json);
?>
and the downloads.json
{"count":174}
try like this
for example for 3 button
<input type='button' name='btn1' class='download'/>
<input type='button' name='btn2' class='download'/>
<input type='button' name='btn3' class='download'/>
send name of button to server and show count in different .smallbtn1،.smallbtn2،.smallbtn3
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
//get name of button
var name= $(this).prop('name');
//==================
$.ajax({
url: "downloads.php",
data:{buttonName:name},
method: "POST",
success: function(response) {
if (response = 'success') {
//get count download
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response);
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
});
//===================
}
}
});
return true;
});
in downloads.php open json file
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'.$buttonName] = $json['count'.$buttonName] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
downloadsCount.php
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
downloads.json
{"countbtn1":0,"countbtn2":0,"countbtn3":0}
this is my test and working for me
I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});
I have an ajax script, which I kinda understand, but still need some extra help.
$('.images').click(function(){
var imageId = $(this).attr('id');
alert(imageName);
$.ajax({
type: "get",
url: "imageData.php",
dataType: "json",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
alert(imageId);
$("#images_"+imageId).html(data);
}
});
//$('#images_'+imageId).toggle();
});
I have that code, it goes to this imageData.php file
<?php
if(isset($_GET)){
$images = "";
$path = 'img/';
$imageId = $_GET['getImageId'];
$sql = mysql_query("SELECT * FROM images WHERE iID = '".$imageId."'");
while($row = mysql_fetch_array($sql)){
$images .= $path.$row['images'];
}
$json = json_encode($images);
?>
<img src='<?php echo $json;?>'/>
<?php
}
?>
Why does it output error when I try to echo a string from $images, but it outputs correctly when I do echo $imageId;? I'm trying to output something from mysql, but not trying to output just the id.
Need help please, thank you
You don't need use json_encode here, there is not data that needs to be in JSON format. There is also no reason to loop over the result set, if the query only returns one image.
Try this:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
$path = 'img/' . $row['images'];
}
}
?>
<?php if($path): ?>
<img src='<?php echo $path;?>'/>
<?php endif; ?>
If the iID is actually an integer, you need to omit the single quotes in the query.
You also have to change the dataType from json to html, as you are returning an image tag (HTML) and not JSON:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "html",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html(data);
}
});
Another option is to return only text (the link) and create the images on the client side:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
echo 'img/' . $row['images'];
}
}
?>
And in JavaScript:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "text",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html('<img src="' + data + '" />');
}
});
As you may get many images because you use while loop you probably want to do this like so:
in php:
$x = 0;
$another = array();
while($row = mysql_fetch_array($sql)){
$another[$x] = $path.$row['images'];
$x++;
}
echo json_encode($another);
and in jquery (in your success callback):
$.each(data, function(i, v){
// Do the image inserting to the DOM here v is the path to image
$('#somelement').append('<img src="'+v+'"');
});
For outputing an image you must set src attribute of the image tag, if you already have one, or you can create it on the fly. See here how to do that > jQuery document.createElement equivalent?