Hot answers tagged

67

Check the constant DOING_AJAX. Its definition is the first working code in wp-admin/admin-ajax.php. Some very weird plugins, like Jetpack, are defining that constant in unexpected places, so you might include a check for is_admin() as well. Example: if ( is_admin() && defined( 'DOING_AJAX' ) && DOING_AJAX ) { // do something } I have ...


55

In backend there is global ajaxurl variable defined by WordPress itself. This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself. Good way to do this is to use wp_localize_script. Let's assume your AJAX calls are in my-ajax-script.js file, then add ...


44

A 0 response means either that the action is not set (in the ajax data) or that the action's callback function cannot be found.


43

to use ajaxurl directly, in your plugin file add this: add_action('wp_head', 'myplugin_ajaxurl'); function myplugin_ajaxurl() { echo '<script type="text/javascript"> var ajaxurl = "' . admin_url('admin-ajax.php') . '"; </script>'; } you can then use the ajaxurl for ajax request.


34

The default response from admin-ajax.php is, die( '0' ); ...by adding your own wp_die() or exit() or die() after returning your desired content prevents the default response from admin-ajax.php being returned as well. It also generally means that your ajax call has succeeded. Ultimately, to answer your question, it's meant to work this way. What you ...


28

admin-ajax.php loads wp-load.php: /** Load WordPress Bootstrap */ require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' ); wp-load.php loads wp-config.php, and there wp-settings.php is loaded. And here we find this: // Load the functions for the active theme, for both parent and child theme if applicable. if ( ! defined( 'WP_INSTALLING' ) || 'wp-...


25

What you have to do is add die();at the end of your function. See the reason and more here: http://codex.wordpress.org/AJAX_in_Plugins Notes: You should echo something before executing die. This will prevent server errors, and will help when debugging.


23

using wp_die(); at the end of AJAX function fixed the issue for me. e.g add_action( 'wp_ajax_my_ajax_function', 'my_ajax_function' ); function my_ajax_function(){ echo json_encode($myvar); wp_die(); }


22

wp_send_json() handles all parts of returning content in an AJAX call. First off, it sets the content type of the returned content to application/json with the proper charset. Secondly, it automatically calls wp_die() after sending the JSON result, which is necessary in an AJAX call in WordPress. You could consider using wp_send_json_success() for ...


19

You could just use a RewriteRule to your .htaccess above the regular permalink rewrite rules: RewriteRule ^ajax$ /wp-admin/admin-ajax.php [L] Now send your AJAX requests to example.com/ajax, and never miss core changes to that file after upgrades.


18

The errors I've spotted in your code: One was pointed by @helgatheviking in a comment: the Ajax callback has to be a public method, not private. Not sure how are you initializing this class, but wp_enqueue_script&_style (in singular) has to be encapsulated inside a wp_enqueue_scripts hook (WP_DEBUG dumps a notice). You can drop the & from $this, ...


17

Using wp_die() is the best of those options. As others have noted, there are many reasons to prefer a WordPress-specific function over the plain die or exit: It allows other plugins to hook into the actions called by wp_die(). It allows a special handler for exiting to be used based on context (the behavior of wp_die() is tailored based on whether the ...


17

I think the only thing missing here is that you need to move add_action('wp_ajax_nopriv_ajaxlogin','ajax_login'); outside ajax_login_init. That code registers your Ajax handler, but when you only run it on wp_enqueue_scripts, it's already too late and wp_ajax_nopriv_ hooks are already run. So, have you tried something like this: function ajax_login_init(){...


17

If you do not die, execution will continue and might generate extra output which might break whatever information you are trying to send from the server to the browser. Strictly speaking, you might not need to die, but there is very little point in taking the risk. In more general terms, WordPress Ajax shows its age and the lack of experience working with ...


16

1) Why use admin-ajax.php instead of encoding your json in a separate file like themes/example/json.php and encode your data there? Using admin-ajax.php means that the WordPress Core is loaded and available. WIthout that, you would need to hand load the files you need, which is a complicated process and prone to failure if you don't know the Core very, ...


15

I had the same problem. Solution: add_action('wp_ajax_nopriv_my_action', 'my_action_callback'); add_action('wp_ajax_my_action', 'my_action_callback'); If you dont add both (with and without nopriv) it will work in either signed in mode or signed out mode only. nopriv is for signed out, the other is for signed in.


15

Could you place the action (ajaxConversion) in your Data and check? jQuery.ajax({ type:"POST", url: ajaxurl, data: { action: "ajaxConversion", amount: amountToConvert }, success:function(data){ alert(data); }, error: function(errorThrown){ alert(errorThrown); } });


15

you can use FormData an example: let form_data = new FormData; form_data.append('action', 'myAction'); form_data.append('first_name', 'my first name'); form_data.append('phone', 'my phone'); axios.post(myVars.ajax_url, form_data).then(function(response){ console.log(response.data); })


15

You don't need apiFetch or localization to get a list of all categories. You can do this with the wp.data module: wp.data.select('core').getEntityRecords('taxonomy', 'category'); See the Gutenberg Handbook entry on Core Data for more details.


14

Here is a working solution (tested as is) The HTML (could be part of page content) <input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input> <div id="datafetch">Search results will appear here</div> The JavaScript ( goes to your theme's functions.php ) // add the ajax fetch js add_action( 'wp_footer', 'ajax_fetch' ...


14

From the codex AJAX in Plugins add_action( 'wp_ajax_my_action', 'my_action_callback' ); function my_action_callback() { global $wpdb; // this is how you get access to the database $whatever = intval( $_POST['whatever'] ); $whatever += 10; echo $whatever; wp_die(); // this is required to terminate immediately and return a proper ...


13

Its an old question however would like to answer for other people Within ajax function hooked to wp_ajax do this. $url = wp_get_referer(); $post_id = url_to_postid( $url );


12

For me the trick was to add wp_ajax_nopriv action. I tested the script on one browser when I was logged in WP admin, and then I tried same script in Chrome and realized that the script doesn't work. After I put wp_ajax_nopriv, everything started to work. :) add_action( 'wp_ajax_nopriv_erase_uploaded_images', 'erase_uploaded_images' ); add_action( '...


12

What you're experiencing (AJAX works locally, but not on the server) there is a delay problem. Locally everything works that fast, that you can't see your problem. In short, this is your problem: AJAX callback (A) executes > AJAX Callback (B) doesn't know that it has to wait for (A) > You can't see the problem in your local install as (A) is finished too ...


12

When you use jQuery.post(), the data is sent as regular $_POST arguments. So this JavaScript … var data = { action: 'load_post', foo: 'bar' }; … is available in your callback function per: $action = $_POST['action']; $foo = $_POST['foo']; // bar And when you are using jQuery.get(), the data is in $_GET. You can also use $_REQUEST which ...


11

In WordPress, nonces are specific to the user, the action being performed, and the time. With regards to time, a nonce is valid for 24 hours, and changes every 12 hours. This is considered an acceptable trade-off, since using a real number-used-once would involve adding a tracking system and having storage of the used nonces. Nonces are also hashed, and so ...


11

Our journey starts here with the WP_Customize_Background_Image_Control class, which is a WP_Customize_Image_Control. I'd imagine offering these built-in backgrounds in a new tab alongside the existing Upload New and Uploaded tabs. There are at least two ways of achieving the following: either creating your own modified class based off of the ...


11

Hi You have Use this COde For WordPress front-end AJAX file upload tutorial Code Here is my code: In my template file example.php <form enctype="multipart/form-data"> <input type="text" name="support_title" class="support-title"> <input type="file" id="sortpicture" name="upload"> <input class="save-support" name="save_support" ...


10

The action should be part of the data object: var formdata = new FormData(); formdata.append('name', 'This is Name'); formdata.append('action', 'plugin_save'); $.ajax({ url: 'admin-ajax.php', type: 'POST', data: formdata, contentType:false, processData:false, success: success, error: error });


10

it seems the latter only accepts x-www-form-urlencoded That's not completely true. WordPress admin-ajax.php takes the action from $_REQUEST['action'] and $_REQUEST is equal to: array_merge($_POST, $_GET); But what many people don't realize is that $_GET in PHP is not the data was sent to page using HTTP GET method, in fact, you can use whatever HTTP ...


Only top voted, non community-wiki answers of a minimum length are eligible