Remove an item from $form_state in an ajax callback

I’m using this form api example: AjaxAddMore. I want to add a “remove button” for each indiviaul element, in order to remove an item but not the latest. Thouse are my changes:

...   $  form['names_fieldset'] = [       '#type' => 'fieldset',       '#title' => $  this->t('People coming to picnic'),       '#prefix' => '<div id="names-fieldset-wrapper">',       '#suffix' => '</div>',       '#attributes' => array('class'=>array('container-inline')),     ];      for ($  i = 0; $  i < $  num_names; $  i++) {        $  form['names_fieldset']['fields'][$  i] = [         '#type' => 'fieldset',         '#name' => 'id_'.$  i       ];        $  form['names_fieldset']['fields'][$  i]['ids'] = [         '#type' => 'textfield',         '#title' => $  this->t('ID'),         '#default_value' => $  i,         '#name' => 'id_'.$  i       ];        $  form['names_fieldset']['fields'][$  i]['name'] = [         '#type' => 'textfield',         '#title' => $  this->t('Name')       ];        $  form['names_fieldset']['fields'][$  i]['remove'] = [         '#type' => 'submit',         '#name' => 'remove_'.$  i,         '#value' => $  this->t('Remove this'),         '#submit' => ['::removethisCallback'],         '#ajax' => [           'callback' => '::addmoreCallback',           'wrapper' => 'names-fieldset-wrapper',         ],       ];     } .... 

It works good and I can add several records. But I can’t remove an item other than the latest one. This is my callback function where I’ve tried to unset the item I want to remove:

public function removethisCallback(array &$  form, FormStateInterface $  form_state) {     $  button_clicked = $  form_state->getTriggeringElement()['#name'];     $  id = substr($  button_clicked,7);     $  values = $  form_state->getValue(['names_fieldset']);     unset($  values[$  id]);     $  form_state->setValues(['names_fieldset'], array_values($  values));        $  name_field = $  form_state->get('num_names');     if ($  name_field > 1) {         $  remove_button = $  name_field - 1;         $  form_state->set('num_names', $  remove_button);     }        $  form_state->setRebuild(); } 

But It doesn’t work. How could I remove or update an item from $ form_state?

How to form json with nested properties via FormData() for javascript ajax request?

I need to send some data using ajax, first I get these with my form then to form me need json for ajax request. Me need this json object for request:

          {             "productId": 0,             "number": "30-E-5",             "amount": 6.09,             "primeCost": 11.4,             "manufacturer": 'HonBar',             "productTypeId": 1,             "parameters": [                 {                     "parameterId": 2,                     "value": "XXX"                 },                 {                     "parameterId": 3,                     "value": "CK45"                 },                 {                     "parameterId": 4,                     "value": "30"                 }             ]           }  

I take the data from the form, then add the missing properties for json, via method form.append(). As a result missing properties not add in “form”. My html form and post request:

document.getElementById('dataForm').addEventListener('submit', function (ev) {     let form = new FormData(document.getElementById('dataForm'));     form.append("productId", 0);     form.append("parameters"[0]['parameterId'], 2);     form.append("parameters"[1]['parameterId'], 3);     form.append("parameters"[2]['parameterId'], 4);          console.log(json);       fetch( "api/Products/AddProducts", {             method: 'POST',           headers: {               Accept: 'application/json',               'Content-Type': 'application/json',           },           body: JSON.stringify(form)           })           .then(res => res.json())           .then(response => console.log('Success:', JSON.stringify(response)))             .catch((error) => {                 console.error(error);             });          ev.preventDefault();     });
<!DOCTYPE html> <html> <head> 	<title></title> 	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head>  <body> <div class="container-fluid represent-product">         <div class="row">             <form id="dataForm" method="post">                 <div class="row p-2">                     <div class="col-2 form-group">                         <label>Name type</label>                         <select name="productTypeId" class="form-control" id="TypeProduct">                             <option value="1">AAAA</option>                             <option value="2">BBBB</option>                         </select>                     </div>                     <div class="col">                         <label>number</label>                         <input name="number" class="form-control" value=""  />                     </div>                     <div class="col">                         <label>diameter</label>                         <input name="parameters[2].value" class="form-control" value=""  />                     </div>                      <div class="col">                         <label>manufacturer</label>                         <input name="manufacturer" class="form-control" value=""  />                     </div>                     <div class="col">                         <label>Type</label>                         <input name="parameters[0].value" class="form-control" />                     </div>                     <div class="col">                         <label>Grade steel</label>                         <input name="parameters[1].value" class="form-control" />                     </div>                     <div class="col">                         <label>primeCost</label>                         <input name="primeCost" class="form-control" />                     </div>                     <div class="col">                         <label>amount</label>                         <input name="amount" class="form-control" />                     </div>                     <div class="col justify-content-center btn-add">                         <button type="submit" class="btn btn-primary  button-add">Submit</button>                     </div>                 </div>             </form>         </div>     </div>    </body> </html>

As a result i receive error : “SyntaxError: Unexpected token < in JSON at position 0”

