Follow button with AJAX - php

I have created a button with which you can follow/unfollow a user, with AJAx and PHP.
If you click on the button, you follow, else, you unfollow.
There's a function that checks if the user you try to follow is already followed...
HTML
<div class="heart"><i class="fa fa-heart awesome"></i></div>
PHP
public static function Follow($user, $seguidor){
$sql = "INSERT INTO seguidores (id_canal, id_seguidor) VALUES ('$user', '$seguidor')";
$resultado = self::Conexion($sql);
return $resultado;
}
public static function CheckFollow($user, $seguidor){
$heart = "";
$sql = "SELECT * FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
$resultado = self::Conexion($sql);
$verificacion = false;
if(isset($resultado)) {
$fila = $resultado->fetch();
if($fila !== false){
$verificacion = true;
}
}
if($verificacion == false){
$heart = "<div data-id='".$user."' class='heart'><i class='fa fa-heart awesome'></i></div>";
} else {
$heart = "<div data-id='".$user."' class='heart like'><i class='fa fa-heart awesome'></i></div>";
}
return $heart;
}
public static function Unfollow($user, $seguidor){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
$resultado = self::Conexion($sql);
return $resultado;
}
AJAX
$(document).ready(function () {
$function() {
var element = $(this);
var data_id = element.attr("data-id");
$.ajax({
type: "POST",
url: "database.php",
data: data_id,
success: function(){ }
});
return false;
}
});
The problem is, how can I load those php funcionts everytime I click the button...
Click > follow
Another click > unfollow

Here's a few suggestions:
I notice you are creating HTML strings in PHP. If at all possible, you want to avoid doing that.
Keep all your HTML, CSS and JavaScript client-side. As you progress as a developer, you will start to see why. Think of them as templates.
In this case, you just need to return either "followed" or 'unfollowed" to the client callback. Could boil it down to a boolean!
So, in your template, define both the followed state and the unfollowed state. Use CSS to hide the appropriate one. This can be incredibly lightweight!
In these examples, you just set the follow attribute on your button.
So your javascript would look like:
// I would do something like:
find=document;
id="getElementById";
/* ... */
success: function (request, status)
{
if (!status)
return
;
find[id]("follow-1").setAttribute("follow", request.responseText)
}
(check the ajax api of the lib)
1.)
<button id="follow-1" follow="true">
<img src="transparent.png" />
</button>
+
button[follow="false"] > img
{ background: transparent url("unfollow.png");
}
button[follow="true"] > img
{ background: transparent url("follow.png");
}
2.)
<button id="follow-1" follow="true">
<img src="follow.png" />
<img src="unfollow.png" />
</button>
+
button[follow] > img
{ display: none;
}
button[follow="false"] > img:last-child
{ display: block;
}
button[follow="true"] > img:first-child
{ display: block;
}

I would suggest using framework such as CodeIgniter to handle the back-end as you can post data directly to public controller methods directly from ajax, but for rough idea on how it could work (you may need to fix up bugs / tweak as I wrote from memory):
Add to PHP to handle incoming requests:
//Minimal vulnerability protection while getting inputs.
$update_types = array("Follow", "CheckFollow", "Unfollow");
$update_method = in_array($_POST["update_type"],
$update_types)? $_POST["update_type"], "");
if ($update_method) {
//Call the update function & bounce the response
//in JSON back to the AJAX handler.
echo json_encode(call_user_func($update_method,
(int) $_POST["user_id"], (int) $_POST["seguidor"]));
}
Javascript:
$(document).ready(function () {
//Button click handler.
$("div.heart").on("click", function() {
var my_button = $(this);
var update_type = "";
if (my_button.hasClass('.like'))
update_type = "Unfollow";
else
update_type = "Follow";
$.ajax({
type: "POST",
url: "database.php",
data: {
"update_type": update_type,
user_id: my_button.attr("data-id"),
seguidor: "some value here - not sure based on code"
},
success: function(response) {
//response from server - check for errors...
//Update the UI - add heart if follow updated, remove it if not.
//You will need to modify your php functions to return result code and then either add "like" class or remove it - obviously this is not a complete rewrite of your app.
if ("/* result is followed */")
my_button.addClass("like");
else
my_button.removeClass("like");
}
});
});
});

Related

InlineButton should change value (date) in database

