1

I have been working at this for weeks without success. I've figured out problem after problem with the code, but none of the corrections seem to fix my core problem. The form doesn't insert anything into the database and I don't know why. all my data's passed in the ajax call but it doesn't insert in the data in the database.

I'm new to ajax and to WordPress plugins so I might be missing something obvious. Please help me know where I am going wrong. Thanks in advance.

My widget form plugin code

public function widget( $args, $instance ) {


    if ( ! isset( $args['widget_id'] ) ) {

        $args['widget_id'] = $this->id;
        
        }

        $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Contact' );

        $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
        
        
         ?>
    <?php
        if ( $title ) {
           echo '<h2 class="widget-title">'.$args['before_title'] . $title . $args['after_title'].'</h2>';
          
        }
       ?>

    <form  class="form-group" method="POST" id="form" action="">
        <label>Name</label><br>
        <input class="form-control" type="text" id="name" name="name" ><br>
        <label>Mobile</label><br>
        <input type="text" class="form-control" id="mobileno" name="mobileno" required><br>
        <label>Email</label><br>
        <input class="form-control"  type="email" id="email" name="email" ><br>
        <label>Message</label><br>
        <textarea class="form-control" id="message" name="message"  maxlength="10" onKeyPress="lengthcheck()"></textarea><br><br>
        <button  class="btn btn-warning" type="submit" id="submit">Send Message</button>
    </form>
<?php } 


This is my enqueue methods:

add_action( 'wp_enqueue_scripts', 'vs_con_enqueue_scripts' );

function vs_con_enqueue_scripts(){
 wp_register_script( 
   'ajaxHandle', 
   plugins_url('valid.js', __FILE__), 
   array('jquery'), 
   false, 
   true 
 );
 wp_enqueue_script( 'ajaxHandle');
 wp_localize_script( 
   'ajaxHandle', 
   'ajax_object', 
   array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) 
 );
 wp_enqueue_style( 'bootstrap-style','https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );

}


add_action( "wp_ajax_contact", "vs_contact_form" );
add_action( "wp_ajax_nopriv_contact", "vs_contact_form" );


function vs_contact_form(){
 
   global $wpdb;

       $name = $_POST["name"];
       $email = $_POST["email"];
       $mobileno = $_POST["mobileno"];
       $message = $_POST["message"];
      
       
       $tablename = $wpdb->prefix.'contactdetails';
       //method 1 (Two Methods Works Prefect) Perform 1 or 2 whatever you want
// $insert_row = $wpdb->insert( 
       //   $tablename, 
       //     array( 
       //         'name' => $name, 
       //         'email' => $email, 
       //         'mobileno' => $mobileno,
       //         'message' => $message 
       //     ),
       //     array(
       //       '%s',
       //       '%s',
       //       '%s',
       //       '%s'
       //     )
       //   );
           // if row inserted in table
       $qry="INSERT INTO $tablename (name,email,mobileno,message) VALUES ('$name','$email','$mobileno','$message')"; 
       $insert_row=$wpdb->query($qry);  //method 2

        if($insert_row)
        {
           echo json_encode(array('res'=>true, 'message'=>__('Message Sent Successfully')));
       }else{
          echo json_encode(array('res'=>false, 'message'=>__('Something went wrong. Please try again later.')));
       }
       
       wp_die();
}

Here this is my form submit jquery ajax call function

valid.js

jQuery(document).ready(function($){
    $('form#form').on('submit', function(e){
       e.preventDefault();
       var name =jQuery('#name').val();
       var email = jQuery('#email').val();
       var mobileno = jQuery('#mobileno').val();
       var message = jQuery('#message').val();
      
       var text;
       if(name.length < 5){
         text = "Please Enter valid Name";
        alert(text);
         return false;
       }
       if(isNaN(mobileno) || mobileno.length != 10){
         text = "Please Enter valid mobileno Number";
         alert(text);
         return false;
       }
       if(email.indexOf("@") == -1 || email.length < 6){
         text = "Please Enter valid Email";
         alert(text);
         return false;
       }
      var data = {
       action:'contact',
       name: name,
       email: email,
       mobileno: mobileno,
       message: message
      }; 
       $.ajax({
          type:"POST",
          dataType:'json',
          url: ajax_object.ajaxurl,
          data :data,
          encode:true,
         success: function(data){
            if (data.res == true){
                alert(data.message);    // success message
            }
            else{
              alert(data.message); 
            }
         }  
        });
         $('#form')[0].reset();
       });

   
      });

please help me to find out where I am wrong?

8
  • What are you getting in ajax response? Also make sure your datatype of custom table's columns are correct.
    – Bunty
    Commented Dec 15, 2020 at 9:17
  • @bunty i was getting an ajax response Something went wrong. Please try again later and I got an error in my debug.log wpdb::prepare was called <strong>incorrectly</strong>. The query does not contain the correct number of placeholders (2) for the number of arguments passed (5)
    – dhanar98
    Commented Dec 15, 2020 at 9:40
  • Code seems correct to me. Not sure why it is failing to insert data to the table. You can do var_dump($insert_row) after insert query and check what error it shows. My feeling is either table does not exist( giving possibility ) OR all the columns are set to not null and you have null data in your request OR data types are not proper.
    – Bunty
    Commented Dec 15, 2020 at 9:55
  • @Bunty I got this error wpdb::prepare was called <strong>incorrectly</strong>. The query does not contain the correct number of placeholders (2) for the number of arguments passed (5) in the data section i pass my form data and action in my php function i only got 4 data how i pass action i paramater
    – dhanar98
    Commented Dec 15, 2020 at 11:14
  • Can you sdd SQL for creating the custom table? So that I can check that by m end.
    – Bunty
    Commented Dec 15, 2020 at 12:36

1 Answer 1

0

Thanks for giving the table schema.

There are few problems in the code and table as well.

Issue 1

In the "vs_contact_form" function, there is a wrong parameter. Change below line

$messsage = $_POST["messsage"];

To

$messsage = $_POST["message"];

Issue 2

In same function change below array. ( Array key should match the table column name )

array( 
    'name' => $name, 
    'email' => $email, 
    'mobileno' => $mobileno,
    'messsage' => $messsage 
)

To

array( 
    'name' => $name, 
    'email' => $email, 
    'mobileno' => $mobileno,
    'message' => $messsage 
)

Issue 3

It's issue with table. Your table doesn't have proper datatype length Please delete your table and create new table using following query

CREATE TABLE `wp_contactdetails` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `mobileno` varchar(255) NOT NULL,
  `message` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


ALTER TABLE `wp_contactdetails` ADD PRIMARY KEY (`id`);


ALTER TABLE `wp_contactdetails` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; COMMIT;
6
  • I change all issues again my data's not inserted
    – dhanar98
    Commented Dec 16, 2020 at 5:07
  • Strange. I tried again from scratch and I am not having the issue. Can you tell me now what error you are getting by adding var_dump($insert_row) again.
    – Bunty
    Commented Dec 16, 2020 at 6:50
  • Safer side, sharing the whole function "vs_contact_form" to check if something still missing from your side codeshare.io/5g7QpY
    – Bunty
    Commented Dec 16, 2020 at 7:08
  • 1
    Thanks for helping us. Now it's work. I made some changes in insertion
    – dhanar98
    Commented Dec 16, 2020 at 8:08
  • thanks for helping me . I made changes in my queries. Now I update my working code in the coding section
    – dhanar98
    Commented Dec 16, 2020 at 8:16

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.