create twitter like follow button - javascript

I have been trying to create a twitter follow button. I followed some recommendations and the end result is not satisfactory. Last time it was working, and now I cannot put it to work besides all my efforts.
I would thought this would be more less simple and it has actually been a challenge!
Check code below (HTML, PHP, JS)
HTML
<button class="btn btn-follow cenasparvas" id="<?php echo $profile_data['user_id']; ?>" type="button" onclick="status();"> Follow
JS (to actually update the database)
<script type="text/javascript">
function status()
{
var this = $('.btn-follow');
var userid = $this.attr("id");
var datastring = 'user_id=' + userid;
if (!this.hasClass('follow')) {
$.ajax({
type: "POST",
url: "follow.php",
data: datastring,
success: function(html)
{
alert('sucess');
}
});
} else if (!this.hasClass('btn-danger')) {
$.ajax({
type: "POST",
url: "unfollow.php",
data: datastring,
success: function(html)
{
alert('sucess aassss');
}
});
}
}
JS (the script that changes the type of button that appears - with support of bootstrap)
<script type="text/javascript">
var btn = $('.btn-follow');
btn.click(h);
btn.hover(hin, hout);
function hin() {
if (btn.hasClass('follow')) {
btn.text('Unfollow');
btn.removeClass('btn-success');
btn.addClass('btn-danger');
} else {
btn.addClass('btn-follow');
}
}
function hout() {
if (btn.hasClass('follow')) {
btn.text('Following');
btn.removeClass('btn-danger');
btn.addClass('btn-success follow');
} else {
btn.removeClass('btn-danger');
}
}
function h() {
if (btn.hasClass('follow')) {
btn.removeClass('btn-success follow');
btn.text('Follow');
btn.removeClass('btn-danger');
} else {
btn.text('Following');
btn.addClass('btn-success follow');
}
}

Related

Add one or two more PHP variables to the javascript code

I am a decent PHP programer and recently I got stuck in a javascript code.
I have the code below:
$(function () {
$('.more').live("click", function () {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("div#updates").append(html);
$("#more" + ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
This code submit without problems one PHP variable to the process page loadmore.php using this input
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
<a href="#" class="more" id="<?php echo $load_id; ?>">
load more
</a>
</div>
How can put more variables in the input and the javascript code to work with them on the process page?
I want to set one or two more variables.
UPDATE:
I updated the code like this:
HTML input:
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
load more</div>
JAVASCRIPT CODE:
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: {"lastmsg="+ ID, "act="+ ACT},
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
I am not sure if the data lines was writed properly because the script looks like it's frozen now
SOLVED:
I just used a datastring like this
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
var dataString = 'lastmsg='+ ID + '&act=' + ACT;
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: dataString,
//data: {"lastmsg="+ ID, "act="+ ACT },
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
Just send data as an object:
data: {
"lastmsg": "lastmsg="+ ID,
"anotherData": "someData"
}
You'll retrieve them in your PHP script as follows:
$_POST["lastmsg"];
$_POST["anotherData"];

Running jquery function after one function is executed

I am adding some comments with AJAX and get return formatted HTML and adding it to HTML with DOM manipulation,
jQuery.ajax({
url: baseURL + "index.php/user/news/add_comment",
data: $("#comment_fm").serialize(),
type: "POST",
success: function(data) {
var objData = jQuery.parseJSON(data);
if (objData.cival == 1) //Success..
{
$("#comment").val('');
$("#comment_box").replaceWith(objData.comment);
$("#commentcounts").replaceWith(objData.commentcounts);
}
} // Success End
}); //AJAX End
With above code i can see my comments are added,
Now in same return formatted HTML, there is delete button which have JS function associated,
Below is delete JS,
function deletecomment(commentid) {
jQuery.ajax({
url: baseURL + "index.php/user/news/deletecomment",
data: {
comment_id: commentid
},
type: "POST",
success: function(data) {
var objData = jQuery.parseJSON(data);
if (objData.cival == 1) {
$("#commentcounts").replaceWith(objData.commentcounts);
$("#commentbox" + commentid).remove();
}
}
});
}
Below is my delete button which fire to function deletecomment()
<i class="fa fa-trash text-info"></i>
But my problem is that i can not delete this comment just after adding function is run,
If i refresh page, then delete function works a needed,
So question is, how to make multiple function work without reloading page?
Thanks in advance,
I would suggest you to try as below:
<a class="deleteComment" data-id="<?php echo $comment['comment_id'];?>" href="#"><i class="fa fa-trash text-info"></i></a>
Your JS would be:
$(document).on('click','.deleteComment',function(){
jQuery.ajax({
url: baseURL + "index.php/user/news/deletecomment",
data: {
comment_id: $(this).data('id');
},
type: "POST",
success: function(data) {
var objData = jQuery.parseJSON(data);
if (objData.cival == 1) {
$("#commentcounts").replaceWith(objData.commentcounts);
$("#commentbox" + commentid).remove();
}
}
});
});

Syntax error in ajax

I got this script from the web and I've manipulated it to fit my way but it tells me syntax error
$(document).ready(function(){
$Addr = localStorage.getItem('eaddress');
$email7 = $('#email7')
if ($Addr !== null) {
$('#email7').val($Addr);
}
if ($Addr != '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
}
});
Missing a bunch of bracing:
$(document).ready(function() {
var $Addr = localStorage.getItem('eaddress');
if ($Addr) {
$('#email7').val($Addr);
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if (result === "ok") {
window.location = 'page.html';
}
}
});
}
});
Not absolutely required, but I also added var to local variables, simplified and combined and if test and removed a local variable not being used.
In the future, you can paste a block of code into http://jshint.com/ and it will show you where you've gone wrong. It also makes other recommendations for robust code.
Close all semicolons and braces: add });} before very last });
Result:
$(document).ready(function () {
$Addr = localStorage.getItem('eaddress');
$email7 = $('#email7')
if ($Addr != null) {
$('#email7').val($Addr);
}
if ($Addr !== '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function (data) {
$('#log_msg').html(data);
var result = $.trim(data);
if (result === "ok") {
window.location = 'page.html';
}
}
});
}
});

