How to handle Ajax post requests in a Wordpress plugin? - javascript

I'm trying to figure out how Ajax and Wordpress plugins work, but it seems to be pretty badly documented. Ideally what I want is:
The plugin gets it own Ajax url to use, this is defined globally.
The plugin can handle Ajax requests
I understand that there are two actions that are used for this. One for logged in users and one for users without an account or privileges. However, I just want to create an Ajax endpoint for a form.
I'm not looking for code snippets, just need to be pointed in the write direction as to Wordpress Plugins and Ajax handling.

I implemented below own AJAX functionality in functions.php, Just try this in plugin,
functions.php :
function prefix_ajax_delete_search() {
global $wpdb;
$user_id = get_current_user_id();
$wpdb->delete('sf_save_search', array('id' => $_POST['tid']) );
wp_die();
}
add_action( 'wp_ajax_delete_search', 'prefix_ajax_delete_search' );
Script.js:
function deleteSearch( tid) {
var url = window.location.href;
jQuery.post(
ajaxurl,
{
'action': 'delete_search',
'tid': tid,
},
function(response){
location.reload();
}
);
}

Related

Auto Refresh PHP Function without reloading page Javascript / Ajax

Is it possible to use Ajax, Jquery or Javascript to call a specific PHP Function and refresh / reload it every 10 seconds for example inside a specific Div or areas?
Connection.php
function TerminalStatus ($IPAddress, $portStatus ) // Responsible for current terminal status
{
$connectStatus = fsockopen($IPAddress, $portStatus, $errno, $errstr, 10); // Build cconnection to Terminal socket 25001
if (!$connectStatus) {
echo "$errstr ($errno)<br />\n";
} else {
$Status = fgets($connectStatus) ;
echo $Status ();
}
}
This connection is just to see the current status of a terminal.
I want to see the status of this function at the bottom of my index.php without refreshing the whole page.
I can accomplish this by putting this function in its own PHP Files (status.php) and using Javascript in the following way:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#Status').load('status.php');
}, 1000); // refresh every 1000 milliseconds
</script>
But i just want to utilise the function instead.
Is this possible?
The solution you have already is the correct way to do this: the JavaScript fetches a URL, and that URL renders the appropriate piece of content.
It's important to remember that, as far as the web browser is concerned, PHP doesn't exist. Any request from the browser - whether you've typed in a URL, followed a link, submitted a form, made an AJAX request, etc - is just a message to some remote server for a particular URL, perhaps along with some extra headers and body data. When the server receives that request, it can do whatever it likes to generate a response to the browser.
So when you write $('#Status').load('status.php');, the browser is sending a request to the server, which happens to be configured to execute the PHP script status.php. You can then do what you like in PHP to produce the response - but there is no direct link between a request and a PHP function.
However, as others have pointed out, you don't have to create a new PHP file for every piece of behaviour you want, because inside the PHP code you can check things like:
the query string parameters, in $_GET
submitted form data, in $_POST
the HTTP headers from the request
These can be set by your JavaScript code to whatever you like, so you could for instance write $('#Status').load('index.php?view=statusonly'); and then at the top of index.php have code like this:
if ( $_GET['view'] === 'statusonly'] ) {
echo get_status();
exit;
}
How you arrange this is entirely up to you, and that's what programming is all about 🙂
That's impossible to do this operation just with the PHP function.
you should use javascript as you use that or use socket in javascript to connect you status.php and update without refresh the whole page.
I'm not sure if i understood the problem but you can use AJAX to execute specific function. Something like this:
First build your ajax:
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus", // this will call the function
success: function(status){
$('#Status').text(status); // this will load the info you echo
},
});
Since you want to do it every second - wrap the whole thing with interval (i use your code from the question):
var auto_refresh = setInterval( function () {
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus",
success: function(status){
$('#Status').text(status);
},
});
}, 1000);
Then, on you PHP_FILE add condition the execute the specific function when POST been done:
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST['refreshStatus']) {
// run this code
}
Is that what you aimed to achieve?
jQuery::load() supports fragment identifiers. So you can just load the part that you want to replace:
$( "#Status" ).load( "status.php #PartId" );
This will load the HTML output of the script and extract the part. The PHP script will run completely - the rest of the HTML output will be thrown away on the JS side.

Ajax call in WP

