wordpress function is not being executed - javascript

I have this button
<button class="button1" id="myid1">Activate</button>
when user click this button then this jquery executes and we are getting alert also.
jQuery(document).ready(function($) {
$(\'#myid1\').click(function(e){
e.preventDefault();
var $el = $(this).parents().eq(1);
remove_element($el);
var data1 = {
action: \'enable_function1\',
};
$.post(ajaxurl, data1, function(response) {
alert(\'Congratulations,Activated' \');
}); });
});
here is my WordPress function
function enable_function1() {
add_filter('mod_rewrite_rules', 'someotherfunction');
}
but nothing is being written by mod_rewrite_rules

in your wordpress backend you need to do this. The action is not the name of the function, it's used by wordpress to identify which function to execute
function your_function() {
add_filter('mod_rewrite_rules', 'someotherfunction');
}
add_action("wp_ajax_enable_function1", "your_function");
add_action("wp_ajax_nopriv_enable_function1", "your_function");
check this for more details :
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Related

How to trigger another jquery event using the return data of previously executed jquery event

I have a button, for example
<a id="btn" class="button">Submit</a>
When this button is clicked, it triggers a jquery function
for example,
$("#btn").on("click", function() {
$.ajax({
url: 'index.php',
type: 'post',
data: {product_id: 1, qty: 2},
dataType: 'json',
success: function(json) {
if (json['success']) {
console.log('Product added to cart');
}
if (json['error']) {
console.log('Product not added to cart');
}
});
});
Now, I would like to know if it is possible to trigger another jquery event by some other jquery code, once the above function is executed, and I want to use the return values of the previous function without making any changes to the above-mentioned function.
For example, I would like to run the following function immediately after the above jquery event by writing another jquery code and not changing any part of the previous code.
function anotherAction(json_array) {
if (json_array['success']){
//calling another function
}
}
You mean
function anotherAction() {
if (submitBtn() == 'Submitted'){
console.log('Button is submitted');
}
}
But then you need to make str global in scope
Perhaps like this
let str;
$("#btn").on("click", function() {
str = 'Submitted';
});
$("#check").on("click", anotherAction);
function anotherAction() {
console.log('Button has '+(str === 'Submitted' ? "" : "not ")+'been clicked');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="button">Click</button>
<button id="check" type="button">Check</button>
without making any changes to the above-mentioned function.
No. Its not possible. submitBtn function's return value is unused/no-reference/destroyed inside "#btn" click event. So you'll never know what was returned.

How to call a function in javascript?

I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};
var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update
I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.

Use geocomplete function after ajax event

I have a button that adds an input box where you can type an address. For the address, I'm using the geocomplete plugin. In all input boxes that were not generated with ajax the geocomplete works. If the input was generated by ajax, it doesnt.
This is my code to generate the input box:
$('.add-drop').on('click', function(){
$.ajax({
url : '/ajax/get-location-input',
success : function(data){
$('#additional-drop').append(data);
}
});
});
This is my geocomplete code:
$(".get-location").geocomplete({
details : "form",
types : ["geocode", "establishment"]
}).bind("geocode:result", function(event, result){
console.log(result);
});
The problem is not with the class. I was trying to do something like $(".get-location").on("geocomplete"... but it wasn't working. Any idea? Thanks
AJAX is Asynchronous (Asynchronous JavaScript and XML) That means it might execute after the main code has been finished processing
$.ajax({
url: '/ajax/get-location-input',
success:function(data){
alert(data);
}
});
alert('Hi ');
In this case, Hi will alert first, then data. In your case, the inputs might not even be generated yet and so the geolocation code won't see them
The correct code:
$.ajax({
url: '$('#additional-drop').append(data);',
success:function(data){
$('#additional-drop').append(data);
$(".get-location").geocomplete({
details: "form",
types: ["geocode", "establishment"]
});
}
});
Will make the code run after the data has been fetched from the server
This is me recommended way to do this:
(function () {
$.fn.addGeolocation = function () { this.geocomplete({ details: "form", types: ["geocode", "establishment"] }).bind("geocode:result", function(e, a){ console.log(a); }); }
$.get('/ajax/get-location-input', function (a) {
$('#additional-drop').append(data);
$(".get-location").addGeolocation();
});
/* You may or may not need this */
window.onload = function () { $(".get-location").addGeolocation(); }
}());

jQuery .on not working after ajax delete and div refresh

On a page with a tab control, each tab contains a table, each tr contains a td with a button which has a value assigned to it.
<td>
<button type="button" class="btn" name="deleteEventBtn" value="1">Delete</button>
</td>
This code below works for the first delete. After the AJAX call & the refresh of the div, no further delete buttons can be clicked. The .on is attached to the document. The same happens if I attach it to the body or anything closer to the buttons.
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
}
});
}
$(document).ready(function () {
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
}
});
});
Any ideas? Could it be related to the wildcard for starts with [name^="delete"]? There are no other elements where the name starts with 'delete'.
EDIT
When replacing
$(container).trigger('refresh');
with
location.reload();
it "works", however that refreshes the whole page, loses the users position and defeats the point of using AJAX.
As the button click is firing at first attempt, there is no issue in that code. All you have to do is, put the button click event in a method and call it after the refresh. This way, the events will be attached to the element again. See the code below,
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
BindEvents();
}
});
}
$(document).ready(function () {
BindEvents();
});
function BindEvents()
{
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
});
}
Apologies to all and thanks for your answers. The problem was due to the way the popup was being shown & hidden.
$('#delete-popup').modal('show');
and
$('#delete-popup').hide();
When I changed this line to:
$('#delete-popup').modal('hide');
it worked. Thanks to LShetty, the alert (in the right place) did help!
If you are using Bootstrap Modal
After Ajax Request before Refreshing page add
$('.modal').modal('hide');
This Line will Close your Modal and reload your page. Before that it will complete all Ajax Request things.
But for google chrome there is no issues :) hope this help someone.

