I am new to website development and am developing a WordPress site. Although similar to another question on SO, that question does not use jQuery.AJAX but rather jQuery.post with a request type of 'category'. I have some sort of syntax problem when trying to use AJAX. I have created a simple plugin to enter a name, send it to the server, and have it echoed back. Following is the php file, my-ajax-test.php:
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'my-script-handler', plugins_url( '/my-ajax-test.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'my-script-handler', 'ajax_test', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
function my_ajax_test() {
/**** Create Input Form ****************************/
?>
<h2>Select Persons You Wish to Register</h2>
<form action="">
<input type="text" id="ajax_guest_name" name="guest_name">
<p id="ajax_guest_text">Enter Guest Name</p>
<br><br>
<input type="button" id="ajax_rsvp" name="ajax_guest" value="Register Guest">
</form>
<?php
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
function my_ajax_callback() {
$guest_name = $_POST[ajax_guest_name];
echo $guest_name;
die();
}
};
add_shortcode('My-AJAX-Test', 'my_ajax_test');
The JS file, my-ajax-test.js looks like this:
// use wordpresses version of script
var $jq = jQuery.noConflict();
$jq(document).ready(function(){
$jq("#ajax_rsvp").click(function(){
/* Send guest name to server via AJAX */
var g_name = document.getElementById("ajax_guest_name").value;
alert("RSVP Button was clicked with Guest Name: " + g_name);
$jq.ajax({
url : ajax_test.ajax_url,
type : 'post',
data : {
action: 'my-ajax-test',
ajax_guest_name : g_name
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
}); // End of button click function
}); // End of Main Document Ready Function
All seems well, but nothing is being sent to the server with the button click. The Console log has an error:
HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
(XHR)POST - http://localhost:81/wordpress/wp-admin/admin-ajax.php
I keep going over the code to see what I have wrong and can not find it. Any suggestions would be appreciated.
Hello LCSF and welcome to StackOverflow.
You have multiple errors in your code. You are posting your data to a my-ajax-test function (which doesn't exist. Your main plugin function is my_ajax_test) when what you should be doing is posting it to your my_ajax_callback function. That is the function you registered via the wp_ajax action hook. That is why Wordpress cannot find you action. In addition to that, your callback function is encapsulated inside your main plugin function, which is why even if you change the Ajax request the function will not be found due to it's scope. To solve this do the following:
In your JavaScript file change the action in your Ajax function to my_ajax_callback
Extract the my_ajax_callback function out of the my_ajax_test function. Your code structure will then look like this:
function my_ajax_test(){
//content
}
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
function my_ajax_callback(){
//content
}
Action my-ajax-test is not what you need to pass as action parameter.
Replace:
action: 'my-ajax-test',
with:
action: 'my_ajax_callback',
Related
I have a Wordpress website page where I want to enter two values- gender and manufacturer, then display a list which shows which items match the gender and manufacturer selected.
So that the whole page is not refreshed I want to do this with an AJAX request which has to follow a particular route in Wordpress which has got me completely lost. At the moment I am having trouble even passing my two variables from the HTML page through to the JS and PHP.
For some reason the code always thinks that the user has selected Men even where Women or Junior is chosen.
My HTML
<form>
<br>
<select id="gen" name="gen">
<option value="Men">Men</option>
<option value="Women">Women</option>
<option value="Junior">Junior</option>
</select>
</form>
<div><a class="chartsearch">Search</a></div>
<div id="results">
Results go here if it works
<br>
<br>
</div>
Then my JS and PHP which is currently all contained in the functions.php file in my public_html/wp-content/themes/inspiro folder.
//Load jQuery
wp_enqueue_script('jquery');
//Define AJAX URL
function myplugin_ajaxurl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myplugin_ajaxurl');
//The Javascript
function add_this_script_footer(){ ?>
<script>
jQuery(document).ready(function($) {
// This is the variable we are passing via AJAX
let str = document.getElementById('gen').value;
// This does the ajax request (The Call).
$( ".chartsearch" ).click(function() {
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'example_ajax_request', // This is our PHP function below
'str' : str // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
$("#results").text(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
});
</script>
<?php }
add_action('wp_footer', 'add_this_script_footer');
//The PHP
function example_ajax_request() {
// The $_REQUEST contains all the data sent via AJAX from the Javascript call
if ( isset($_REQUEST) ) {
$str = $_REQUEST['str'];
// This bit is going to process the gender variable and display results
if ( $str = 'Men' ) {
$results = 'Mens results';
} else {
$results = 'Other results';
}
// Now let's return the result to the Javascript function (The Callback)
echo $str;
echo $results;
}
// Always die in functions echoing AJAX content
die();
}
// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
If you select Men and click Search it displays Men Mens Results but the same happens if you select Women. This tells me that it is getting the initial value for $str as Men but not ever changing it. So there is no point going any further with my code until it does. Once it does I can get the AJAX request to search my SQL database and show real Mens Results, Women Results, Junior Results rather than just the text.
Can anyone see what I have done wrong? I know I am a clown and a complete novice but any help would be appreciated.
It's because you st your variable at the documentReady event callback. So the var has the default value (the value at the documentReady moment).
move it in the submit event:
// This does the ajax request (The Call).
$( ".chartsearch" ).click(function() {
let str = document.getElementById('gen').value;
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'example_ajax_request', // This is our PHP function below
'str' : str // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
$("#results").text(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
$str = 'Men' is always true, because assigning the value Men to $str won't fail.
To compare them, you should write: $str == 'Men'
I'm trying to send form data to a table called attendants. I have the form, the AJAX and query created, but when trying to test (when submitting the form), I see a POST http://localhost/rsvp/wp-admin/admin-ajax.php 400 (Bad Request) error on console.
Unsure what's causing this as when I run a console.log(ajaxurl); the URL it returns is http://localhost/rsvp/wp-admin/admin-ajax.php which is correct.
Unsure what's happening here?
EDIT: I've recently discovered that http://localhost/rsvp/wp-admin/admin-ajax.php returns 0.
form.php (Folder Path: rsvp > template-parts > parts > form.php) :
<div class="form sectionPadding" id="rsvp-form">
<form id="rsvpForm" method="post">
<?php get_template_part('template-parts/snippets/form-step-1'); ?>
<?php get_template_part('template-parts/snippets/form-step-2'); ?>
</form>
</div>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
form.js (form.js compiles into theme.min.js. The path to theme.min.js is rsvp > assets > build > js > theme.min.js) :
jQuery('#rsvpForm').on('submit', function(e) {
e.preventDefault();
jQuery.ajax({
action: 'send_to_db',
dataType: "text",
type: "post",
data: $('form').serialize(),
url: ajaxurl,
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error");
}
});
});
functions.php
add_action("wp_ajax_send_to_db", "send_to_db");
add_action("wp_ajax_nopriv_send_to_db", "send_to_db");
function send_to_db(){
if (isset($_POST['submit'])) {
global $wpdb;
$first_name = $_POST['fname'];
$table_name = $wpdb->prefix . "attendants";
$row_result = $wpdb->query("INSERT INTO $table_name (first_name) VALUES ('$first_name')" );
if ($row_result == 1){
echo "submitted";
} else{
echo "error";
}
die();
}
}
To summarize, my folder structure is:
rsvp
assets
build
js
theme.min.js
template-parts
parts
form
form.php
form.js
functions.php
EDIT: I've recently discovered that
http://localhost/rsvp/wp-admin/admin-ajax.php returns 0.
That's indeed the expected return value when the request (URL) doesn't contain the AJAX action name. Additionally, the HTTP response status would also be a 400 Bad Request which basically means "missing action name" or "there's no callback registered for that action".
And in your case, it seems that your AJAX script is not sending the AJAX action.
Because in your form.js script, the action parameter should be in the data — and as far as I know, jQuery.ajax() doesn't have a action property:
jQuery.ajax({
action: 'send_to_db', // this should be in 'data'
...
data: $('form').serialize(),
...
});
So you can do data: $('form').serialize() + '&action=send_to_db' like so:
jQuery.ajax({
...
data: $('form').serialize() + '&action=send_to_db',
...
});
That way, WordPress would recognize the AJAX action (via $_REQUEST['action']) and then run the proper AJAX handler / PHP callback, which is send_to_db() in your case.
And you can confirm if your AJAX callback is registered properly by visiting /wp-admin/admin-ajax.php?action=send_to_db — are you still seeing a 0?
Update
If the HTTP response status is no longer 400 (where it should now be 200), then it means your AJAX request is sending an action (send_to_db in your case) and that there's a PHP callback registered for that AJAX action (wp_ajax_send_to_db / wp_ajax_nopriv_send_to_db).
But because your callback is only doing something when the POST variable submit is set, then if your AJAX request data doesn't include that, the response would still be a 0.
If you want to avoid that, then you can do something like so:
function send_to_db() {
if ( isset( $_POST['submit'] ) ) {
// ... your code here.
//die();
} else {
echo 'Invalid request!';
}
wp_die(); // It's recommended to always call this to end an AJAX request,
// but die() is OK, too.
}
And with that, when you manually go to /wp-admin/admin-ajax.php?action=send_to_db (i.e. without sending any POST data), you'd see Invalid request! on the page. window.fetch( '/wp-admin/admin-ajax.php?action=send_to_db' ) would even receive that same response.
So now that the error 400 is gone, you just need to make sure your AJAX request is sending the proper data and that your PHP callback is working (or doing what it needs to do). And on Chrome, you can easily inspect the request and response data, headers, etc. by opening the developer tools and go to the Network → XHR tab and simply click on the relevant request.
Your SQL query is highly insecure and I strongly suggest you to use wpdb::prepare() to prepare the query for safe execution:
//$row_result = $wpdb->query("INSERT INTO $table_name (first_name) VALUES ('$first_name')" );
$query = $wpdb->prepare(
"INSERT INTO $table_name (first_name) VALUES (%s)",
sanitize_text_field( $first_name )
);
$row_result = $wpdb->query( $query );
Alternatively, for inserting a single database row/entry, you can just use wpdb::insert():
$row_result = $wpdb->insert( $table_name, array(
'first_name' => sanitize_text_field( $first_name ),
) );
And I have actually tested your original PHP callback, and it worked, so long as the request data are good. :)
I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );
I'm trying to do an AJAX request in an WordPress plugin. The request is initiated on the front page embedded in an article using a custom shortcode.
I tried to combine infos from the documentation and this tutorial.
However something is going wrong when testing that method... the AJAX query hook isn't called.
This is how my page.php script is called for short code delivery:
add_shortcode('testshortcode', 'TestShortCodeFunction');
function TestShortCodeFunction($attributes)
{
ob_start();
include(__DIR__.'/page.php');
return ob_get_clean();
}
This is my compacted test script page.php:
<?php
add_action('wp_ajax_test', 'Test');
add_action('wp_ajax_nopriv_test', 'Test');
// do_action('wp_ajax_nopriv_test'); this calls Test()
function Test()
{
echo 'Hallo';
die();
}
?>
<script type='text/javascript'>
jQuery(document).ready(function() {
console.log("JS query started");
// The following does not call test()
jQuery.ajax({
type: "POST",
url: "http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test",
success: function(data) {
console.log("Query returned: "+data);
}
});
});
</script>
Output on the console is:
JS query started
Query returned: 0
The Test() function is never call according to the PHP debugger.
The admin-ajax.php is executed according to the network monitor (URL http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test) but returns 0.
Inside admin-ajax.php do_action('wp_ajax_test') is called according to the PHP debugger.
I'd be really surprised if you managed to make those Ajax action hooks work inside an Output Buffer.
AFAIK, we should only use PHP ob_* functions as last resort.
Here's a standard implementation. A JavaScript file will be enqueued inside the shortcode callback function, and inside it we fire a document.ready Ajax call. The admin-ajax.php URL is passed to a JS object using wp_localize_script. Check the code comments for more info and the Codex for details on each WP function:
<?php
/**
* Plugin Name: (SO) Simple Ajax Shortcode
* Description: Fire an Ajax action when rendering a shortcode
* Author: brasofilo
* Plugin URL: https://stackoverflow.com/a/22585520/1287812
*/
add_shortcode( 'testshortcode', 'shortcode_so_22579460' );
add_action( 'wp_enqueue_scripts', 'enqueue_so_22579460' );
add_action( 'wp_ajax_Test_SO', 'Test_SO' );
add_action( 'wp_ajax_nopriv_Test_SO', 'Test_SO' );
/**
* Enqueue our script inside the shortcode
*/
function shortcode_so_22579460($attributes)
{
wp_enqueue_script( 'my-script' );
return '<h1>Check the broswer console.</h1>';
}
/**
* Register and localize our script
*/
function enqueue_so_22579460()
{
wp_register_script(
'my-script',
plugin_dir_url( __FILE__ ) . 'ajax.js',
array( 'jquery' ) // enqueue jQuery as dependency
);
// We can pass any number of PHP data to the JS 'wp_ajax' object
// Here, only the basics, Ajax URL and a security check
wp_localize_script(
'my-script',
'wp_ajax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' )
)
);
}
/**
* Ajax callback
*/
function Test_SO()
{
// Security check
check_ajax_referer( 'ajax_post_validation', 'security' );
// Demonstrative boolean value to return
$random = ( rand() % 2 != 0 );
if( $random )
wp_send_json_error( array( 'error' => 'Random is ODD' ) );
else
wp_send_json_success( 'Random is EVEN' );
}
And the JavaScript file (ajax.js) stored in the same folder as the plugin file:
jQuery(document).ready( function($)
{
var data = {
action: 'Test_SO',
security: wp_ajax.ajaxnonce
};
$.post(
wp_ajax.ajaxurl,
data,
function( response )
{
// Errors
if( !response.success )
{
// No data came back, maybe a security error
if( !response.data )
console.log( 'AJAX ERROR: no response' );
// Error from PHP
else
console.log( 'Response Error: ' + response.data.error );
}
// Success
else
console.log( 'Response Success: ' + response.data );
}
);
});
Here's a similar answer of mine using OOP and jQuery commands to trigger the action. And an article of interest.
I'm trying to load a .js file from a wp plugin.
The code where I load jquery, jquery-UI and my .js file look like this, and is located inside the "main" plugin file:
//Load Java and Jquery
function load_jquery() {
// only use this method is we're not in wp-admin
if (!is_admin()) {
// deregister the original version of jQuery
wp_deregister_script('jquery');
wp_deregister_script('jquery-ui');
wp_deregister_script('lyox-script');
// discover the correct protocol to use
$protocol='http:';
if($_SERVER['HTTPS']=='on') {
$protocol='https:';
}
// register the Google CDN version
wp_register_script('jquery', $protocol.'//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
wp_register_script('jquery-ui', $protocol.'//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', false, '1.10.3');
wp_register_script('lyox-script', plugins_url( '/includes/script.js' , __FILE__ ), array( 'jquery', 'jquery-ui' ) );
// add it back into the queue
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui');
wp_enqueue_script('lyox-script');
}
}
add_action('template_redirect', 'load_jquery');
Then inside the .js file I have the following code, where the post() function is added to a form button onclick="post();":
$(document).ready(function() {
function post() {
var name = $('#name').val();
$.post('process.php', {postname:name},
function(data)
{
alert(data);
$('#result').html(data);
});
}
});
Still nothing happens when I try it out on a page. Any ideas?
You can do like this using admin ajax :
I will not explain the functions . you can google it and learn .
Step 1: Localize some values for your script to be used in your javascript files,
get admin-ajax.php url
$author_nonce = wp_create_nonce( 'nk_author' );
wp_localize_script( 'nk_script', 'nk_object',array( 'nk_ajax_url' => admin_url( 'admin-ajax.php' ) , 'nk_plugin_url' => plugins_url() ,'nk_author' => $author_nonce) );
step 2 : In your script you can do this .
var data = {
action: 'nk_action', // the function that will be called in your plugin
_ajax_nonce : nk_object.nk_author, // nonce for security
id : 'mydata' //your data to be sent
};
//(admin ajax url , your data , callback for response )
jQuery.post(nk_object.nk_ajax_url, data, function(response) {
$('#nk_result').html(response);
}
});//end jQuery.post
step 3 : In your plugin.php file do this
<?php
add_action('wp_ajax_nk_action', 'nk_action_callback');
function nk_action_callback() {
check_ajax_referer('nk_author');
if(isset($_POST['id']))
{
$id=$_POST['id'];
echo $id;
}
die();//dont forget to write die
}?>