Frontend Ajax call not working using wp_ajax, wp_enqueue_script and wp_localize_script

I think i’ve almost got my head around this ajax is WordPress business, thoroughly ejoying learning it but i’m now totally stumped.

First up is the nasty bits! I have these in my main plugin file:

Read More
wp_enqueue_script( 'function', plugin_dir_url( __FILE__ ) . 'function.js', array( 'jquery', 'json2' ) );
wp_localize_script( 'function', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

add_action('wp_ajax_nopriv_pfxconversion', 'pfxconversion');

Here is what’s is function.js

$(document).ready(function() {

    $("#convert").click(function () {
                var from = $("#from").val();
                var to = $("#to").val();
                var amount = $("#amount").val();

    //Make data string
     var dataString = "amount=" + amount + "&from=" + from + "&to=" + to;

         $.ajax({
           type: "POST",
           action: pfxconversion,
           url: MyAjax.ajaxurl,
           data: dataString,
           success: function(data){

           $('#result').show();

            //Put received response into result div
            $('#result').html(data);
           }
         });
    });
});

and here is the function that I know works perfectly outside of WordPress.

function pfxconversion () {
//Get Posted data
$amount = $_POST['amount'];
$from = $_POST['from'];
$to = $_POST['to'];

//make string to be put in API
$string = "1".$from."=?".$to;

//Call Google API
$google_url = "http://www.google.com/ig/calculator?hl=en&q=".$string;

//Get and Store API results into a variable
$result = file_get_contents($google_url);

//Explode result to convert into an array
$result = explode('"', $result);

################################
# Right Hand Side
################################
$converted_amount = explode(' ', $result[3]);
$conversion = $converted_amount[0];
$conversion = $conversion * $amount;
$conversion = round($conversion, 2);

//Get text for converted currency
$rhs_text = ucwords(str_replace($converted_amount[0],"",$result[3]));

//Make right hand side string
$rhs = $conversion.$rhs_text;

################################
# Left Hand Side
################################
$google_lhs = explode(' ', $result[1]);
$from_amount = $google_lhs[0];

//Get text for converted from currency
$from_text = ucwords(str_replace($from_amount,"",$result[1]));

//Make left hand side string
$lhs = $amount." ".$from_text;

################################
# Make the result
################################

echo $lhs." = ".$rhs;exit;
}

The problem is I don’t get the result from my function / ajax request printed out in the #result div

Any help is greatly appreciated.

Edit I’m now getting a -1 value in #result, after changed my js from $ to jQuery – Firebug was reporting an error ($ is not a function).

Edit 2 I’m pretty certain I have the action right now but i’m still getting an output in #result of -1:

jQuery(document).ready(function() {

    jQuery("#convert").click(function () {
                var from = jQuery("#from").val();
                var to = jQuery("#to").val();
                var amount = jQuery("#amount").val();

    //Make data string
     var dataString = "amount=" + amount + "&from=" + from + "&to=" + to;

         jQuery.ajax({
           type: "POST",
           url: MyAjax.ajaxurl,
           data: "action=pfxconversion"&dataString, 
           success: function(data){
           jQuery('#result').show();

            //Put received response into result div
            jQuery('#result').html(data);
           }
         });
    });
});

Related posts

Leave a Reply

3 comments

  1. Look at the top of your generated HTML source code. Are you seeing something like this:

    <script type='text/javascript'>
    /* <![CDATA[ */
    var MyAjax = {"ajaxurl":"http://localboast/home/wp2/wp-admin/admin-ajax.php"};
    /* ]]> */
    </script>
    

    wp_localize_script now escapes whatever you pass into it. So that the problem I have.

  2. In your jQuery, maybe try something like this:

    jQuery( document ).ready( function() {
    
        jQuery( "#convert" ).click( function() {
            var from = jQuery( "#from" ).val();
            var to = jQuery( "#to" ).val();
            var amount = jQuery( "#amount" ).val();
    
            //Make data string
            var dataString = "amount=" + amount + "&from=" + from + "&to=" + to;
    
            jQuery.post( MyAjax.ajaxurl, {
                action: 'pfxconversion',
                data: dataString
            }, function( data ) {
    
                if( data.response === 'success' ) {
    
                    // Success
                    jQuery( '#result' ).show();
    
                    //Put received response into result div
                    jQuery( '#result' ).html( data.html );
    
                } else {
    
                    // Failure
    
                }
    
            } );
        } );
    } );
    

    The PHP function that this AJAX call sends data to and receives data from should send back a JSON encoded array and also I added in a ‘success’ and ‘failure’ variable called response, might as well send this back with your AJAX call for better accuracy.

    Your JSON encoded array that you send back to the AJAX should look something like this:

    $response = json_encode( array( 'response' => 'success', 'html' => 'some value' ) );
    echo $response;
    exit; // This is needed to send back properly
    

    Edit

    Based on your example, you should change this line:

    echo $lhs." = ".$rhs;exit;
    

    to something like

    echo json_encode( array( 'html' => $lhs." = ".$rhs, 'response' => 'success' ) ); exit;
    

    And then you could access it with data.html in your AJAX function.

    Edit 2

    On another note, you need to enqueue your scripts in the wp_enqueue_scripts hook like below. You would remove these codes and re-place them in your plugin like this (also changed the location of the file to use plugins_url()):

    function enqueue_some_scripts() {
    
        wp_enqueue_script( 'json2' );
        wp_enqueue_script( 'jquery' ); // If not loaded in your theme already, wouldn't hurt here though I don't think!
    
        wp_enqueue_script( 'function', plugins_url( 'function.js', __FILE__ ), array( 'jquery', 'json2' ) );
        wp_localize_script( 'function', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    
    }
    
    add_action( 'wp_ajax_nopriv_pfxconversion', 'pfxconversion' );
    add_action( 'wp_enqueue_scripts', 'enqueue_some_scripts' );
    
  3. This is incredibly late answer, but in WP you need to die() at the end of your php AJAX function. If you don’t die you get that 0 response. Check out the wp-admin/admin-ajax.php file.