Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda