Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Javascript Ajax call to functions.php using wordpress

Hi I am following a tutorial on Ajax calls in wordpress. The example has all the code in functions.php but I want to be more organised and include the javascript in a js file.

Here is what I have so far

functions.php

//The PHP
function example_ajax_request() {
    // The $_REQUEST contains all the data sent via AJAX from the Javascript call
    if ( isset($_REQUEST) ) {
        $fruit = $_REQUEST['fruit'];
        // This bit is going to process our fruit variable into an Apple
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }
        // Now let's return the result to the Javascript function (The Callback)
        echo $fruit;
    }
    // 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' );

and in the Javascript file test.js:

var ajaxurl = "' . admin_url('admin-ajax.php') . '";

// This is the variable we are passing via AJAX
var fruit = 'Banana';
// This does the ajax request (The Call).

$( ".banana" ).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
          'fruit' : fruit // This is the variable we are sending via AJAX
      },
      success:function(data) {
  // This outputs the result of the ajax request (The Callback)
          $(".banana").text(data);
            window.alert("here");
      },
      error: function(errorThrown){
          window.alert(errorThrown);
      }
  });
});

How can: 'action':'example_ajax_request', // This is our PHP function below

be accessed from the functions.php file?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!