0

I have the following form

<form name="interest_calculator" id="interest_calculator">
                    <input type="hidden" name="action" value="calculate_investor_interest" />
                    <div class="tab">
                        <h4><span class="badge">01</span> Investment Details</h4>
                        <div class="form-group">
                            <label for="currency_type">Select Currency</label>
                            <select name="currency_type" id="currency_type" class="form-control">
                                <option value="USD" selected>USD</option>
                                <option value="KSHS">KSHS</option>
                            </select>
                            <small>For USD transactions,our dollar exchange is @ <strong>1 USD = <?php echo get_option('qfe_buying_rate');?> KES today(buying)</strong> and @ <strong>1 USD= <?php echo get_option('qfe_selling_rate');?> KES today(selling)</strong></small>
                        </div>
                        <div id="principal_amount_group" class="form-group">
                            <label for="principal_amount">Amount to  Invest</label>
                            <small id="amount_error" class="error"></small>
                            <input type="text" required name="principal_amount" id="the_principal_amt" class="form-control"/>
                            <small id="amount_info">minimum amount is: <strong><?php echo get_option('qfe_minimum_usd');?> USD</strong></small>

                        </div>
                        <div class="form-group">
                            <label for="trade_months">Number of months to trade</label>
                            <select name="trade_months" id="trade_months" class="form-control" required>
                                <option value="3">3 Months</option>
                                <option value="6">6 Months</option>
                                <option value="9">9 Months</option>
                                <option value="12">12 Months</option>
                            </select>
                        </div>
                        <button id="btnDoCalculation" type="submit" class="btn btn-success pull-left" name="btnDoCalculation">Visualize Interest</button>
                    </div>

                    <div class="clearfix"></div>

                    <div class="tab">
                        <h4><span class="badge">02</span>Payment Details</h4>
                        <div class="form-group">
                            <h3>Charge Details</h3>
                            <p>Charge details are as follows:</p>
                            <div class="row">
                                <div class="col-xs-12 col-sm-6">
                                    <table id="deposit_results" class="table table-condensed">
                                        <thead>
                                            <tr>
                                                <th>Item</th>
                                                <th class="text-right">Cost</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>Amount to Deposit</td>
                                                <td id="deposit_value" class="text-right"></td>
                                            </tr>
                                            <tr>
                                                <td>Transfer Charge</td>
                                                <td id="management_charge_value" class="text-right"></td>
                                            </tr>
                                            <tr>
                                                <td>Total to Deposit</td>
                                                <td id="total_deposit_value" class="text-right"><strong></strong></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <h3>Banking Details</h3>
                            <p><strong>Bank:</strong> N/A</p>
                            <p><strong>Acc. No:</strong> N/A</p>
                            <p><strong>Acc. Name</strong>N/A</p>
                        </div>

                        <div class="form-group">
                            <label for="the_schedule">Interest payment terms(Cannot be be altered)</label>
                            <select name="the_schedule" id="the_schedule" class="form-control" required>
                                <option value="monthly">Monthly</option>
                                <option value="maturity" selected>On Maturity</option>
                            </select>
                            <small>Money will be wired to your stated bank account. Other methods coming soon</small>
                        </div>
                    </div>

                    <button id="nextBtn" class="btn btn-primary pull-right">Next</button>
                    <button id="prevBtn" class="btn pull-right">Previous</button>

                    <!-- Circles which indicates the steps of the form: -->
                    <div style="text-align:center;margin-top:40px;">
                      <span class="step"></span>
                      <span class="step"></span>
                    </div>

                </form>

The ajax submission code for the btnDoCalculation is as follows:

