Hot answers tagged

67

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 ...


48

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.


29

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.


27

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(); }


24

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 ...


24

Now I got it! WordPress is just awesome. Also Thank you knif3r, your suggestions help me lot. I am trying to explain it in my words. Please correct me, if I am wrong. What is nonce? Nonce is something like security hash to prevent attacks and mistakes. It creates unique identifiers to check if the ajax request is coming from website or not. In WordPress ...


21

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 ...


21

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.


20

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 ...


20

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(){...


19

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); })


18

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 ...


17

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 );


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, ...


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

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 ...


13

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" ...


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( '...


11

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 ...


11

Currently there is no straight way to add custom price to product which is added through function $woocommerce->cart->add_to_cart (Documentation) but we have a bypass way that i explain in code below global $woocommerce; $custom_price = 1000; // Cart item data to send & save in order $cart_item_data = array('custom_price' => $custom_price); ...


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

You need to send your data in application/x-www-form-urlencoded format. As axios sends json $_REQUEST['action'] is not received by wordpress and it returns '0'. To achieve this you can use either use URLSearchParams API or Qs. Now suppose your jQuery was something like this var data = { action: 'get_names', key2:'value2' ...... }; jQuery.post('/wp-admin/...


10

Option 1 The simple way - return all the posts in JSON format and loop through them in JavaScript PHP: function get_ajax_posts() { // Query Arguments $args = array( 'post_type' => array('products'), 'post_status' => array('publish'), 'posts_per_page' => 40, 'nopaging' => true, 'order' => 'DESC'...


10

The issue here, I think, is how axios works. Not WordPress. But you're absolutely correct to want to use a POST request here. By default I believe axios sends data in a POST request as JSON in the body. To get JSON in the body of the request in PHP you need to do this (from here): $inputJSON = file_get_contents('php://input'); $input = json_decode($...


9

This was very frustrating to figure out. I spent hours on this issue and discovered your problem is in this input: <input type="text" name="name" id="name" size="30" value=""/> Try changing the input field name to anything but "name", for example: <input type="text" name="user_name" id="name" size="30" value=""/>


9

You can also use wp_send_json() described in the Codex as send a JSON response back to an AJAX request, and die(). So, if you have to return an array, you only have end your function with wp_send_json($array_with_values);. No need to echo or die. You also get two help helper functions wp_send_json_success() and wp_send_json_error() which adds a key named ...


9

Create a child theme so you don't mess with the code of an existing theme because next time you'll update the theme, you may loose all your changes (see Child Themes) Here is how to pass values to your ajax request: jQuery(document).ready(function() { jQuery(".mark-as-read").click(function () { console.log('The function is hooked up'); jQuery....


8

You can use the inbuilt spinner class : Add the class to the HTML where you want the spinner to appear, for example after your search button : <button type="button" id="searchsubmit">Search Button</button> <span class="spinner"></span> <!-- Add this spinner class where you want it to appear--> In jQuery you should add the ...


8

I would recommend using wp_send_json_success() and wp_send_json_error() on server side. You don't need to worry about die() etc and the "status" variable is sent automatically, it's much cleaner this way. For example function ajaxConversion(){ // ... wp_send_json_success(array( 'amount' => $amount )); } Will result in something like ...


8

BODA82's answer helped, but eventually I realized that I should have replaced responseText with responseJSON method in my JavaScript code. In the example below I was storing the Ajax response results in a variable. I didn't know there was a specific method to get the response in JSON. In a such way the object/array with get_posts() results is returned ...


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