1

I'm quite new to WordpPress and web development as in general. Trying to save data to wordpress DB from the form I have on the page via ajax call.

This is the form I have:

             <form type="post" action="" id="MSRPForm">
                    <div class="py-3 my-0 form-group row border-top border-bottom align-items-center">
                        <label for="inputEmail" class="col-sm-4 col-form-label" >Email</label>
                        <div class="col-sm-8">
                            <input name="Email" type="text" class="form-control-plaintext" id="inputEmail"
                            placeholder="email@example.com">
                        </div>
                    </div>
                    <div class="py-3 my-0 form-group row border-top border-bottom align-items-center">
                        <label for="inputZipCode" class="col-sm-4 col-form-label" >Zip Code</label>
                        <div class="col-sm-8">
                            <input name="ZipCode" type="text" class="form-control" id="inputZipCode" placeholder="Enter your Zip Code">
                        </div>
                    </div>

                    <div class="py-3 my-0 form-group row border-top border-bottom align-items-center">
                        <label for="inputMSRP" class="col-sm-6 col-form-label font-weight-bold" >MSRP<br><small>Manufacturer's Suggested Retail Price</small></label>
                        
                        <div class="col-sm-6">
                        <input name="MSRP" type="text" min="1000" class="form-control text-right" id="inputMSRP" placeholder="Enter the MSRP">
                        </div>
                    </div>
                    <button id="msrp-btn" type="button" class="btn btn-primary my-2">Calculate</button>
                </form>

This is an AJAX. It is wrapped into jQuery function, so it works for sure:

 let ajaxurl = "wp-admin/admin-ajax.php";
$(document).ready(function(){
    $("#msrp-btn").click(function(e) {
        e.preventDefault();       
        let email = $('#inputEmail').val();
        let zipCode = $('#inputZipCode').val();
        let msrp = $('#inputMSRP').val();

        let info = {
            'action': 'addMSRP',
            'email': email,
            'zipCode' : zipCode,
            'msrp' : msrp
        };
            
        
        jQuery.ajax({
            type: "POST",
            url: ajaxurl, 
            data: info,
            beforeSend: function() {            
                $('#myModal').modal('show'); 
                // console.log( info);
            },
            success: function(res){
                console.log(res);
            },
            error: function(res){
                console.log(res)
            },
        }); 

    });  
});

Finally this is a code I have in my functions.php

    add_action('wp_ajax_addMSRP', 'addMSRP');
add_action('wp_ajax_nopriv_addMSRP', 'addMSRP');

function addMSRP() {

    global $wpdb;

    $email = $_POST['Email'];
    $zipCode = $_POST['ZipCode'];
    $MSRP = $_POST['MSRP'];
    
    
    if ( $wpdb->insert( 'msrp_info', array(
        'email' => $email,
        'zipCode' => $zipCode,
        'MSRP' => $MSRP
    ) ) === false ) {
        wp_die('Database Insertion failed'); 
    } else {
        echo "Info successfully added, row ID is ".$wpdb->insert_id;
    }
    exit();
}

Looks like code is working as data get passed to the server, but it is not getting saved to the DB. Would appreciate if somebody can tell what I'm doing wrong. Thank you.

  • What is the error you are getting? Did you turn on WP DEBUG in wp_config.php? Also please try adding `wp_die();` aftter this line: `echo "Info successfully added, row ID is ".$wpdb->insert_id;` – Ozgur Sar Nov 25 '20 at 18:21
  • @ozgur I'm getting "Database Insertion failed" in the console. Nope I didn't. Will do so. Thanks. – Michael Kashapov Nov 25 '20 at 18:24
  • there is no need to enable WP DEBUG if you are already getting the error message. – Ozgur Sar Nov 25 '20 at 18:25
  • You can try to add `echo $wpdb->show_errors();` before the `wp_die('Database Insertion failed');` line to display the DB errors. – Ozgur Sar Nov 25 '20 at 18:29
  • 1
    I noticed that your are not using the same case letters. I'm not sure but it may be the source of your problem. Maybe your DB doesn't accept null values. For example you send all lowercase `msrp` from ajax but you are trying to read it with `$MSRP = $_POST['MSRP'];` which is all uppercase. – Ozgur Sar Nov 25 '20 at 18:30
  • This is an error I'm getting now after I turned on WP DEBUG `

    WordPress database error: [Table 'dolphin.msrp_info' doesn't exist]
    SHOW FULL COLUMNS FROM "msrp_info"

    1Database Insertion failed` Looks that table doesn't exist and this is why it's failed. Am I right?
    – Michael Kashapov Nov 25 '20 at 18:36
  • So it says you don't have `msrp_info` table in your DB. – Ozgur Sar Nov 25 '20 at 18:39
  • @ozur yeah, so I guess I have to figure that one out. Thank you! – Michael Kashapov Nov 25 '20 at 18:40

1 Answers1

0

There are a few issues I can see, namely, you are not passing in the correct variable to the $_POST. You also need to specify the name of the database table. Try the following code for database inserting.

add_action('wp_ajax_addMSRP', 'addMSRP');
add_action('wp_ajax_nopriv_addMSRP', 'addMSRP');  

function addMSRP(){
    
        global $wpdb;
        //output will be your debug tool - if it posts it works.
        $output = ['status' => 1];
        $email = sanitize_text_field($_POST["email"]);
        $zipcode = sanitize_text_field($_POST["zipCode"]);
        $MSRP = sanitize_text_field($_POST["msrp"]);
    
        $table = $wpdb->prefix . 'enteryourdatabasename';
        //This below code has to match exactly what the database reads.
        //If 'msrp' in the database the table is 'MsRp' - than replace it as spelled below. 
        $data = array(
            'email' => $email,
            'zipcode' => $zipcode,
            'msrp' => $MSRP,
            
        );
    
        $wpdb->insert($table, $data);
    //using wp_send_json to send that response and kill script.
        $output['status'] = 2;
        wp_send_json($output);
    
    
    
    }
Chris Norman
  • 111
  • 1
  • 8