theme development - my ajax wont sent the data, please correct my code

admin2025-01-07  3

First please excuse my English. So I built my own WordPress theme and want to use ajax in it, I'm using ajax for change post category in my post loop inside functions.php, so when a person clicked the button in index.php ajax will send the data and functions.php will change the category, the problem is i can't reach admin-ajax.php

SO IN HERE MY CODE IS JUST FOR TESTING IF THE AJAX WORK OR NOT, IT WONT ECHO THE POST THAT HAD BEEN SENT

This is my .js file that contains ajax

  function kategori(kategori2){
      //alert(kategori2);
      jQuery.ajax({
        url: MyAjax.ajax_url,
        type: "POST",
        data: { action: "berubah", kategori: "berita"},
        success : function(data) {

        }
      });

  }

This is my function.php

<?php

// Support Featured Images
add_theme_support( 'post-thumbnails' );

add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );

function my_script_enqueuer() {
    wp_register_script( 'add-order-front',  get_template_directory_uri() . '/js/programku.js' );
    wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'add-order-front' );

}

add_action( 'wp_ajax_berubah', 'berubah' );
add_action( 'wp_ajax_nopriv_berubah', 'berubah' );

function berubah()
{
    $kategori = isset( $_POST['kategori'] ) ? $_POST['kategori'] : '';
    echo $kategori;
    wp_die();
}



I new to javascript too, I use Mozilla console and got this

'ReferenceError: ajax_object is not defined'



EDIT #1 -

i can reach admin-ajax.php now, my fault was i didn't have header.php on my theme, sorry i new in wordpress

now my problem is, function.php can't get the data sent by AJAX from programku.js and response in console is an HTML code


in my theme i just have 5 files

  1. index.php
  2. programku.js inside the js folder
  3. header.php
  4. footer.php
  5. and last functions.php

Is there is a files that important in wordpress theme developing that i left?




First please excuse my English. So I built my own WordPress theme and want to use ajax in it, I'm using ajax for change post category in my post loop inside functions.php, so when a person clicked the button in index.php ajax will send the data and functions.php will change the category, the problem is i can't reach admin-ajax.php

SO IN HERE MY CODE IS JUST FOR TESTING IF THE AJAX WORK OR NOT, IT WONT ECHO THE POST THAT HAD BEEN SENT

This is my .js file that contains ajax

  function kategori(kategori2){
      //alert(kategori2);
      jQuery.ajax({
        url: MyAjax.ajax_url,
        type: "POST",
        data: { action: "berubah", kategori: "berita"},
        success : function(data) {

        }
      });

  }

This is my function.php

<?php

// Support Featured Images
add_theme_support( 'post-thumbnails' );

add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );

function my_script_enqueuer() {
    wp_register_script( 'add-order-front',  get_template_directory_uri() . '/js/programku.js' );
    wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'add-order-front' );

}

add_action( 'wp_ajax_berubah', 'berubah' );
add_action( 'wp_ajax_nopriv_berubah', 'berubah' );

function berubah()
{
    $kategori = isset( $_POST['kategori'] ) ? $_POST['kategori'] : '';
    echo $kategori;
    wp_die();
}



I new to javascript too, I use Mozilla console and got this

'ReferenceError: ajax_object is not defined'



EDIT #1 -

i can reach admin-ajax.php now, my fault was i didn't have header.php on my theme, sorry i new in wordpress

now my problem is, function.php can't get the data sent by AJAX from programku.js and response in console is an HTML code


in my theme i just have 5 files

  1. index.php
  2. programku.js inside the js folder
  3. header.php
  4. footer.php
  5. and last functions.php

Is there is a files that important in wordpress theme developing that i left?




Share Improve this question edited Jan 25, 2019 at 8:52 Gufyand D asked Jan 8, 2019 at 15:23 Gufyand DGufyand D 14 bronze badges 5
  • "this is my file" - is it the functions.php file of your custom theme? And in the source code (HTML of the page), find the variable ajax_object - if it's nowhere, then your script may not be loaded/registered on that page. – Sally CJ Commented Jan 9, 2019 at 2:09
  • its function.php , now the ajax is work, the problem now is the function.php wont retrieve data that sent by ajax – Gufyand D Commented Jan 9, 2019 at 14:55
  • add console.log(data) to your ajax success function so you can see what you're getting back – mrben522 Commented Jan 9, 2019 at 15:38
  • i had add consol.log(data) . its show my html source code, why? – Gufyand D Commented Jan 9, 2019 at 15:44
  • @maverick thanks for editing, but it still wont echo the data, can you give me a simple wordpress code that had ajax in it? so i can understand what is my fault – Gufyand D Commented Jan 25, 2019 at 4:26
Add a comment  | 

2 Answers 2

Reset to default 0
function kategori(){
    //alert(kategori2);
    jQuery.ajax({
        url: MyAjax.ajax_url,
        type: "POST",
        data: {
            action: "berubah",
            kategori: "berita"
        },
        success : function(response) {
            console.log(response);
            //Acess whatever you sent from the back-end with response.data.%var_name%
        },
        error: function(data ) {
            console.log(response);
        }
    });
}

function berubah()
{
    $kategori = $_POST['kategori'];
    wp_send_json_success( $kategori, 200 );
}

Use wp_send_json_success.

Response I got:

{"success":true,"data":"berita"}

as requested by Gufyand D here is simple ajax request in wordpress ( based on question )

***place this code inside your js file***
(function($){
    $('div#element_id').on('click', function(){
    // here idea is to get values from page using js to send them as data e.g. var cat_name = you can get category name using jquery.

    $.ajax( {
        type: 'post',
        url: MyAjax.ajax_url,
        data: {
            action: 'berubah',
            cat_name: var_name // if you used a js var to store category name, just type variable name else if you want to use static value then wrap them in quotes like "category_name".
        },
        success: function(response){
            console.log(response);
        }
    } );
 } );
})(jQuery);

This is minimum javascript code to see ajax in action ( console.log )

Now, functions.php file

NOTE: you should know in which theme you are making changes ( parent or child; as enqueuing scripts process varies ). Following code is for parent theme's functions.php file

add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );

function my_script_enqueuer() {
    wp_register_script( 'add-order-front',  get_template_directory_uri() . '/js/programku.js' );
    wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'add-order-front' );

}

add_action( 'wp_ajax_berubah', 'berubah' ); // this is for logged in users
add_action( 'wp_ajax_nopriv_berubah', 'berubah' ); // this is for non logged in users

function berubah()
{
    // always check if the value is set or not ( I like ternery operator to do this )
    $kategori = isset( $_POST['cat_name'] ) ? $_POST['cat_name'] : ''; // you need to match the data sent from js file to this file i.e., the variable name used in the js file to send category name should match the array key you want to retrieve using POST superglobal
    echo $kategori;
    wp_die(); // always terminate ajax request after finishing your purpose i.e., wp_die() will prevent further execution of the script ( just in case )
}

To check response see screen shot:

Final Notes:

  1. make sure your script is available to the page you are viewing
  2. when developing, always turn on WP_DEBUG

I hope this helps you a little

Cheers!!!

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736260515a671.html

最新回复(0)