I am creating a button to send an email to the logged-in user's branch.
Just to begin coding this, I need to send an AJAX call successfully, triggering the 'success' method of the AJAX object.
I have read that the proper way is as below, using a wp_localize() function to make the admin-ajax.php file URL available in my Javascript.But it is not working.
I have tested that the enquiry() function is getting called successfully, so the script is properly enqueued.
This is my PHP plugin code:
add_action('woocommerce_after_add_to_cart_button','ajax_register_script');
function ajax_register_script()
{
wp_register_script('mailer-script', plugins_url('/ajax-script.js', __FILE__),
array('jquery'), '1.0', true);
wp_enqueue_script('mailer-script', plugins_url('/ajax-script.js', __FILE__),
array('jquery'), '1.0', true);
wp_localize_script( 'mailer-script', 'mailer_ajax',
array( 'ajax_url' => admin_url('admin-ajax.php')) );
}
add_action('woocommerce_after_add_to_cart_button', 'button_function', 45);
function button_function()
{
echo "<div class='unique' id='mail-button' onclick='enquiry()'>
Not sure of your prescription? Click to be contacted</div>";
}
and this is my JS:
function enquiry() {
$.ajax({
url: mailer_ajax.ajax_url,
type: 'post',
data: {
action: 'go',
},
success: function () {
document.getElementById('mail-button').innerHTML = "Thankyou for your enquiry, an email has been sent to your branch. You will be contacted shortly";
},
})
};
Thanks very much for any insight.
After lots of neatening up and refactoring my code is working.
I wish i knew exactly what the problem was, as in principle the above seems to be correct.
A great help was rams0610's answer on this question.
Using AJAX in a WordPress plugin

Cannot access $wpdb, comes back NULL

I'm developing a rather simple plugin using the Wordpress Plugin Boilerplate. Utilizing AJAX, I set up a action based upon a button press that's supposed to remove an item from the custom database table I set up. The AJAX works, the button works, the call to the operating PHP file works.
However, when I get to the operating PHP file where some simple database manipulation is supposed to take place, nothing happens. The file at this point consists of:
global $wpdb;
$table_name['database_name'] = $wpdb->prefix . 'database_name';
echo var_dump($wpdb);
echo var_dump($table_name);
echo var_dump($wpdb->prefix);
That's it right now. And these var dumps come back as "NULL," "database_name", and "NULL."
What am I doing wrong here? In the few others files involved in this project everything works fine. What did I break? If it's an AJAX thing and Wordpress handles AJAX differently, I'd love to see a good tutorial for it, because the few I've found that handle Wordpress AJAX explicitly have been outdated and/or broken.
it means you are calling $wpdb even before wordpress can initialize it, or you're doing something even more weirder
it can be done something like this,
jquery
$('body').on('click', '.some-click-handler', function() {
$.ajax({
type: 'POST',
url: ajaxurl,
data: {'action':'test_ajax'},
success: function(data) {
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
});
});
your php ajax handler, though you should add more security like nonce
//wp_ajax_nopriv for non logged-in user
add_action('wp_ajax_test_ajax', function() {
global $wpdb;
wp_send_json( $wpdb );
});
checkout wordpress ajax docs https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Is it safe to use ajax get method to load information for the site?

I have an html page and I need to load some usual information(can be seen by all people) from DB.
so I put this code in the html:
<script type="text/javascript">
$(document).ready( function() {
setTimeout( "getRate()", 100 );
});
function getRate() {
$.ajax( {
type: "GET",
url: "api.php",
dataType: "json",
data: {call: 'getRate'},
success: function(result){
//set result to the DOM element....
},
error: function(){
}
});
}
</script>
and I have a api.php file like this:
<?php
if($_SERVER['REQUEST_METHOD']=="GET") {
$function = $_GET['call'];
if($function == "getRate") {
//get result from DB
echo json_encode(result);
}
}
but my code reviewer said that when put this url in the browser directly "https://****.com/api.php?call=getRate", it also returned the json result,is it safe??
well there is no secret information requested by the ajax call,so
it's I think it's OK , but I'm not sure.
Is there any security risk for doing like this?
If your question is whether or AJAX itself is secure, then yes, AJAX is used all the time to exchange information between a browser and a remote API.
As for your code specifically, there doesn't seem to be a vulnerability here provided:
The raw JSON response truly doesn't have any secret information
The SQL query (or equivalent) used to generate the JSON isn't vulnerable to injection attacks if someone tries to craft the call: getRate param to something malicious.
The AJAX call doesn't alter the state of the database
The AJAX call doesn't tie up resources for anything other than a very small amount of time. For instance someone spamming https://****.com/api.php?call=getRate shouldn't bring down the site.

Path for ajax url in Wordpress

How to call an ajax url in wordpress. Through a javascript file
I was using http://example.com/site/wp-content/plugins/pluginname/upload.php..
This is working but now I have changed the structure.
Now I want to make a call to a function inside a class
e.g
class A{
function xyz(){
include('upload.php');
}
}
Now, I am not calling upload.php through the javascript file but loading it inside the xyz function in the class.
So I want a way to call the xyz function from the javascript file.
Thanks
Read this link http://codex.wordpress.org/AJAX_in_Plugins. Do you need to register wordpress hook wp_ajax.
Add to your php code:
add_action( 'wp_ajax_xyz', array($this, 'xyz') );
In javascript
var data = {
action: 'xyz'
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
Did you see this questions:
how to call ajax on frontend of wordpress
Wordpress: how to call a plugin function with an ajax call?
And i think Getting Started with AJAX & WordPress Pagination helps you too.

Categories

Resources