1

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:

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);
           }
         });
    });
});
8
  • Have you checked the AJAX call using Firebug, Chrome, etc? Are the headers being sent like intended? What kind of response do you get from the function? Also, shouldn't "action" from the $.ajax call be inside the dataString? Are you sure it's being sent to your ajax URL? WordPress will give a "0" response if the action is not set or not valid... Jan 29, 2012 at 19:16
  • Hi Tomas, thanks for your response, Wordpress is indeed returning a "0". I'm pretty certain the action is in the correct place, but i may be wrong?
    – Danny
    Jan 29, 2012 at 19:30
  • What happens if you add add_action('wp_ajax_pfxconversion', 'pfxconversion'); right after the no_priv action? What if you change all the $ in your js to jQuery?
    – mor7ifer
    Jan 29, 2012 at 20:09
  • I managed to get a "-1" response (was "0" before) after changing $ to jQuery (i made an edit before you mentioned it :p ) adding the other action right after it still produces -1, so at least I know its working in a fashion. The problem appears to be my action in function.js - I think it needs adding to the data: but i'm not 100% sure how to add a var + the action
    – Danny
    Jan 29, 2012 at 20:16
  • From the edits you've made, you're probably requesting a "pfxconversionamount" action. Perhaps you're missing a "&" after "action=pfxconversion"? Everything else seems OK to me. Jan 29, 2012 at 21:40

3 Answers 3

0

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.

1
  • Interesting, certainly looks to be a problem, that is what i see in the source!
    – Danny
    Feb 10, 2012 at 21:41
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' );
10
  • Thanks mate but changing the js to your example hits me back with a 0 where as i was at least getting a -1 before. However i'm not sure what you mean with that last part, json_encode, I'll go look it up as i guess i'm missing something. Thanks for your help
    – Danny
    Jan 30, 2012 at 1:48
  • I added jQuery( '#result' ).html( 'failed' ); to the else statement and as i expected it is coming back as failed!
    – Danny
    Jan 30, 2012 at 1:53
  • @Danny See my edit I explain how you can use the json_encode to send variables back in your example.
    – Jared
    Jan 30, 2012 at 1:57
  • Thanks for that, I was almost there before you spoon fed me the answer :p Much appreciated. The bad news is i'm still getting "failed"! In which case i'm convinced the problem lies in here somewhere: 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');
    – Danny
    Jan 30, 2012 at 2:02
  • Which hook are you running wp_enqueue_script and wp_localize_script on or are they not hooked to any action?
    – Jared
    Jan 30, 2012 at 2:05
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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