0

I made top menu in wp admin dashboard. There I will have input field. It will be input where admin can enter Google locations. After picking correct location admin will press save and location will be saved into wordpress database in locations table. For now I made text input field only to test it. I have:

 <form id="location_form" method="post" action="save-locations.php">
                    <table class="form-table">
                <tr valign="top">
                    <th scope="row">Enter location:</th>
                    <td>
                        <div class="container">
       <div class="row">
  <input type="text" id="username" name="username" placeholder="Username" autocomplete="off" class="required"/>
  </div>
               </td>
               </tr>
   <input id="submit" name="submit" type="submit" value="Send It" />
   </form>
        <div id="response"></div>
    </div>

Than I have save-location.php located in wp-admin folder where I make sql insert into db and I have validate.js where I have aja call:

  function ajaxSubmit() {
  //loading circle so user can see something is happening
    $('#submit').attr('disabled', 'disabled');
 //collect data
 var username = $('#username').val();
 //put data in one variable
var data = 'username=' + username;

$.ajax({
    url: "save-location.php", //send it to php to handle data
    type: 'get',
    dataType: 'json',
    data: data,
    cache: false,
    success: function (response) {
        if (response.error != 'true') {

            $('#response').html('<h3>Records added successfully.</h3>').fadeIn('slow');


        }
        else {

            $('#response').html('<h3>Could not able to execute sql</h3>').fadeIn('slow');
        }
    },
    error: function (jqXHR, textStatus, errorThrown) {

        $('#response').text('Error Thrown: ' + errorThrown + '<br>jqXHR: ' + jqXHR + '<br>textStatus: ' + textStatus).show();
    }
 });
 return false;
}

But nothing happens. Where I made msitake?

1

1 Answer 1

1

When doing AJAX call in WordPress, you should always post to admin-ajax.php file. Here's how you do that.

In your plugin or functions.php:

function process_my_ajax_call() {
    // Do your processing here (save to database etc.)
    // All WP API functions are available for you here
}
// This will allow not logged in users to use the functionality
add_action( 'wp_admin_my_action_no_priv', 'process_my_ajax_call' );
// This will allow only logged in users to use the functionality
add_action( 'wp_admin_my_action', 'process_my_ajax_call' );

You'll also have to pass the correct URL to the admin-ajax.php file to your JavaScript and wp_localize_script function is great just for that:

function localize_my_scripts() {
    $localizations = array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
    );

    wp_localize_script( 'my-script-handle', 'myVars', $localizations );
}
add_action( 'wp_enqueue_scripts', 'localize_my_scripts' );

Now in your JavaScript:

$.ajax({
    url: myVars.ajaxUrl, // Notice the AJAX URL here!
    type: 'post',
    data: 'username=test&action=my_action', // Notice the action name here! This is the basis on which WP calls your process_my_ajax_call() function.
    cache: false,
    success: function ( response ) {
        // Parse ajax response here
        // Do something with the response
    },
    error: function ( response ) {
        // Handle error response here
    };
});

This is, of course, just a huge summary of how to make AJAX calls in WordPress. You will still need to verify nonces, create a proper AJAX response using WP_Ajax_Response class and then enqueue the wp-ajax-response script on frontend to process WP's response. If you want to learn more, there's a comprehensive guide to AJAX in WordPress written by Ronald Huereca and it's available for free!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.