WordPress Ajax Callback

0 Votes
    955 Views

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;
});
});

7

Answers


  1. otinane

    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

Please signup or login to answer this question.