plugin development – Data not insert and update through ajax and jQuery in admin page?

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 the data

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

magento2.3.4 – Magento2 – How to fetch the admin product form data in ajax

We are trying to show some information before saving the product via an ajax call.

In this ajax, we need to pass all the product form data.

The initial thought was to serialize the product form. But cannot see the form tag in the product add/edit area.

How can we get this product form data in javascript to pass via ajax?

ajax – Passing data-dialog-options and data-dialog-type dynamically to a tag not opening modal

I’m trying to create a dynamic way to open a modal window in drupal. The current structure work like this.

<a class="use-ajax" href="http://drupal.stackexchange.com/node/810">Testing 1 </a>

For that to work and open the modal, I had to add via inline

data-dialog-options="{&quot;width&quot;:800}" data-dialog-type="modal"

What I want is to add the data-dialog-options and data-dialog-type dynamically when the use-ajax class is added to the element.

I tried:

jQuery(document).ready(function() { 
    $('.use-ajax').attr({
        "data-dialog-options":'{&quot;width&quot;:800}', 
        "data-dialog-type":"modal"
    });
});

And even thou it added the attributes to the tag, it is not opening the modal:

<a class="use-ajax" data-dialog-options="{&quot;width&quot;:800}" data-dialog-type="modal" href="http://drupal.stackexchange.com/node/810">Testing 1 </a>```

jquery – Erro “Uncaught TypeError: Cannot read property ‘toLowerCase’ of undefined” utilizando ajax

Estou tento o erro “Uncaught TypeError: Cannot read property ‘toLowerCase’ of undefined” quando tento chamar uma função Ajax a partir do evento “onChange” de um combobox (select).
O código Ajax e a api estão funcionando corretamente. Eles são chamados também no carregamento da página.

    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/libs/mohithg-switchery/switchery.min.css" />
    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/libs/multiselect/css/multi-select.css" />
    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/libs/select2/css/select2.min.css" />
    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/libs/selectize/css/selectize.bootstrap3.css" />
    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/libs/bootstrap-select/css/bootstrap-select.min.css" />
    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.css" />
    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/css/bootstrap.min.css"  id="bs-default-stylesheet" />
    <link type="text/css" rel="stylesheet" href="http://pt.stackoverflow.com/../assets/css/app.min.css" id="app-default-stylesheet" />
    
    <script type="text/javascript" src="https://pt.stackoverflow.com/assets/libs/jquery/jquery-3.5.1.js"></script>

    <script type="text/javascript">
        //---------------------------------------
        // CARREGA O BROWSE NA ABERTURA DA PAGINA
        //---------------------------------------
        jQuery(document).ready(function($) {
            jLoadBrowse();
        });
    
        
        //-----------------------------------
        // FUNCAO PARA CARREGAMENTO DO BROWSE
        //-----------------------------------
        function jLoadBrowse() {
            var cOrderBy   = 'OS_DATA';
            var cSearch    = '';
            var cStatus    = '';
            var nPag       = 1;
            var nQtdRegPag = 0;
            var cHtml      = '';
            
            
            //--REGISTROS POR PAGINA
            nQtdRegPag = $('#cboRegPag').val();
            
            
            var oParams = JSON.stringify({
                "cWhere"  : cSearch,
                "cOrderBy": cOrderBy,
                "nPag"    : nPag,
                "nQtdReg" : nQtdRegPag
            });
            

            $.ajax({
                url: '../../api/BrwOrdensServico.php',
                method: 'POST',
                timeout: 0,
                headers: {'Content-Type': 'application/json'},
                data: oParams,                    

                success: function(oDados, oTextStatus, oStatus) {                        
                    
                    $('div').parents('#Browse').html('');
                    
                    cHtml = '';
                    for (nCountA = 0; nCountA < oDados('aDados').length; nCountA++) { 
                        cHtml += '<p>(LINHA: ' + nCountA + ') ID: ' + oDados('aDados')(nCountA)('OS_ID') + ' - ' + oDados('aDados')(nCountA)('PRJ_DESCR') + '</p>';
                    }
                    
                    $('#Browse').append(cHtml);
                
                },
                
                error: function(oErro) {
                    alert('OCORREU UM ERRO AO PROCESSAR');
                }
            });
        }            
    </script>
</head>

<body>
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="cboRegPag" class="mr-3">Resultados p/ P&aacute;gina:</label>
                                <select class="form-control" id="cboRegPag" style="width: 140px" onChange="jLoadBrowse()">
                                    <option value="12" selected="">12</option>
                                    <option value="24">24</option>
                                    <option value="60">60</option>
                                    <option value="120">120</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-4">
                                <label for="cboRegPag" class="mr-3">Filtrar Status</label>
                                <select id="cboStatus" name="cboStatus" 
                                        class="form-control select2-multiple select2-hidden-accessible" 
                                        data-toggle="select2" 
                                        multiple="" 
                                        data-placeholder="Selecione ..." 
                                        data-select2-id="4" 
                                        tabindex="-1" 
                                        aria-hidden="true">
                                    <optgroup label="Status" data-select2-id="Status">
                                        <option value="00" data-select2-id="00">Pr&eacute; Ordens de Servi&ccedil;o</option>
                                        <option value="01" data-select2-id="01">Ordens de Servi&ccedil;o em Aberto</option>
                                        <option value="02" data-select2-id="02">Ordens de Servi&ccedil;o em Aprovadas</option>
                                        <option value="03" data-select2-id="03">Ordens de Servi&ccedil;o em Rejeitadas</option>
                                        <option value="04" data-select2-id="04">Ordens de Servi&ccedil;o Salvas c/ Cr&iacute;tica</option>
                                        <option value="99" data-select2-id="99">Ordens de Servi&ccedil;o Faturadas</option>
                                    </optgroup>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <div id="Browse">
                <!--AQUI SERA MONTADO O BROWSE, VIA SCRIPT-->
            </div>
        </div>
    </div>
        

    <script type="text/javascript" src="../../assets/libs/selectize/js/standalone/selectize.min.js"></script>
    <script type="text/javascript" src="../../assets/libs/mohithg-switchery/switchery.min.js"></script>
    <script type="text/javascript" src="../../assets/libs/multiselect/js/jquery.multi-select.js"></script>
    <script type="text/javascript" src="../../assets/libs/select2/js/select2.min.js"></script>
    <script type="text/javascript" src="../../assets/libs/jquery-mockjax/jquery.mockjax.min.js"></script>
    <script type="text/javascript" src="../../assets/libs/devbridge-autocomplete/jquery.autocomplete.min.js"></script>
    <script type="text/javascript" src="../../assets/libs/bootstrap-select/js/bootstrap-select.min.js"></script>
    <script type="text/javascript" src="../../assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.js"></script>
    <script type="text/javascript" src="../../assets/libs/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
    <script type="text/javascript" src="../../assets/js/pages/form-advanced.init.js"></script>
    
</body>

ajax – How can webform performance be improved on low internet connection?

I built a site with Drupal 9 and webform.
The form consists of three pages and contains a few computed fields.
On the first page are mandatory fields.

When on a machine with a normal/fast internet connection, everything is fine.
When on a machine (smartphone) with a slow internet connection (or on „Low-end mobile“ in chromium’s developer tools), I can enter all information on the first page, press next, it loads the second page and jumps back to the first one, claiming that the mandatory fields were empty.

Is there something that should be cached and that I missed so far? Do I have to manipulate some timeouts (where are they, I didn’t find them)?

8 – How to add an Ajax call to an element that already has callback set?

I want to add an ajax callback to a form element inside a form_alter, but it already has 2 callbacks assigned to it.

When I review:

$form['payment_information']['payment_method']['#ajax']['callback']

it has 2 callbacks already assigned to it.

If I do this:

$form['payment_information']['payment_method']['#ajax'] = [
  'callback' => '_sia_general_get_fee',
  'event' => 'click',
];

My callback is hit on click; but of course, the other 2 callbacks are wiped out and do not work.

If I add something like this:

$form['payment_information']['payment_method']['#ajax']['callback'][] = '_sia_general_get_fee';

then the other callbacks are called; but mine is not – I suspect since I no longer of an event defined.

I am also not sure how the other ajax calls work when they have no events defined for them.

Is there any way to do this?

8 – How to load a webform via ajax inside custom JS?

Try the following steps :

  1. Create follow this how to create contact form block
  2. Create route for example form/contact-us-block :

custom_module.routing.yml

custom_module.get_contact_form_block:
  path: '/form/contact-us-block'
  defaults:
    _controller: 'Drupalcustom_moduleControllerTutorialController::getContactFormBlock'

getContactFormBlock Action in your controller

public function getContactFormBlock() {
    //- Set your block id here
    $bid = 4;
    $block = Drupalblock_contentEntityBlockContent::load($bid);
    $build = Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
      ->view($block);
    return render($build)->__toString();
  }
  1. Get the block html in your Js.

    (function ($, Drupal) {
      $(document).ready(function ($) {
        $.ajax({
          url: 'form/contact-us-block',
          success: function (response) {
            console.log(response);
          },
          error: function (error) {
            console.log(error);
          }
        });
      });
    })(jQuery, Drupal);

ajax – How to upload image to folder using php

I’m having trouble figuring out how to upload images. I created a module we’ll call it “my_module”. Inside there, I have a few folders: “templates, src, js, img”. I’m trying to save images in my “img” folder, but I can’t seem to figure this out.

I added my php code below.

$db = Database::getConnection();
    $current_loggedin_user_ID = Drupal::currentUser()->id();

    $time = time();

    $valid_extensions = array('jpeg', 'jpg', 'png'); // valid extensions
    $upload_destination = '../../img/';

    /** Create php variables from ajax request **/
    $poster_company_name = $_POST('postCompanyName');
    $poster_company_message = $_POST('postMessage');

    $poster_image = $_FILES('postImage')('name');
    $poster_image_size = $_FILES('postImage')('size');
    $poster_image_temp = $_FILES('postImage')('tmp_name');

    //$errorimg = $_FILES("postImage")("error"); //stores any error code resulting from the transfer


    $ext = strtolower(pathinfo($poster_image, PATHINFO_EXTENSION));

    // can upload same image using rand function
    $final_image = rand(1000,1000000).$poster_image;
    $upload_destination = $upload_destination.strtolower($final_image);

    if($poster_image_size <= 1000000) {

      if(in_array($ext, $valid_extensions)){

        if(move_uploaded_file($poster_image_temp, $upload_destination)){

          $insert_update = $db->upsert('dr_user_posts')
            ->fields((
              'poster_id' => $current_loggedin_user_ID,
              'posting_to_id' => $postingToId,
              'company_name' => $poster_company_name,
              'post_image' => $final_image,
              'post_message' => $poster_company_message,
              'created_at' => $time,
            ));

          $insert_update->key('follower_id');
          $result = $insert_update->execute();

          return new AjaxResponse(("result" => "success", "msg" => "Success!"));

        } else {
          return new AjaxResponse(("result" => "error", "msg" => "Something went wrong with moving the file to the server."));
        }

      } else {
        return new AjaxResponse(("result" => "error", "msg" => "Invalid file type."));
      }

    } else {
      return new AjaxResponse(("result" => "error", "msg" => "Can only upload 1MB of image file."));
    }

As you can see, I have a variable called $upload_destination. This is the part where I am having trouble because I can’t figure out how to move the upload image to the “img” folder.

Not sure if the “../../img/” is necessary? Obviously, the above php code is in a Controller folder inside the “src” folder. Path issues always confuse me.

Another note that should be considered is that I get an error when I try to upload the image “Something went wrong with moving the file to the server.” If you look closely, you’ll know that this is coming from the if statement where the “move_uploaded_file” function is at.

Honestly, not sure what I’m doing wrong.

I will eventually move this to a live server so I would also appreciate the solution working for both local and live server.

For Drupal I am using the Acquia Dev Desktop 2 if it helps. Also, this info is coming from a twig template using bootstrap to setup the form and using jQuery ajax to make the request to the controller. But I feel that the issue is back-end (Controller).

I appreciate any help. Thank you!