skip to Main Content

I made custom plugin and done crud operation, display all data in admin page, used ajax and jquery. Data successfully deleted but not inserted or updated. Data successfully pass through ajax but not inserted. Also What I saw if input block is empty and I put some data and updated it. It got first row data.
Error- https://prnt.sc/wnzqjr
ajax for insert data

<tr>
                     <td><?php echo $q ?></td>

                     <td>
                        <input type="text" name="question" class="question"  value="<?php echo $print->question ?>" ></td>
                     <td>
                     <input type="text" name="answer" class="answer"  value="<?php echo $print->answer ?>" > </td>

                     <td>
                        <input type="button" value="Insert" id="insert" data-id = "<?php echo $print->id ?>" name="insert" class="ins_btn">
                    </td>

                    <td>
                        <input type="button" value="Update" id="update" data-id = "<?php echo $print->id ?>" name="update" class="upd_btn">
                    </td>

                     <td>
                        <input type="button" value="Delete" id="delete" data-id = "<?php echo $print->id ?>" name="delete" class="del_btn">
                    </td>
                </tr>
jQuery('.ins_btn').click(function(){
        var id = jQuery(this).attr('data-id');
        var question = jQuery('#question').val();
        var answer = jQuery('#answer').val();
        // alert(id);
        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php');?>', 
            type: 'POST',
            data:{ 
              action: 'insert_records', 
              insert_record : id,
              insert_question: question,
              insert_answer: answer
            },
            success: function( data ){
                alert("Records are successfully insert");
                location.reload();
            }
         });
    });

insert query

 function insert_records(){
  global $wpdb;
 $id = $_POST['insert_record'];
 $question = $_POST['insert_question'];
 $answer = $_POST['insert_answer'];


  $db_inserted = $wpdb->insert( $wpdb->prefix.'faqq', 
        array( 'ID' => $id, 
               'question' => $question, 
               'answer' => $answer) 
    );
}
add_action( "wp_ajax_insert_records", "insert_records" );
add_action( "wp_ajax_nopriv_insert_records", "insert_records" );

ajax for update the data

jQuery('.upd_btn').click(function(){
        var id = jQuery(this).attr('data-id');
        var question = jQuery('#question').val();
        var answer = jQuery('#answer').val();
        alert(question);
        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php');?>', 
            type: 'POST',
            data:{ 
              action: 'update_records', 
              update_record : id,
              update_question : question,
              update_answer : answer

            },
            success: function( data ){
                alert("Records are successfully updated");
                location.reload();
            }
         });
    });

update query

function update_records(){
  global $wpdb;
  // $table_name = $wpdb->prefix.'faqq';
  $id = $_POST['update_record'];
  $question = $_POST['update_question'];
  $answer = $_POST['update_answer'];
  $db_updated = $wpdb->update( $wpdb->prefix.'faqq', 
        array('question'    => $question,
              'answer'   => $answer, array( 'ID' => $id ) )
          ); 
}

Here are some errors. 1)Getting error when update the data through ajax- https://prnt.sc/wnymkx, https://prnt.sc/wnyos5, https://prnt.sc/wnyuhk

3

Answers


  1. Chosen as BEST ANSWER

    Don't need id field for inserting data, So I remove it. I use classes for question and answer fields.

    jQuery('.ins_btn').click(function(){
            var question = jQuery(this).closest('tr').find('.question').val();
            var answer = jQuery(this).closest('tr').find('.answer').val();
            // alert(question);
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php');?>',  
                type: 'POST',
                data:{ 
                  action          : 'insert_records', 
                  insert_question : question,
                  insert_answer   : answer
                },
                success: function( data ){
                    location.reload();
                }
             });
        });
    
    

    Same as for update function, only add reference id field. Because for updating the data, reference Id is important.

    jQuery('.upd_btn').click(function(){
            var id = jQuery(this).attr('data-id');
            var question = jQuery(this).closest('tr').find('.question').val();
            var answer = jQuery(this).closest('tr').find('.answer').val();
            
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php');?>', 
                type: 'POST',
                data:{ 
                  action: 'update_records', 
                  update_record : id,
                  update_question : question,
                  update_answer : answer
    
                },
                success: function( data ){
                    location.reload();
                }
             });
        });
    

    And in update query, I added parenthesis at wrong position.

    function update_records(){
      global $wpdb;
       // echo "<pre>"; print_r($_POST);
       // die();    
      // $table_name = $wpdb->prefix.'faqq';
      $id = $_POST['update_record'];
      $question = $_POST['update_question'];
      $answer = $_POST['update_answer'];
    
      $db_updated = $wpdb->update( $wpdb->prefix.'faqq', 
            array('question'    => $question,
                  'answer'   => $answer
              ),
                   array( 'ID' => $id ) 
              );
    
      // $wpdb->query($wpdb->prepare("UPDATE $table_name SET question = '$question', answer = '$answer' WHERE id = $id"));
    }
    add_action( "wp_ajax_update_records", "update_records" );   //update_records is action
    add_action( "wp_ajax_nopriv_update_records", "update_records" );
    

  2. The problem might be that your loop which is creating the list for displaying on admin page is causing multiple elements to have the same id, when id attributes must be unique within the DOM. To fix this use common classes on the elements within the loop, then DOM traversal to find them when the button is clicked.

    Change the code block for display like this:

    $mysql = Database::DBCon()->prepare('SELECT * FROM table_name');
    $mysql->execute();
    while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC)){
        $html = '<tr>
        <td><input type="text" value="'. $fetch['question'] .'" class="question"></td>
        <td><input type="text" value="'. $fetch['answer'] .'" class="answer"></td>
        <td>
            <button type="button" class="btn btn-danger insert-btn" data-id="'. $fetch['ID'] .'">Insert</button>
            <button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
        </tr>';
        //echo $html;
    }
    

    Then change implementation of function to something like this:

    $(document).ready(function() {
        $(document).on('click', '.update-btn', function() {
            var $row = $(this).closest('tr');
            var id = $(this).data('id');
            var question= $row.find('.question').val();
            var answer = $row.find('.answer').val();
    
            // ajax request here...
       });
    })
    
    Login or Signup to reply.
  3. i think you forgot to enqueue your script file where jQuery is written. that’s it is showing script called incorrectly
    you suppose to register your script by admin_enque_script hook

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search