$('#btnDoCalculation').click(function(e){
                var formData = $('#interest_calculator').serialize();

                $.ajax({
                    type: 'POST',
                    url:'<?php echo admin_url('admin-ajax.php');?>',
                    data:formData,
                    action:'calculate_investor_interest',
                    dataType: 'json',
                    encode:true
                }).done(function(data){
                    if(data.success){   
                        console.log(data.message);
                        var results = data.calc_results;

                        var newData = results.reduce(function(collection, element){
                        var rowData = {}; //create a new empty row

                          element.reduce(function(collection, element){
                            //put the elements into the row
                            rowData[element[0]] = element[1];
                            return rowData;
                          }, rowData);

                          collection.push(rowData); //add the row to the results
                          return collection;
                        }, []);                         

                        var tr;
                        //overwrite data
                        $('#compound_interest_table tbody').empty();


                        for (var i=0; i<newData.length; i++){
                            tr = $('<tr/>');

                            //put datejs library here.....

                            tr.append('<td>' + newData[i].maturity_date + '</td>' );
                            tr.append('<td>' + newData[i].interest_rate + '</td>' );
                            tr.append('<td class="hidden-xs hidden-sm">' + newData[i].interest_earned + '</td>' );
                            tr.append('<td>' + newData[i].management_fee + '</td>' );
                            tr.append('<td class="hidden-xs hidden-sm">' + newData[i].gross_earning + '</td>' );
                            tr.append('<td class="hidden-xs hidden-sm">' + newData[i].investor_net_commission + '</td>' );
                            tr.append('<td>' + newData[i].investor_net_earning + '</td>' );


                            $('#compound_interest_table tbody').append(tr);

                        }

                    }else{
                        console.log('There is a problem ');
                    }

                }).fail(function(data){
                    console.log(data);
                });

                e.preventDefault();
            });

The ajax action hook :

//handle form submissions
function handle_investment_calc(){
    include_once('includes/controllers/investment_calculator.php');
}
add_action('wp_ajax_calculate_investor_interest', 'handle_investment_calc');

When using pure PHP, HTML and CSS, it works perfectly. The data from the form is sent, a calculation is done (via investment_calculator.php script) and the results are output to the compound_interest_table with no fuss. However, when I transfer the code to a wordpress plugin (as shown above) and try to do ajax the wordpress way, I am not getting any result output.

Where am I going wrong? The desired effect is that when I click the Do calculation button, it returns output to the table as above. The investment_calculator script is ok.

UPDATE:

After adding the 'action' parameter to the ajax code, it seems that now data is being sent to the investment calc and results are ok (in the console). The results are however not outputting to the table.

Console response Console response for Ajax Call

UPDATE 2:

Modified the ajax call like this.

$.ajax({
                    type: 'POST',
                    url:'<?php echo admin_url('admin-ajax.php');?>',
                    data:formData,
                    action:'calculate_investor_interest',
                    dataType: 'json',
                    encode:true,
                    complete:function(r){
                        console.log(r.responseText);

                        var results = r.responseText;

                        var newData = results.reduce(function(collection, element){
                        var rowData = {}; //create a new empty row

                          element.reduce(function(collection, element){
                            //put the elements into the row
                            rowData[element[0]] = element[1];
                            return rowData;
                          }, rowData);

                          collection.push(rowData); //add the row to the results
                          return collection;
                        }, []);                         

                        var tr;
                        //overwrite data
                        $('#compound_interest_table tbody').empty();


                        for (var i=0; i<newData.length; i++){
                            tr = $('<tr/>');

                            //put datejs library here.....

                            tr.append('<td>' + newData[i].maturity_date + '</td>' );
                            tr.append('<td>' + newData[i].interest_rate + '</td>' );
                            tr.append('<td class="hidden-xs hidden-sm">' + newData[i].interest_earned + '</td>' );
                            tr.append('<td>' + newData[i].management_fee + '</td>' );
                            tr.append('<td class="hidden-xs hidden-sm">' + newData[i].gross_earning + '</td>' );
                            tr.append('<td class="hidden-xs hidden-sm">' + newData[i].investor_net_commission + '</td>' );
                            tr.append('<td>' + newData[i].investor_net_earning + '</td>' );


                            $('#compound_interest_table tbody').append(tr);

                        }



                    }

                });

Data is being recieved, thanks to @ Piyush Rawat but there's now a problem with the mapreduce function ('reduce not a function'). how to I solve it

  • 2
    you need to pass action = calculate_investor_interest in your ajax data parameter – Piyush Rawat Nov 14 '17 at 11:57
  • Here is a complete reference link : wordpress.stackexchange.com/questions/184214/… – Piyush Rawat Nov 14 '17 at 11:58
  • @PiyushRawat Hi. Thanks for that. Please check the updated question, I am getting a response but it's not outputting to the table – nelson Nov 14 '17 at 12:17
  • if the AJAX answers good response, you need to debug the JavaScript construction of the output idownvotedbecau.se/nodebugging – mmm Nov 14 '17 at 12:21
  • 1
    @nelson you getting issues in fetching data? – Piyush Rawat Nov 14 '17 at 12:50
