WordPress Ajax Callback

I want your help as I am new in Ajax and WordPress. This is a simple plugin and I want to know what I am doing wrong and getting “zero” result

ajax.php

    add_shortcode( 'ajax_shortcode', 'ajax_shortcode_function' );

  function ajax_shortcode_function() {
  wp_enqueue_script('jquery');
  wp_register_script ('ajax_script', plugins_url( '/ajax.js', __FILE__ ), plugins_url( '/ajax.js', __FILE__ ), array('jquery'));
  wp_enqueue_script ( 'ajax_script' );
  wp_localize_script ( 'ajax_script', 'ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' )));


  function my_submit_process() {
    global $wpdb;
    $text1 = $_POST['text1'];
    $text2 = $_POST['text2'];

    echo $text1 + $text2;
    wp_die();
echo 'sfdasdfsdfsdfas';
echo $text1 + $text2;
  }

  add_action('wp_ajax_submit_process', 'my_submit_process');
  add_action('wp_ajax_nopriv_submit_process', 'my_submit_process');
?>
<input type="text" id="text1"> +
<input type="text" id="text2">
<button id="button"> = </button>
<div id="result"></div>
<?php
}

ajax.js

jQuery(document).ready(function($){

$('#button').click(function(e) {
    var val1 = $('#text1').val();
    var val2 = $('#text2').val();
    $.ajax({
        type: 'POST',
        url: ajax.ajax_url,
        data: { action: 'submit_process', text1: val1, text2: val2 },
        success: function(response) {

            $('#result').html(response);
        }
    });
    return false;
});
});

3

Answers


  1. otinane
    1 Votes

    I just saw that in wp_register_script i have

    plugins_url( '/ajax.js', __FILE__ )
    

    twice. I removed it and I get the 0 result again

  2. sdexp
    1 Votes

    I see you are using wp_die(). I would put a die() at the end of the method instead of a wp_die() in the middle like that. I don’t know if it would make a difference.

  3. scott
    0 Votes

    It looks odd to me that your ajax_shortcode_function() registers and enqueues your ajax script. According to the codex, you should register/enqueue in functions.php. Additionally, if you only need the url to ajax-admin.php, the tutorial says you can use the global ajaxurl variable and therefore you don’t need to localize your script.

    The other thing that looks odd is my_submit_process() seems to be located within ajax_shortcode_function(). I’d check that the closing brace is in the correct location and try again if it isn’t.

Please signup or login to answer this question.

Signup for an account and start participating in our site today!




Social Signup

You can also login with your Facebook, Twitter or Linkedin account

Log in with Facebook