I am trying to start a PHP function in Wordpress on the click of a link. I've managed to do it using a form-submit, but I want to do it on a link click.
I've pulled together an AJAX request but it doesn't seem to work - any thoughts much appreciated.
HTML Link Code
Ajax Click
Javascript Function
<script>
// Create a function to pick up the link click
$('#link_id').click(function(event){
event.preventDefault(); // prevent default behaviour of link click
var data = {
action: 'test_response_php', // This is the PHP function to call - note it must be hooked to AJAX
};
// Post to The Wordpress URL
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
alert(response);
});
});
PHP Function
function php_function() {
echo 'Hello World';
// Some interesting server side stuff
}
add_action('wp_ajax_nopriv_test_response_php', 'php_function');
add_action('wp_ajax_test_response_php', 'php_function');
Change your anchor tag like this:-
Ajax Click
You were missing id tag in anchor and you are running click event on id click.
Related
Maybe is a strange title but all I want is to do so:
I have an arduino webserver and an webserver
My arduino server can receive data via url like
192.168.1.2?light=1 - light on
192.168.1.2?light=0 - light off
It is working just fine, but the problem is when I put that link anywhere on an website (in button or just normal links) the arduino server is opening in browser, is there possible to just load it using ajax, js or jquery or just simply using html?
Assuming you have a webpage with jQuery.
HTML
<a class="access-only" href="http://192.168.1.2?light=1">Turn on the light</a>
<a class="access-only" href="http://192.168.1.2?light=0">Turn off the light</a>
JS
$(document).ready(function() {
// Attach click handler to all "access-only" links.
$('a.access-only').click(function() {
// Once the link is clicked, access its URL with a GET request.
$.get($(this).attr('href'), function(response) {
// Do nothing here, the URL has been accessed.
});
// Return false to prevent the browser's default click action.
return false;
});
});
If want to use this link from a webpage then (requires jQuery):
$.get('http://192.168.1.2?light=1', function(response) {
console.log(response);
});
You can try this.
$(".yourAtag").click(function(e){
e.preventDefault();
$.ajax({url: this.href, success: function(result){
alert('success!');
}});
});
I use Codeigniter and Bootstrap.
I have a button:
<a class="btn btn-success" id="btnid" href="http://site/controllerName/parameter">Text</a>
If I click to the button its call a controller with one parameter then the controller redirects to a site.
My question is that is there a way to call the controller with a parameter but skipping the redirection?
Try following
$(document).ready(function(){ // Add your event handlers inside ready block
$("#btnid").click(function(event) { // button event handler
event.preventDefault(); // prevent page from redirecting
$.ajax($(this).attr('href')).done(function(response) { // send call
// after call
});
});
});
For details refer to - ajax, preventDefault
Edit
As there are more than one link. You can use class selector. Currently, you have 2 classes btn and btn-success. You can use either of them, however, I will suggest you to add one more class let us say btn-api
Then update your click selector to
$(".btn-api").click(function(event)) {
event.preventDefault(); // prevent page from redirecting
$.ajax($(this).attr('href')).done(function(response) { // send call
// after call
});
});
https://api.jquery.com/event.preventdefault/ - prevents the default action
$( "a" ).click(function( event ) {
event.preventDefault();
}
You need to use event.preventDefault();
This is an exemple with just JavaScript (Not jQuery)
<script>
function stopDefAction(evt) {
evt.preventDefault();
}
document.getElementById('btnid').addEventListener(
'click', stopDefAction, false
);
</script>
You can find documentation and complete exemple here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You can call a javascript method which does a ajax call. Then there will be no redirect.
<a class="btn btn-success" id="btnid" onclick="javascript:theFunction();" href="#">Text</a>
<script type="text/javascript">
function theFunction () {
event.preventDefault();
// add your ajax call to the controller here e.g
$.ajax({
url: "http://site/controllerName/parameter"
}).done(function() {
// action when the controller call returns
});
}
</script>
By default a click on the a link to a controller will either render this controller's view or redirect to another view. To stop redirecting, you must call the controller via AJAX. To fully understand this, lets see what happens when you don't use ajax:
You click on the link which triggers the request.
The request is routed to your controller.
The controller processes the request. The ending line of the controller is something like $this->load->view('your-view');
This loads the raw HTML after any view logic has been processed and sends it back to your browser via normal HTTP. This issues a redirect (or a refresh if it was the same page).
What AJAX does, is that it takes the data received in step 4, and makes it available in a variable via javascript. To see this, we can write a code snippet:
HTML
<a onclick="getAjaxData()" class="btn btn-success" id="btnid">Text</a>
The easiest way to use ajax is via JQuery.
Javascript
function getAjaxData(e) {
// Make sure that the link default action doesnt occur.
e.preventDefault();
$.ajax({
type: 'GET', // depending on the controller method.
url: 'http://site/controllerName/parameter',
success: function(data)
{
// The variable data contains the data returned from the controller.
},
error: function()
{
alert('Something went wrong!');
}
});
Now if you leave things as they are, the vairable data will contain the raw HTML returned from the controller. Usually if you will use AJAX, it is better to either return HTML snippets which you can append directly to your current HTML DOM, or return data in JSON format, which you can then process via javascript.
I am trying to create a webpage that will dynamically fill a div using AJAX. I have been able to simply update the div content with the following AJAX code:
$(document).ready(function(){
$("#projects-list a").click(function(e){
e.preventDefault();
var url = $(this).attr('href'); //get the link you want to load data from
$.ajax({
type: 'GET',
url: url,
success: function(data) {
$('#content').fadeOut(300, function() {
$('#content').html(data).delay(200).fadeIn(300);
});
}
});
});
});
However, I also am hoping to find a way to update the page URL or change the hash. So for instance, when a user is given the link to /projects.html they will be sent to a page of links, and then when a link is clicked the content is changed using AJAX and the url will change to /projects.html#first. This way then a user navigates to /projects.html#first they will see the content for the first project rather than the original list of projects to choose from.
I would recomend to use a library to handle URL and paths
http://github.com/flatiron/director
http://balupton.github.com/history.js/demo
if you want to use standard # then you can use via js, on a function call do :
window.location.hash = valueYouWantToSet, some ID mostly,
and then you can check on page load if there is a # in there then call a particular function like :
handleHash: function () { if (!isNaN(parseInt(window.location.hash.replace('#', '')))){ this.showDetails(window.location.hash.replace('#', '')); }
The problem:
I have a series of 'accept' buttons, on click it opens a lightbox (a modal- using bootstrap), of course this is done without refreshing the page.
On the lightbox I need to show information regarding what is being accepted (therefore I need to pass a PHP variable to the lightbox). So the problem is how can I pass on a variable on click without refreshing the page? I tried using javascript, but the thing is once I set up a variable in JS I can't get that variable to PHP without refreshing the page.
The button has this code.
<button class="btn btn-acceptColor m-t-lg">Accept</button>
The other code isn't relevant for the purpose of this question. I just need the concept of how to actually do it.
Any help!?
there are many examples.
I provides some links, you can use them in your code as you suitability..
1). Ajax Tutorial
2). jQuery Ajax POST example with php
3). jQuery Ajax POST example with php
4). show data in lightbox
5). How to add jquery lightbox to content added to page via ajax?
I hope above links helpful for you
$(".btn-acceptColor").click( function (){
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$.ajax({
type: "POST",
url: "exaple.php",
data: person,
success: function(msg) {
var msg = $.parseJSON(msg);
if(msg.success=='yes')
{
return true;
// fill you light-box form get value from example.php page
}
else
{
alert('Server error');
return false;
}
}
});
});
People create their own websites using WYSIWYG creator i give them. These websites have links inside of them. Also they can explore the HTML of the website and put there their own links.
I would like now to handle every link click occurring in website created with my creator and log it to my server. I know how to pass the data from JS or jQuery to PHP server. But what i need to know is how to handle the moment when person clicks a link, postpone the redirection for some moment, and in this time get the url and title of this link and send to my PHP server.
So how to handle every link click (or location change) on website that structure i don't know and get the link and title of the link clicked?
$('a').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var title = $(this).attr('title');
// Send your data to php
if ($(this).attr('target') === '_blank') {
window.location.href = href; // redirect to href
} else {
window.open(href);
}
});
jQuery("a").click(function(){
var href = $(this).attr('href');
$.post('/', {link: href}).then(function(){ document.location = href; });
return false;
});
just a try
To intercept every link, just place this function somewhere that every page has access to (header/footer/etc.):
$('a').click(function(event) {
event.preventDefault();//To prevent following the link
//Your logic. attr('href') and attr('title')
});
You can use jQuery to do this. Use the on event and bind to the click event of a element. You can then do an event.preventDefault(); do your logic and then continue as normal by getting the href from the target.
Why you want to wait till logging is completed for the redirection. Let it be an asynchronous call so that user don't need to wait. If you want to have your server page in a different domain, to tackle the cross domain ajax issue, use jsonp datatype.
$('a').click(function() {
$.ajax({
url:"yourwebsite/loggingpage.php?data="+$(this).attr("href"),
dataType: 'jsonp' // Notice! JSONP <-- P (lowercase)
});
});
and in loggingpage.php, you can read the request data and log it to your persistent storage or wherever you want.