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.
ajax for insert the data

        var id = jQuery(this).attr('data-id');
        var question = jQuery('#question').val();
        var answer = jQuery('#answer').val();
        // alert(id);
            url: '<?php echo admin_url('admin-ajax.php');?>', 
            type: 'POST',
              action: 'insert_records', 
              insert_record : id,
              insert_question: question,
              insert_answer: answer
            success: function( data ){
                alert("Records are successfully insert");

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

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

            success: function( data ){
                alert("Records are successfully updated");

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-

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="">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() { 

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="">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="" />
    <link type="text/css" rel="stylesheet" href="" />
    <link type="text/css" rel="stylesheet" href="" />
    <link type="text/css" rel="stylesheet" href="" />
    <link type="text/css" rel="stylesheet" href="" />
    <link type="text/css" rel="stylesheet" href="" />
    <link type="text/css" rel="stylesheet" href=""  id="bs-default-stylesheet" />
    <link type="text/css" rel="stylesheet" href="" id="app-default-stylesheet" />
    <script type="text/javascript" src=""></script>

    <script type="text/javascript">
        jQuery(document).ready(function($) {
        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

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

                success: function(oDados, oTextStatus, oStatus) {                        
                    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>';
                error: function(oErro) {
                    alert('OCORREU UM ERRO AO PROCESSAR');

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                        <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>
                        <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-placeholder="Selecione ..." 
                                    <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>
    <div class="row">
        <div class="col-12">
            <div id="Browse">

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

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:


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 :


  path: '/form/contact-us-block'
    _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()
    return render($build)->__toString();
  1. Get the block html in your Js.

    (function ($, Drupal) {
      $(document).ready(function ($) {
          url: 'form/contact-us-block',
          success: function (response) {
          error: function (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')
              '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,

          $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!