Jquery variable returns null

I am working on a wordpress shop right now and trying to implement a currency converter. So in the cart table is a dropdown list of available currencies.

When clicked the price should show up in that currency. Simple enough…

Read More

Here is part of the php with the list:

<section class="currency-converter-form" style="display:none;">

        <p class="form-row form-row-wide" id="convert_to_field">
        <select name="currency" id="currency" class="currency_to" rel="convert_currency_to" >
            <option value="gbp" >GBP - British Pound Sterling</option>
            <option value="usd" >USD - US Dollar</option>
            <option value="aud" >AUD - Australian Dollar</option>
            <option value="cad" >CAD - Canadian Dollar</option>
            <option value="jpy" >JPY - Japanese Yen</option>
            <option value="nzd" >NZD - New Zealand Dollar</option>
            <option value="rub" >RUB - Russian Ruble</option>
            <option value="chf" >CHF - Swiss Franc</option>
        </select>
        </p>

Here is what I have as the jquery so far:

jQuery( function( $ ) {

$( document ).on( 'click', '.currency-converter-button', function() {
    $( '.currency-converter-form' ).slideToggle( 'slow' );


    return false;
}).on( 'change', function() {

    var currency = $( "#currency" ).val();

    console.log(currency);

    jQuery.ajax({
    type: 'POST',
    url: currency_conversion.ajaxurl,
    data: {
        action: 'get_conversion',
        currency
    },
    success: function (data, textStatus, XMLHttpRequest) {
        alert(data);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

    });$( '.currency-converter-form' ).hide();
});

Here the target php just to test the thing:

    add_action( 'wp_ajax_get_conversion', 'get_conversion' );



function get_conversion() {

 $to = $_POST['currency'];

 echo json_encode($to);}

I basically tried to use code already existing in wordpress an adjusted it. I would be happy if the alert would give me the selcted currency, but it returns 0.

I googled a lot and tried different things to no avail. I would appriciate any help here.

Related posts

1 comment

  1. I’m not sure if this is the only problem in your code, but it’s definitely one: the currency value inside the data that is passed to PHP has no key. The correct data to pass would then be:

    data: {
        action: 'get_conversion',
        currency: currency
    },
    

    With this, PHP should now be able to access $_POST['currency'] to get the currency value unless there are other problems.

Comments are closed.