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.
Related
If ajax call ok than a href not working or if i stop ajax call than href ok, But i want both work on click
View
Ajax Request
$("body").on("click", ".btnad", function(e){
e.preventDefault();
details_id = $(this).attr('id');
$.ajax({
url: 'assets/php/process.php',
type: 'post',
data: { details_id: details_id },
success:function(response){
data = JSON.parse(response);
$("#getID").text(data.id);
$("#getTitle").text(data.ad_title);
$("#getUser_coin").text(data.user_coin);
}
});
});
If I understand correctly, you want to initiate an AJAX request and follow the link. You can't reliably do both an an asynchronous thing (ie an AJAX request) and still allow the browser to follow a link to a new page.
Instead, you should drop your use of AJAX, and instead allow your browser to perform a normal request to assets/php/process.php, but hae that page redirect the browser to the page you want to show next.
I'm not a jQuery expert, but tried to create a (simple) function where users can simple click on a button to upvote an item. After a lot of failures, I managed to create the following:
jQuery
function vote(_obj) {
$.ajax({
type: "POST",
data: "id=" + $(_obj).attr("id"),
url: "vote.php"
});
}
$('.favorite').click(function() {
vote(this);
});
So every time a user click, the page refresh (and automatically jumps to the top of the page). I tried already do add a e.preventDefault(); but without any results.
HTML/CSS
<i class="fas fa-heart" style="color:#dc3545"></i>
Kind regards!
Just prevent the default action of the click. This would prevent a form submitting or a link from following it's href url or whatever the default of that element is when that event occurs
$('.favorite').click(function(event) {
event.preventDefault();
vote(this);
});
In additional to e.preventDefault() you can use return false; from a jquery event handler.
$('.favorite').click(function() {
vote(this);
return false;
});
Alternatively, semantically this should really be a <button> not an <a>, make it type='button' and it won't do anything other than your code (the default is type=submit so needs the type= specified otherwise will attempt to submit your form). You may need to add some css to stop it looking like a "button".
<button type='button' class="favorite">
<i class="fas fa-heart" style="color:#dc3545"></i>
</button>
with your same existing code
Prevent reloading
You can use preventDefault() function like this to prevent your browser from reloading :
In your Javascript :
$('.favorite').click(function(e) {
e.preventDefault();
vote(this);
});
Your a tag doesn't have href value so it looks like reloading page (but it's browsing to the same page).
Update vote value
To update your vote value, you can use success() function of jQuery's Ajax call, and update value as you want (ex: only increase or getting value from the call's response), using selector to update the right value.
$.ajax({
type: "POST",
data: "id=" + $(_obj).attr("id"),
url: "vote.php",
success : function(response){
// update your value here, using selector
// ex: $('.vote-' + $(_obj).attr('id')).val(response.vote)
},
error: function(response) {
// handle error
}
});
I have a search result displayed - in this there is an anchor tag like below.
<div class="addfriend">
Add as friend
</div>
I was doing this because, I want to keep my search result. I dont want to do POST-REDIRECT-GET method. I was using AJAX to update friends nesting DB table. If I prevent default action on anchor tag, the link is being opened in the same page and redirected to add_friend.php?from=kpkdhar22&id=2 , DB is updated and when back is pressed search result page is giving error message and search is gone. I want to keep target="_blank" because in case JS is not enabled in browser, it will do in php.
Can I execute the JS function other than anchor tag and still have a new tab.
My AJAX code is like this :
function addfriend(fid, uid) {
// uid -- person sending friends request
// fid -- person receiving friends request
var id = '#' + uid;
$("id").parent().empty().addClass("friend").removeClass("addfriend").html("<span>Request sent</span>");
var userid = uid;
var friendid = fid;
var status = 'N';
var dataString = 'userid=' + uid + '&friendid=' + fid + '&status=' + status;
$.ajax({
type : "POST",
url : "js/add_friend.php",
data : dataString,
cache : true,
success: function (html) {
var id = '#' + uid; // is this ok as selector
$("id").parent().empty().addClass("friend").removeClass("addfriend").html("<span>Request sent</span>");
},
error : function () {
$("#errors").html('');
$("#errors").html('Failed to send your request.');
}
});
}
When the function addfriend(1,2) is executed, a new tab is opened and in add_friend.php a JS alert message is displayed and I am closing that tab immediately. But AJAX success function is not executed, so I added the same before AJAX call, but that is also not worked.
console message -- XHR finished loading: POST "http://localhost/bp1/js/add_friend1.php".
Please suggest me some process, or steps where am I going wrong.
Regards,
Poorna.
You have to make your link stop acting as such. Your AJAX call inside the addfriend() function complicates this a little, but not too much. First of all, change the "onclick" attribute of your link to
onclick="return addfriend(1, 2)"
i.e. add the return statement, and add this to the very end of your addfriend() JS function (after your AJAX call):
return false;
This will trick DOM into thinking that you did click on your link, but for some reason it didn't go well, and the browser should not follow the "href" URL.
I have a question. I'm using a Fancybox instance to show categories of tags. In this fancybox, users can edit the categories, delete them or create new ones.
The script that is executed in the fancybox is called with AJAX. That means that a PHP-file (called categories.php) is being executed while the browser doesn't redirect (it stays on tags.php). And here's where the problem kicks in:
I have a form on categories.php. If the user presses submit, then jQuery cancels the default event and send an AJAX request. This AJAX request should be send to this code (e.g. the code in categories.php).
How can I do that?
$(document).ready(function() {
$('form').on('submit', function(event) {
// cancel the default event (i.e. POST the form)
event.preventDefault();
var postData = $(this).serialize();
var postUrl = this.href;
var createCategory = $.ajax({
url: postUrl,
type: 'POST',
data: postData
});
createCategory.done(function(result) {
// code to reload the page
// .replaceWith()?
$('.testdiv').append(result);
console.log('done');
})
});
});
Should the postUrl be $(this).href ? or Should I change that to point to the categories.php?
I think you should try to point at categories.php.
I am attempting the following:
When a user clicks a link, I want to update a specific column of a specific table in the database via ajax. BUT I still want the user to be redirected to the href="<url>" of the link.
I tried jQuery without return false; but then the ajax doesn't work.
I tried with return false; but then the page obviously doesn't redirect to the url as I wanted.
Thanks in advance for your help.
Do your AJAX call, then set document.location when done.
$('a').click(function(e){
var href = this.href; // get href from link
e.preventDefault(); // don't follow the link
$.ajax({
url: '/path/to/site',
data: {some: data},
success: function(){
document.location = href; // redirect browser to link
}
});
});
You need to serialize these actions yourself. In the event handler first run your AJAX request, then lookup the href from the tag and use a location redirect to take the client to that URL.
Put the redirect code in the success callback:
$.ajax({
...
success: function(){
$(location).attr('href',url); // You URL inserted
}
});