0

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?




enter image description here

enter image description here

  • "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 Jan 9 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 Jan 9 at 14:55
  • add console.log(data) to your ajax success function so you can see what you're getting back – mrben522 Jan 9 at 15:38
  • i had add consol.log(data) . its show my html source code, why? – Gufyand D Jan 9 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 Jan 25 at 4:26
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"}

  • {"success":true,"data":"berita"} i got this too, thanks, but how i use the data in function.php? i want to echo that data, i mean just the data not "success":true – Gufyand D Jan 10 at 9:23
  • @GufyandD In your JS, use response.data and work from there. – coolpasta Jan 10 at 11:34
  • what do you mean by that? where i have to add that, can you give the code – Gufyand D Jan 10 at 12:49
  • i had add that and got this on console ReferenceError: response is not defined – Gufyand D Jan 10 at 12:56
  • @GufyandD What are you trying to achieve exactly? Is this a system you're building or? – coolpasta Jan 10 at 12:59
0

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: ![enter image description here

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

  • thank you very very much, but i'm give up now, it still wont write anything i don't know what is my fault, i'm give up with wordpress – Gufyand D Jan 25 at 8:18
  • but i really apreciate your good heart, thanks – Gufyand D Jan 25 at 8:19
  • I suggest you to not to give up. Learn basic html/css, javascript ( jquery is easy to learn ), then php, mysql, then WordPress. With time and effort you will improve your coding skills ( because I did so ). – maverick Jan 25 at 8:23
  • thanks, it working now !!! :D , but just in network preview, i got html in response payload, it wont change the page, maybe because the response is html – Gufyand D Jan 25 at 8:41
  • that html response should be in the console log tooooo Please show screenshot – maverick Jan 25 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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