Sorry if this is a duplicate, but I've been searching for a while, only found a solution to change text or class, so I don't know if this is possible, I just need someone to point me in the right direction on what to do or how to do it.
I have two buttons, one with follow attributes that I send to Ajax to execute a function and another unfollow which does similar but executes the opposite function. I included a code which I used to identify a user to follow or unfollow, it changes between the two buttons but only when I refresh the page, I was wondering if there was a way to have the new attributes of the unfollow button when I have successfully followed a user or unfollowed without the page refresh.
Here's my code of both delegations on ajax
To follow a user
$("body").delegate("#user_click_id","click",function(event){
var user_user_id = $(this).attr("user_user_id");
event.preventDefault();
$(".overlay").show();
$.ajax ({
url: "action.php",
method : "POST",
data:{Userfollow:1,user_user_id:1,user_off_id:user_user_id},
success: function(data){
$("#follow_msg").html(data);
$(".overlay").hide();
count_user_following();
} }) })
To unfollow a user
$("body").delegate("#remove_user_click_id","click",function(event){
var user_unfollow_id = $(this).attr("user_unfollow_id");
event.preventDefault();
var data =$(this).serialize();
swal({
title: "Are you sure?",
text:"You are about to unfollow this user!",
type:"warning",
confirmButtonText:"Yes, Unfollow",
cancelButtonText:"Cancel",
closeOnConfirm:false,
closeOnCancel:false,
showCancelButton:true
},
function (isConfirm) {
if(isConfirm){
$(".overlay").show();
$.ajax ({
url: "action.php",
method : "POST",
data:{UnfollowUser:1,user_remove_id:1,user_off_id:user_unfollow_id},
success: function(data){
swal("Unfollowed","You successfully unfollowed this user","success");
$(".overlay").hide();
count_user_following();
},error:function(data){
swal("Unsuccessful","something went wrong, please try again","error");
$.('.overlay').hide();
count_user_following();
}
});
}else{
swal("You Cancelled","You are still following this user","error");
count_user_following();
}
});
})
So both buttons having attributes highlighted in both functions are given below
Follow attribute on button
<a user_user_id=<?=$user_user_id?> id="user_click_id" class="follow">Follow</a>
Unfollow attributes on button
<a user_unfollow_id=<?=$user_user_id?> id="remove_user_click_id" class="unfollow">Unfollow</a>
So my problem is getting them to switch between the follow and unfollow only after success while maintaining the highlighted attributes, I can change the class and text, but the "user_unfollow_id" to "user_user_id" is what I'm having a problem changing. Maybe I'm just missing something.. Please any step in the right direction will be appreciated.
Just a warning, all of the code below is untested...
Your two jQuery functions are almost identical. To keep things DRY, why not combine everything into one?
Instead of using two different buttons, use one button that acts as a toggle. On or off.
<a data-state="not-followed" user_user_id=<?=$user_user_id?> id="user_click_id" class="follow">Follow</a>
When the user clicks the follow link, a few things can then happen:
In your js, check the value of data-state. If it is "not-followed" then we process a follow request. If it is "followed" then we do an unfollow request. We can modify the values in the link after each press:
$("body").delegate("#user_click_id","click",function(event){
event.preventDefault();
var user_user_id = $(this).attr("user_user_id");
var state = $(this).data('state'); // get the state from the data attribute
$(".overlay").show();
$.ajax ({
url: "action.php",
method : "POST",
data:{
state: state,
userFollow:1,
user_insert_id: 1, // not sure what this is for
user_new_id: <?=$user_user_id>
},
success: function(data){
$("#follow_msg").html(data);
$(".overlay").hide();
count_user_following();
// now update the link
$(this).text(state == 'followed' ? 'unfollow' : 'follow');
// and update the data-state attribute
$(this).data('state',state == 'followed' ? 'not-followed' : 'followed')
}
})
})
So you send both follow and unfollow requests to the same place. Then when the request hits the server, just check to see if state is "follow" or "unfollow" and do the appropriate thing with the other variables that have been sent.
Related
I have different links on my website which lead to other websites. I want to count the amount of clicks on the different links with my MySQL database.
I thought about doing a redirection over a php file which adds it in the database, but I would prefer to not redirect the user. Is it possible that the user just clicks on the tag gets immediately to the external website, and I can still count the click?
Thanks for you answers,
Till
yes you can run an ajax request and when the request is completed then you can redirect user to where ever you want to.
in the ajax request you will count the clicks and save it to the database.
you can do something like
$("a").click(function(){
$.ajax({url: "scriptthatwillcountclick.php", success: function(result){
window.open('redirect_here');
}});
});
Use ajax.
var data = {link:"value"};
$.ajax({
url : "your_file.php",
type: "POST",
data : data,
success: function(data, textStatus, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
You can run this code inside .click function when the link is pressed.
And in your php file just increment the count.
You can use jQuery Ajax funcionality to accomplish your goal, just create an on click even for your "a" element and execute your Ajax to save the click information on your database.
$('a').on('click', function(){
$.ajax({
method: "POST",
url: "save-my-click.php",
data: { 'extrainfo' : "Some extra info" }
});
});
Do not return false, or event.preventDefault() on your click event, because it will brake the redirection.
UPDATE:
You don't need to set the success and error functions because it is going to redirect anyway and you are not going to handle them.
I've got a PHP form set up and it works fine on it's own but now that I've hooked it up with AJAX I'm getting duplicate submissions when someone submits the form so even though they've only submitted the form once it's added the details to the database multiple times.
From my testing it seems as though its sending the data twice but looking at the submissions from other people it's possible that it's doing it more than twice under certain circumstances but I haven't been able to replicate that.
Here is the code I was using initially:
$("#email-gather").submit(function(e) {
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
e.preventDefault();
});
I have had a look around to find a solution and I saw a few people with similar issues saying that .live should be used instead of .submit so I amended my code this this:
$( "#email-gather" ).live( "submit", function() {
event.preventDefault();
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
});
However this also resulted with the same issue so I'm hoping you might have a solution to this issue. I appreciate any help you can provide on the matter.
In the second part of code (that should work), you have event.preventDefault but event is not defined. try to add function(event) and it must work.
Else in the first one, you can put the prevent default before ajax call and take away the second submit. You need to add a return true in the ajax function to tell you script that the submit was successfull.
I have this presumably 'simple' task that is absolutely kicking my butt.
My aim is that when a user clicks a link, I prevent the default, run an ajax function on it, then follow that link (ie. resume default). The only thing I can get to work is capturing the href of the link and then following using window.location - this is not ideal, as it doesn't detect whether a user has opted to open in a new window/tab or in the same window/tab; also I think there must be a better way.
However what is happening is that the default is prevented, AJAX function is run but the link is not then followed. What I'm asking is: how to simulated the link click after the function has run?
HTML
This is the link
jQuery
$(document).on('click', 'a', function(e, options){
// setup our options
options = options || {};
// get some details from the link
var this_href = $(this).attr('href');
var this_id = $(this).data('id');
// if options aren't set and this link has a data-id attribute
if(!options.stuff_done && $(this_id).length){
e.preventDefault(); // prevent link following
// run some ajax
$.ajax({
url: myAjax.ajax_url,
type: 'post',
data: {
action : 'a_php_function',
post_id : this_id
},
success: function(response) {
// do stuff
}).then(function(){
$(this).trigger('click', { stuff_done: true });
});
} else {
// else if it doesn't have a data-id, do default
}
});
Context: Checking if a value ('data-id') is in an array using PHP/AJAX and if it is, removing it. This data-id relates to a post's ID in Wordpress, and needs to be removed when a user follows a link to that post.
Hence - user clicks link, data-id is checked, removed/not-removed from array, link is followed.
First give your href an ID like so:
<a href="some_href" data-id="789" id='#some-link'>This is the link</a>
Then simulate a click of it in your ajax success part:
...
success: function(response) {
$('#some-link').click();
})
...
You can examine the response before triggering the click. Also, I don't think you need the .then and all that.
I've created a dynamic table in PHP, where every image in a row has a specific url in the ID.
For example:
When a user clicks on this image, it executes an action. This works fine.
Afterwards, in the second ajax, it's supposed to reload the colorbox with the previous url. This also works, however, the javascript seems to be loaded again (with the new values though)?
$('#cboxLoadedContent img[alt="markmessage"]').live('click', function(){
var returnurl = "<?php echo $_SESSION['returnpage']; ?>";
var markurl = $(this).attr('id');
alert(markurl);
// Do the action
$.ajax({
method:'GET',
url: markurl,
cache:false
});
// Reload colorbox again with previous contenturl.
$.ajax({
type: 'GET',
url: returnurl,
dataType: 'html',
cache: true,
beforeSend: function() {
$('#cboxLoadedContent').empty();
$('#cboxLoadingGraphic').show();
},
complete: function() {
$('#cboxLoadingGraphic').hide();
},
success: function(data) {
$('#cboxLoadedContent').empty();
$('#cboxLoadedContent').append(data);
}
});
});
</script>
Is there any way to PREVENT the javascript from being re-appended to the colorbox? I've tried a few methods (like removing it with DOM), but nothing seems to work...
The javascript may NOT be disabled, it's supposed to process a new url afterwards...
Try to replace live to one in first line:
$('#cboxLoadedContent img[alt="markmessage"]').one('click', function(){
Try the simple click event binding. Here you only bind it to the selected elements, not to new appended elements. If you want the event to be fired only once, use one.
I'm not sure which version of jQuery you are using, but live() is deprecated as of 1.7, you might want to try using on().
I have a web application which features a bunch of different items, which are generated from a MySQL table. As users scroll through it, I want them to be able to click a link next to the item which will insert the request into a MySQL database. Normally, I’d do this by creating a PHP page (which I will do anyways) that grabs the item name & user id from the URI using the $_GET method & inserts it into the table. However, in this case, I don’t want the users to be redirected away from wherever they are. I just want the link to send off the request, and maybe display a small message after it is successful.
I figured jQuery/AJAX would be best for this, but as I’m not too familiar with it, I’m not sure what to do. Any tips are appreciated!
You have to do something like
$('.classofyourlink').click(function(e){
e.preventDefault();//in this way you have no redirect
$.post(...);//Make the ajax call
});
in this way the user makes an ajax call by clicking a link without redirecting. Here are the docs for $.post
EDIT - to pass the value to jQuery in your case you should do something like
$('.order_this').click(function(e){
e.preventDefault();//in this way you have no redirect
var valueToPass = $(this).text();
var url = "url/to/post/";
$.post(url, { data: valueToPass }, function(data){...} );//Make the ajax call
});
HTML
<a id="aDelete" href="mypage.php">Delete</a>
Script
$(function(){
$("#aDelete").click(function(){
$.post("ajaxserverpage.php?data1=your_data_to_pass&data2=second_value",function(data){
//do something with the response which is available in the "data" variable
});
});
return false;
});
See http://api.jquery.com/jQuery.ajax/
$('#my-link').click(function(){
$.ajax({
url: "mypage.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
return false;
});
$('.classOfYourLinkToBecliked').click(function(){
$.ajax({
type:'GET',
'url':'yoururl',
data: {yourdata},
processData: false,
contentType: false,
cache: false,
dataType: 'json',
success: function(response){
alert(response);
}
});
});