1

Modify the following code I have added action in it.

$('#btnDoCalculation').click(function(e){
        var formData = $('#interest_calculator').serialize();

        $.ajax({
            type: 'POST',
            url: '<?php echo admin_url('admin-ajax.php');?>',
            data:formData,
            dataType: 'json',
            action:calculate_investor_interest
            encode:true,                            


        }).done(function(data){
            if(data.success){   
                    console.log(data);
                    var results = data.calc_results;

                    var newData = results.reduce(function(collection, element){
                    var rowData = {}; //create a new empty row

                      element.reduce(function(collection, element){
                        //put the elements into the row
                        rowData[element[0]] = element[1];
                        return rowData;
                      }, rowData);

                      collection.push(rowData); //add the row to the results
                      return collection;
                    }, []);                         

                    var tr;
                    //overwrite data
                    $('#compound_interest_table tbody').empty();


                    for (var i=0; i<newData.length; i++){
                        tr = $('<tr/>');

                        //put datejs library here.....

                        tr.append('<td>' + newData[i].maturity_date + '</td>' );
                        tr.append('<td>' + newData[i].interest_rate + '</td>' );
                        tr.append('<td class="hidden-xs hidden-sm">' + newData[i].interest_earned + '</td>' );
                        tr.append('<td>' + newData[i].management_fee + '</td>' );
                        tr.append('<td class="hidden-xs hidden-sm">' + newData[i].gross_earning + '</td>' );
                        tr.append('<td class="hidden-xs hidden-sm">' + newData[i].investor_net_commission + '</td>' );
                        tr.append('<td>' + newData[i].investor_net_earning + '</td>' );


                        $('#compound_interest_table tbody').append(tr);

                    }
        });

        e.preventDefault();
    });
1

UPDATE 3: SOLUTION!!! in addition to adding the action parameter to the ajax function, I encoded the results in interest_calculator.php using wp_send_json() and then converted the responseText into an object (using JSON.Parse) so that I can do a Map reduce to simplify the array and output data to the table. Frustrating but I have at least learned something:

Thanks @PiyushRawat..... I owe this answer more to him/her than myself :-)

Here is the Ajax call modification:

$('#btnDoCalculation').click(function(e){
                var formData = $('#interest_calculator').serialize();

                $.ajax({
                    type: 'POST',
                    url:'<?php echo admin_url('admin-ajax.php');?>',
                    data:formData,
                    action:'calculate_investor_interest',
                    dataType: 'json',
                    encode:true,
                    complete:function(data){                    
                            var results_data = data.responseText;
                            var results = JSON.parse(results_data);

                            var newData = results.reduce(function(collection, element){
                                var rowData = {}; //create a new empty row

                                  element.reduce(function(collection, element){
                                    //put the elements into the row
                                    rowData[element[0]] = element[1];
                                    return rowData;
                                  }, rowData);

                                  collection.push(rowData); //add the row to the results
                                  return collection;
                            }, []);                         

                            var tr;
                            //overwrite data
                            $('#compound_interest_table tbody').empty();


                            for (var i=0; i<newData.length; i++){
                                tr = $('<tr/>');

                                //put datejs library here.....

                                tr.append('<td>' + newData[i].maturity_date + '</td>' );
                                tr.append('<td>' + newData[i].interest_rate + '</td>' );
                                tr.append('<td class="hidden-xs hidden-sm">' + newData[i].interest_earned + '</td>' );
                                tr.append('<td>' + newData[i].management_fee + '</td>' );
                                tr.append('<td class="hidden-xs hidden-sm">' + newData[i].gross_earning + '</td>' );
                                tr.append('<td class="hidden-xs hidden-sm">' + newData[i].investor_net_commission + '</td>' );
                                tr.append('<td>' + newData[i].investor_net_earning + '</td>' );


                                $('#compound_interest_table tbody').append(tr);

                            }

                    }
                });
                e.preventDefault();
            });

Double validation is also possible (validating with javascript as well as in the PHP script, acts as a safety net incase javascript fails)

  • 1
    i'm glad you solved it...:) – Piyush Rawat Nov 15 '17 at 3:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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