Prevent multiple ajax submissions on multiple clicks

I've a WordPress blog running this jQuery code that allows users to click a bookmark link that saves the post as a bookmark. Each post shows a total bookmark counter that looks like: "Bookmarked (5)". Although this code works, it registers multiple clicks whenever someone clicks multiple times on the bookmark link and then saves the same post as multiple bookmarks. When the user tries to remove the bookmark by clicking on the bookmark link again, it registers multiple clicks again and the counter starts showing minus numbers which looks like: "Bookmarked (-5)".
I've been searching for an instruction on how to prevent this from happening so that the bookmark counter never runs minus and the user can't bookmark the same post multiple times but had no success so far.
Here is the jQuery code that I'm using:
jQuery(document).ready( function($) {
var added_message = upb_vars.added_message;
var delete_message = upb_vars.delete_message
$(document).on('click', '.upb_add_bookmark', function () {
var post_id = $(this).attr('rel');
var data = {
action: 'bookmark_post',
post_read: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.upb_bookmark_control_'+post_id).toggle();
if($('.upb-bookmarks-list').length > 0 ) {
var bookmark_data = {
action: 'insert_bookmark',
post_id: post_id
};
$.post(upb_vars.ajaxurl, bookmark_data, function(bookmark) {
$(bookmark).appendTo('.upb-bookmarks-list');
$('.no-bookmarks').fadeOut();
});
}
});
return false;
});
$(document).on('click', '.upb_del_bookmark', function () {
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
return false;
});
});
Could you please help me solve this problem?
Thanks a lot!
One way is to add a .disabled class to your link before the $.post().
// Before ajax...
if ($(this).hasClass('disabled')) {
return false;
} else {
$(this).addClass('disabled');
}
// Make sure we refer to the same element
var that = this;
// On post success...
$(that).removeClass('disabled');

Categories

Resources