Trying to create a new page gives an AJAX error

So I just created a page, all works correctly but when I try to put my custom block as content in the page I’m creating it shows the following error as an alert

There was an HTTP AJAX error. Result code HTTP: 500 Info. Path: /panels/ajax/editor/add-pane/panel_context%3Apage-user-admin/middle/block/user-admin/form StatusText: Service unavailable (with message) ResponseText:  

But there is no response text, no log with errors, I tried to restart the server, clear the cache and disable/enable the costum module. Also tried to change jQuery version to a lower one.

How to update multiple fields using ajax?

In content type there are three field . Each field are node reference to different content. Here I want to restrict value and create dependency on these field. For example: I have one auto complete field “Country”. On change of “Country”, select list(i.e. State) field value is updated. On change of “State”, “county” field is updated. Everything is working fine.

When I change value of “Country”, “State” value get change But “county” value hold previous value. How should I achieve this. How should I reset value of county

My code snippet is like

function module_form_alter(&$  form, &$  form_state, $  form_id) {   $  form['field_country'][LANGUAGE_NONE]['#ajax'] = array(     'callback' => '_state_list_callback',     'event'    => 'change',     'wrapper' => 'state-list',     'progress' => array('type' => 'throbber', 'message' =>  'Please wait...'), );   $  form['field_country']['#prefix'] = '<div id="state-list">';   $  form['field_country']['#suffix'] = '</div>';    $  form['field_state'][LANGUAGE_NONE]['#ajax'] = array(     'callback' => '_county_list_callback',     'event'    => 'change',     'wrapper' => 'county-list',     'progress' => array('type' => 'throbber', 'message' =>  'Please wait...'), );   $  form['field_county']['#prefix'] = '<div id="county-list">';   $  form['field_county']['#suffix'] = '</div>'; }   function _county_list_callback(&$  form, &$  form_state) {   return $  form['field_county']; }  function _state_list_callback(&$  form, &$  form_state) {   return $  form['field_state']; } 

Edit button toggles modal and load data from PHP using AJAX and JQUERY

I’ve been working on an edit/update button that will toggle a modal that looks like this:

Update/Edit Employee Modal

And I just want to ask if there’s a better code for this JS I made:

<script>  $  ('body').on('click', '.editButton',function(){     let edit = $  (this).val()     console.log("Edit this : " + edit);      $  ('#updateEmpModal').modal('toggle');       $  .ajax({         type    :   'POST',         url     :   'get.php',         data    :   {'edit' : edit},         dataType:   'json',         success: function(data){             $  ("#updateEmpForm input[name='EMAIL']")         .val(data.EMAIL);             $  ("#updateEmpForm input[name='PASSWORD']")      .val(data.PASSWORD);             $  ("#updateEmpForm input[name='RIGHTS']")        .val(data.RIGHTS);             $  ("#updateEmpForm input[name='LAST_NAME']")     .val(data.LAST_NAME);             $  ("#updateEmpForm input[name='FIRST_NAME']")    .val(data.FIRST_NAME);             $  ("#updateEmpForm input[name='MIDDLE_NAME']")   .val(data.MIDDLE_NAME);             $  ("#updateEmpForm input[name='SUFFIX']")        .val(data.SUFFIX);             $  ("#updateEmpForm input[name='GENDER']")        .val(data.GENDER);             $  ("#updateEmpForm input[name='BIRTHDATE']")     .val(data.BIRTHDATE);             $  ("#updateEmpForm input[name='BIRTHPLACE']")    .val(data.BIRTHPLACE);             $  ("#updateEmpForm input[name='CITIZENSHIP']")   .val(data.CITIZENSHIP);             $  ("#updateEmpForm input[name='RELIGION']")      .val(data.RELIGION);             $  ("#updateEmpForm input[name='ADDRESS']")       .val(data.ADDRESS);             $  ("#updateEmpForm input[name='CONTACT']")       .val(data.CONTACT);             $  ("#updateEmpForm input[name='ICE_NAME']")      .val(data.ICE_NAME);             $  ("#updateEmpForm input[name='ICE_CONTACT']")   .val(data.ICE_CONTACT);             $  ("#updateEmpForm input[name='DEPARTMENT']")    .val(data.DEPARTMENT);             $  ("#updateEmpForm input[name='POSITION']")      .val(data.POSITION);             $  ("#updateEmpForm input[name='EMP_TYPE']")      .val(data.EMP_TYPE);             $  ("#updateEmpForm input[name='edit']")          .val(data.ID);         }     }); });  </script> 

It is working, but I want to know if this is a bad practice and if there are better solutions.

I want to make ajax call to module functuion

I want on onclick event send some data to module and do some processing and get result back.

I have module name ‘custom’ and js code i have mentioned below. Url of page from where ajax call is made is 127.0.0.1/field-work

    Drupal.behaviors.custom = function (context, settings)  {     $  (document).on('click', '#clear-filter', function() {      console.log("Hello");     jQuery.ajax({             type: 'POST',             url: 'custom/field-work',             dataType: 'json',             success: function(data){             console.log(data);            },         });     }); }; 