Im trying to implement an Inline button inside a table, that immediately changes / writes the Date of today in the database.
The click on the Button "change" should write the actual Date in the Database.
I already found a way to create an inline button to change a boolean value inside the Database. To activate / deactivate a Product for example.
Now I nearly need the same only with the fact, that when I press the Button it should write todays date inside the Database.
Creating the Button
function doCustomRenderColumn($fieldName, $fieldData, $rowData, &$customText, &$handled)
{
if ($fieldName == 'active') {
$dataAttributes = sprintf('data-id="%s" data-active="%s"', $rowData['id'], $fieldData);
$customText = '<span class="product-info" style="display: none;" ' . $dataAttributes. '></span>' . $customText;
$customText .= '<button class="btn btn-default inline-button" style="margin-left: 25px;">Change</button>';
$handled = true;
}
}
Handling parameters and executing the query
function DoPrepare() {
if (GetApplication()->IsGETValueSet('id') && GetApplication()->IsGETValueSet('active')) {
$id = GetApplication()->GetGETValue('id');
$active = GetApplication()->GetGETValue('active');
$sql = "UPDATE product SET active=$active WHERE id=$id";
$this->GetConnection()->ExecSQL($sql);
echo json_encode(array("active" => $active));
exit;
}
Handling the button click and calling AJAX
// OnAfterPageLoad event body
function prepareInlineButtons() {
$('button.inline-button').click(function() {
var self = $(this);
var checkboxControl = self.siblings('.pg-row-checkbox');
var productId = self.siblings('.product-info').data('id');
var activity = self.siblings('.product-info').data('active');
$.getJSON(location.href, {id: productId, active: activity == 1 ? 0 : 1}, function (data) {
self.siblings('.product-info').data('active', data.active);
if (data.active == 1) {
checkboxControl.addClass('checked')
}
else {
checkboxControl.removeClass('checked')
}
})
})
}
prepareInlineButtons();
You use click(function(), but this don't gonna work.
This just work for objects already on screen at loading time.
Try use .on() jquery function, like $('button.inline-button').on('click', function()

PHP & MySql and Ajax auto-suggest issue

I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>

Passing HTML Attributes through to JQuery Post

I'm trying create a "Like" option on my websites topics and I want to pass data through an a tag to php using JQuery post but it isn't working properly. Here is the code that I have:
<a class="likelink" href="#" poster="$yourid" like="$postid" user="$postusername">Like</a>
$('.likelink').on('click', function()
{
var poster = $(this).attr("poster");
var lat = $(this).attr("lat");
var lon = $(this).attr("lon");
var like = $(this).attr("like");
var user = $(this).attr("user");
{
jQuery.post("php/like.php", {
poster:poster,
like:like,
user:user
}, function(data, textStatus){
if(data == 1){
$('.likethis').html("Success");
}else{
$('.likethis').html("Error");
}
});
}
return false;
});
Can anyone see if there are any possible errors here or if there is a better solution. Thanks

php mysql not saving data when button clicked and run $.ajax function

I have this
"fsField" is the class of all elements in the form. So whenever the user blurs to another field it submits the form using the function autosave() - given below. It saves data when the user blurs but when the user clicks the button with class "save_secL" to go to next page it does not save.
$('.fsField').bind('blur', function()
{
autosave();
}
});
but when i use this code
$('.save_secL').click(function()
{
var buttonid = this.id;
{
var answer = confirm("You have left some questions unanswered. Click OK if you are sure to leave this section? \\n Click CANCEL if you want stay in this section. ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="unanswered" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="answered all" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
});
**autosave_secL.php is the php source thats saving the data in the database. I ran it independently and it does save data okay. **
function autosave()
{
var secL_partA_ques_1_select = $('[name="secL_partA_ques_1_select"]').val();
var secL_partA_ques_1 = $('[name="secL_partA_ques_1"]:checked').val();
var secL_partA_ques_2_select = $('[name="secL_partA_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partA_ques_1_select=" + secL_partA_ques_1_select + "&secL_partA_ques_1=" + secL_partA_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
}
});
}
**
valid() is a validation function that checks if any field is empty and returns a value if there is an empty field.**
function valid()
{
var items = '';
$('.fsField').each(function()
{
var thisname = $(this).attr('name')
if($(this).is('select'))
{
if($(this).val()=='')
{
var thisid = $(this).attr('id')
items += "#\"+thisid+\",";
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '#B5EAAA');
}
}
else
{
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '');
}
});
return items;
}
Can anyone please help? i am stuck for a day now. Can't understand why it saves when the user goes field to field but does not save when button is clicked with validation.
Tested with Firefox. this line appears in red with a Cross sign beside when the button(save_secL class) is clicked. I am using a ssl connection.
POST https://example.com/files/autosave_secL.php x
Here is the modified code trying to implement the solution
$('#submit_survey_secL').click(function()
{
if(valid() !='')
{
var answer = confirm("You have left some questions unanswered. Are you sure you want to Submit and go to Section B? ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=4"
});
}
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=6"
});
}
});
function autosave(callback)
{
var secL_partL_ques_1_select = $('[name="secL_partL_ques_1_select"]').val();
var secL_partL_ques_1 = $('[name="secL_partL_ques_1"]:checked').val();
var secL_partL_ques_2_select = $('[name="secL_partL_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partL_ques_1_select=" + secL_partL_ques_1_select + "&secL_partL_ques_1=" + secL_partL_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
{
callback();
}
}
});
}
I don't understand why this doesn't work as callback should totally work. Firebug does not show POST https://example.com/files/autosave_secL.php in red any more but it shows that it has posted but I think the callback is not triggering for some reason
$('.save_secL').click(function() {
//...
//start autosave. Note: Async, returns immediately
autosave();
//and now, before the POST request has been completed, we change location...
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
//....and the POST request gets aborted :(
Solution:
function autosave(callback)
{
//...
$.ajax(
{
//...
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
callback();
}
});
}
//and
autosave(function(){
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
});
By the way, your autosave function is pretty hard for your server. Did you consider using localStorage + a final POST request containing all data?
I got the solution.
It might be one of the several. scr4ve's solution definitely helped. So here are the points for which I think its working now.
Moved "cache: false, " and removed "async:false" before url: in the ajax autosave function. Before I was putting it after "data: "
Added a random variable after autosave_secL.php/?"+Match.random()
Added scr4ve's solution so that POST is completed before redirect

jQuery get() php button submit

I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});

Categories