Store clicks on each button separately in json - php

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

Related

Data missing when sent via AJAX

I want to send two values to my PHP script that is being called from an AJAX request. Somehow my data is not being passed to the PHP script.
Maybe I am doing something wrong somewhere. Can I have some insight?
$(function() {
$(".delbutton").click(function() {
var viewed_comments = $("#viewed_comments").val();
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var comments = 'comm=' + viewed_comments;
var tr = $(this).closest('tr');
if (confirm("Are you sure to mark this as viewed?")) {
$.ajax({
type : "POST",
url : "update_entry.php",
dataType: "json",
data: {info:info, comments:comments },
success : function(response) {
if(response=="updation success"){
console.log('inside');
}
}
});
}
return false;
});
});
And my PHP where the AJAX request is going,
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
$level_code = $_SESSION['level_code'];
$action = 'view';
$viewed_date = date("Y-m-d");
$viewed_by = $_SESSION['session_admin_id'] ;
if($action == 'view')
{
$viewed_date = date('Y-m-d h:i:s');
$nots = $db->idToField("tbl_table","notes",$id);
if ($nots == "")
{
$date_string = "last viewed on|".$viewed_date."|" ;
}
else {
$date_string = $nots."last viewed on|".$viewed_date."|" ;
}
$fnc->update_is_viewed_for("tbl_table",$id, "$viewed_date", $viewed_by);
$notes_data = array("notes"=>$date_string,"viewed_comments"=>$viewed_comments);
$db->query_update("tbl_table", $notes_data, "id=$id");
}
if($db->query_update("tbl_table", $notes_data, "id=$id")){
http_response_code();
echo json_encode('updation success');
}else{
http_response_code(204);
}
Isn't it a name thing? You send two POST variables:
data: {
info: info,
comments: comments
},
but you retrieve them with different names:
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
What do you get if you var_dump($_POST);?
Use seriliaze form values it will solve your data missing problem, change #frm to your form id
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"update_entry.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if (data == 'updation success') {
console.log('success');
}
}
});
});
});

Re Construction of php for reading and sending json response

I've got a new project, it was left uncompleted by the previous developer. I'm trying to rebuild the action.php
$.ajax({
type: "POST",
url: "action.php",
data: {action:'upload',
image:data, //data is data:image/png;base64 uri
count:uploadNum,
uniqid:uniqid}
}).done(function(o) {
var data = $.parseJSON(o);
if (!data || data === null) {
toggleError(true);
}else{
if(data.status==true){
uploadLoopCount++;
if(uploadLoopCount < upload_arr.length){
uploadImage();
}else{
readySave = true;
toggleShareButtons('ready');
var loc = location.href
loc = loc.substring(0, loc.lastIndexOf("/") + 1);
loc += '?id='+uniqid;
$('#shareLink').val(loc);
}
}else{
toggleError(true);
}
}
});
and
$.ajax({
type: "POST",
url: "action.php",
data: {action:'save',
profiledata1:JSON.stringify(userdata_arr[0]),
profiledata2:JSON.stringify(userdata_arr[1]),
profiledata3:JSON.stringify(userdata_arr[2]),
profiledata4:JSON.stringify(userdata_arr[3]),
profiledata5:JSON.stringify(userdata_arr[4])}
}).done(function(o) {
var data = $.parseJSON(o);
if (!data || data === null) {
toggleError(true);
}else{
if(data.status==true){
uniqid = data.uniqid;
checkImageUpload();
}else{
toggleError(true);
}
}
});
I've tried creating the action.php, the upload function will upload the image into some directory and there would be some data base links. and the load section would return contents from database. I'm confused with the json part of php.
this is the raw action.php
<?php
if ($_POST['action']=='load') {
$uid=$_POST['uniqid'];
// fetch contents from db with $uid;
header("content-type:application/json");
$data[] = array('status' =>'true','profile1_data' =>'green','profile2_data' =>'blue','profile3_data' =>'orange','profile4_data' =>'green','profile5_data' =>'red' ,'upload' =>'http://localhost/img/', 'format' =>'jpeg' );
$j = json_encode($data);
echo $j;
}
if ($_POST['action']=='upload') {
header("content-type:application/json");
//confused with reading json response
// upload the contents
$data[]= array('status' =>'true' );
$j=json_encode($data);
echo $j;
} ?>
I'm confused with reading the json response and the response as json. Help me to rebuild the action.php. Thanks in advance

Simple php ajax chat

i'm trying to do a simple php chat application that receives data from the client via ajax and writes that data to a text file for storage. But i keep getting anundefined index error on the lines where i try to get the 'name' and the 'message' after parsing the json.
this is the chat.php file:
<?php
if (isset($_POST['data']))
{
$data = $_POST['data'];
$chat = json_decode($data);
$name = $chat->name;
$msg = $chat->msg;
$file = "chat.txt";
$fh = fopen($file, 'w') or die("Sorry, could not open the file.");
if (fwrite($fh, $name + ":" + $msg))
{
$response = json_encode(array('exists' => true));
} else {
$response = json_encode(array('exists' => false));
}
fclose($fh);
echo "<script type='text/javascript'>alert ('" + $name + $msg + "')</script>"
}
?>
this is the javascript:
<script type="text/javascript">
$(document).ready(function() {
$("#btnPost").click(function() {
var msg = $("#chat-input").val();
if (msg.length == 0)
{
alert ("Enter a message first!");
return;
}
var name = $("#name-input").val();
var chat = $(".chat-box").html();
$(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");
var data = {
Name : name,
Message : msg
};
$.ajax({
type: "POST",
url: "chat.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
// display chat data stored in text file
}
});
});
});
</script>
Probably your $chat variable
$chat = json_decode($data);
Does not contains these fields but Name and Message as you delcared here:
var data = {
Name : name,
Message : msg
}
name and msg are valuse and Field names are Name and Message.
Please try to print_r($chat) to see what it contains.

How get AJAX to Post JSON data into div

I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});

jQuery.ajax File Delete

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;
});
});

Categories