Module code to receive ajax call have mentioned below.

function custom_menu() {     $  items['custom/field-work'] = array(     'title' => t('foo AJAX'),     'type' => MENU_CALLBACK,     'page callback' => 'details_data',     'access arguments' => array('access content'),     );     return $  items; } 

From details_data i am returning some random data. But ajax call is not working. If i am removing drupal behaviour the js part is working fine.

Please help me out.

Não consigo acessar o banco de dados via AJAX (Cordova/Phonegap)

preciso urgentemente de ajuda. Sou novato no desenvolvimento mobile e tenho tentado desenvolver um app utilizando cordova. A questão é: criei um bd MYSQL utilizando um host gratuito, um script php para acessá-lo e o hospedei em um site também. Quando acesso o mesmo pelo pc, consigo obter resultado,mas no emulador do aplicativo não recebo resposta Alguma.

Arquivo getDados.php (hospedado em um site):

    <?php     header('Access-Control-Allow-Origin: *');     header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');         //Conectando ao banco de dados         $  con = new mysqli("sql10.freemysqlhosting.net", "login_bd", "senha_bd", "nome_bd");         if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());          //Consultando banco de dados         $  qryLista = mysqli_query($  con, "SELECT * FROM usuarios");             while($  resultado = mysqli_fetch_assoc($  qryLista)){             $  vetor[] = array_map('utf8_encode', $  resultado);          }              //Passando vetor em forma de json         echo json_encode($  vetor); ?> 

Meu arquivo index.html (index do phonegap, na minha máquina):

<!DOCTYPE html> <html lang="pt-br">     <head>         <meta charset="utf-8">         <title>AJAX, JSON E PHP</title>             <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>             <script src="https://IP DA MÁQUINA LOCAL/geek_phonegap/www/ajax.js"></script>     </head>     <body>         <table border="1" width="500">             <thead>                 <tr>                     <th>ID</th>                     <th>Usuario</th>                     <th>Senha</th>                 </tr>             </thead>             <tbody id="tabela">             </tbody>         </table>         <button onclick="funcao1()">Alert</button>     </body>     <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"> </html> 

E meu arquivo ajax.js (também na minha máquina):

function funcao1() { alert("Está chamando o arquivo ajax.js!"); } $  (document).ready(function(){     $  ('#tabela').empty(); //Limpando a tabela     $  .ajax({         type:'post',        //Definimos o método HTTP usado         dataType: 'json',   //Definimos o tipo de retorno         url: 'http://uniapp.orgfree.com/getDados.php',//Definindo o arquivo onde serão buscados os dados         success: function(dados){             for(var i=0;dados.length>i;i++){                 //Adicionando registros retornados na tabela                 $  ('#tabela').append('<tr><td>'+dados[i].id+'</td><td>'+dados[i].usuario+'</td><td>'+dados[i].senha+'</td></tr>');             }         }     }); }); 

Resultado acessando diretamente, pelo pc, http://localhost/geek_phonegap/www/

Resultado acessando diretamente, pelo pc. Mas quando acesso pelo emulador, não obtenho resposta. Podem me ajudar?

Ajax Exposed filter isn’t changing URL

There must be something obvious I’m missing as it seems from other posts that Exposed Filters in views should generate URLS from its results out of the box.

I’ve got some filter with ajax enabled and they work fine, but the url doesn’t change when using the filter.

How to I achieve this and become able to link to a specific setting on the filter?

How to populate select options after ajax call on other select tag?

I want to change options of select on custom form after ajax call on other select. For example, let’s assume that I have select (let’s call it vehicles) options of vehicles like car, train, bicycle etc… if I choose car, then options on values select box changed accordingly via ajax call. Here is the pic. enter image description here

Here is the code:

public function buildForm(array $  form, FormStateInterface $  form_state) {     $  form['vehicles'] = array(             '#type' => 'select',             '#title' => t('Choose Vehicle:'),             '#options' => array('1' => 'car', '2' => 'train'),             '#required' => TRUE,             '#ajax' => [                 'callback' => '::updateValues',                 'event' => 'change',       'wrapper' => 'values-wrapper'             ],         );          $  form['values_wrapper] = [     '#type' => 'container',     '#attributes' => ['id' => 'values-wrapper'],   ];    $  selected = $  form_state->getValue('vehicles');  if (!is_null($  selected)) {      $  values_options = AjaxCall::getValues($  selected); // this gives values accordingly     $  form[values_wrapper]['values'] = array(       '#type' => 'select',       '#title' => t('Choose:'),       '#options' => $  values_options,       '#multiple' => TRUE,       '#required' => TRUE,     );    }     $  form['actions']['#type'] = 'actions';     $  form['actions']['submit'] = [         '#type' => 'submit',         '#value' => $  this->t('Add'),         '#button_type' => 'primary',     ];     $  form['#theme'] = 'system_config_form';      return $  form; } 

I did accordingly via this example http://cgit.drupalcode.org/examples/tree/form_api_example/src/Form/AjaxColorForm.php but failed to do so. What am i doing wrong?