Javascript open in new tab by using json

Javascript Code:
<script type="text/javascript">
function MusteriBilgileriKaydet2() {
var veri = {
AnaOzelDurumId: AnaOzelDurumId.GetValue(),
AnaİlgiliPersonelId: AnaİlgiliPersonelId.GetValue(),
};
if (veri.MusteriAdiTextBox1.trim() == "" || veri.MusteriAdiTextBox1 == undefined || veri.MusteriAdiTextBox1 == null) {
$("#showwarning222").html('<img src="/Image/warning.png" title="Müşteri Adı Giriniz!">').show();
}
else {
LoadingPanel.Show();
$.ajax({
url: "/Home/GenelMusterilerGridView2",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) { // Error
LoadingPanel.Hide();
alert("Müşteri Adı Mevcut");
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
else { // Success
$("#MusterilerGetir").html(mydata);
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
},
error: function () {
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
});
return false;
}
}
</script>
My Controller:
public ActionResult GenelMusterilerGridView2(MyModel model)
{
var stringView = RenderRazorViewToString("MerkezPartial", ModelleriGetir());
return Json(stringView, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { error6 = true, JsonRequestBehavior.AllowGet });
}
}
return null;
}
My all codes works well .
I only want to open in new tab page .
So
How can i open in new tab in browser after i post data to my controller ?
Any help will be greatly appreciated.
Thanks.
you can add to your html <a href tag a target that looks like this.
Link name or text
OR you can in your javascript code add
function OpenNewTab(url){
var something = window.open(url, '_blank');
something.focus();
}
Now this should be working fine but just because some clients prevent pop-ups then you could add this to your html tag too.
<div onClick="OpenNewTab();">your link name</div>
Hope this will work for you
Cheers!

Javascript when to show results

This is my Javascript below I want to show records on load and also show new records when added to the database
showrecords(); displays the records in the database where abouts can I put this in my code where it will work correctly.
$(document).ready(function()
{
//showrecords()
function showrecords()
{
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
}
});
}
$(".comment_button").click(function() {
var element = $(this);
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
// $("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
//Function for showing records
//showrecords();
}
});
}
return false;
});
});
Though polluting the global namespace is not recommended. Here is what I would recommend for your code. Move the showRecords() out of Document ready function and refactor the update ajax code to another function 'updateRecords()'. Have only the event bindings inside the document ready function.
You could return the entire comments as response to POST 'demo_insert.php' service and call 'showRecords()' in the update service success callback.
i've pasted below (untested) code that i think should get the job done. in order to call functions you've got to define them in an accessible area, whether in the "global" (can be called from anywhere) namespace as i've done below, or as part of an another object.
you also need to make sure your functions are defined before you try to call them, as everything works in a top down manner.
function showrecords() {
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function (html) {
$("#display").after(html);
$('content').val('');
$("#flash").hide();
}
});
}
function addComment() {
var test = $("#content").val();
var dataString = 'content=' + test;
if (test == '') {
alert("Please Enter Some Text");
}
else {
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function (html) {
//$("#display").after(html);
$('content').val('');
$("#flash").hide();
//Function for showing records
showrecords();
}
});
}
}
$(document).ready(function () {
showrecords()
$(".comment_button").click(function () {
addComment();
return false;
});
});

Categories

Resources