Update ajax data after dropdown change

Update ajax data after dropdown change

mikepfly2mikepfly2 Posts: 17Questions: 7Answers: 0

I've read through a ton of forum topics regarding this issue but not having much luck. I'm sure it's something easy but can't figure it out.
Basically I want the value of a dropdown to be sent to the editor to save to my DB. It works fine when I hard code it but I can't get the dropdown to update the ajax data variable.

JS:

`$(document).ready( function () {
       
        var editor;
        divtype = $('#insptype_division').val(); // Initial dropdown value
         
        editor = new $.fn.dataTable.Editor( {
                ajax: {url: '../../command/datatables.php',
                        type: 'POST',
                        data: {'action':'insptypes', 'div':divtype}
                    },
        table: "#tblinspectiontypes",
        fields: [ {
                            label: "Description",
                            name: "description"
            }   ,
{
                            label: "Div_ID",
                            name: "insp_divisions_id"
            }                          
        ]
    } );

        var inspectiontypestable = $('#tblinspectiontypes').DataTable( {
            dom: "Bfrt",
            ajax: {url: '../../command/datatables.php',
                        type: 'POST',
                        data: {'a':'insptypes'}
                    },
            columns: [
                    { data: "description" },
                    { data: "insp_divisions_id" }                        
            ],
            select: true,
            responsive: true,
            info:     false,
            paging:   false,
            order: [[ 0, "asc" ]],
            buttons: [
                    { extend: "create", editor: editor },
                    { extend: "editSingle",   editor: editor },
                    { extend: "remove", editor: editor }
            ]
    } );   

        $('#insptype_division').change(function(){
            divtype = $('#insptype_division').val();
            inspectiontypestable.column(1).search($(this).val()).draw();
        });
    } ); 
`

When a user selects from the "insptype_division" dropdown it successfully filters the table but when I add or edit an item I want the selected dropdown value to be sent to PHP with the edit. Instead it just send the initial value from when the page loads.

my PHP:

`<?php
session_start();
// DataTables PHP library
include( "../external/Editor-PHP-1.7.4/php/DataTables.php" );
$pid = $_SESSION['project']['pid'];
$division_id='0';
if(!empty($_POST['div'])){$division_id = $_POST['div'];}

global $obj_db;

// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Options,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate,
    DataTables\Editor\ValidateOptions;

if(isset($_POST['a'])) {
    switch($_POST['a']) {
    case 'divisions':
        // Build our Editor instance and process the data coming from _POST
        Editor::inst( $db, 'insp_divisions' )
            ->fields(
                Field::inst( 'project_id' )
                ->get( false )
                ->setValue( $pid ),
                Field::inst( 'description' )
                    ->validator( Validate::notEmpty( ValidateOptions::inst()
                        ->message( 'A description is required' )    
                    ) )  
            )
            ->where('project_id',$pid)
            ->process( $_POST )
            ->json();
        break;

    case 'insptypes':
        // Build our Editor instance and process the data coming from _POST
        
        Editor::inst( $db, 'insp_types' )
        ->fields(
            Field::inst( 'project_id' )
            ->get( false )
            ->setValue( $pid ),
            Field::inst( 'insp_divisions_id' )
            ->setValue( $division_id ),
            Field::inst( 'description' )
                ->validator( Validate::notEmpty( ValidateOptions::inst()
                    ->message( 'A description is required' )    
                ) )  
        )
        ->where('project_id',$pid) 
        ->process( $_POST )
        ->json();
        break;
    default:
        die('no such action available');
   }
} else {exit;}`

It's got to be something simple. Thanks so much in advance!

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    You should probably use the Editor's "select" field type.
    https://editor.datatables.net/reference/field/select

  • mikepfly2mikepfly2 Posts: 17Questions: 7Answers: 0

    Not really sure if that helps. The select box has Division 1, Division 2, Division 3 and is separate and above the data table. When they select the division the table only shows the inspection types for that division. If the user add or edits a new inspection type I want the key from the select box to be sent to the database. So the value of the drop down selector needs to be sent to the editor php.

  • allanallan Posts: 62,994Questions: 1Answers: 10,368 Site admin
    Answer ✓

    The issue here is that this code:

                    ajax: {url: '../../command/datatables.php',
                            type: 'POST',
                            data: {'action':'insptypes', 'div':divtype}
                        },
    

    is evaluated when the Editor is initialised. It cannot change the value of divtype after the fact (since it is a scalar value, and not passed by reference).

    The way to do what you are looking for is to use ajax.data as a function:

    ajax: {
      ...,
      data: function ( d ) {
        d.action = insptypes;
        d.div = $('#insptype_division').val();
      }
    }
    

    Note that I've got it evaluating the select element's value on each call of that function. Editor will call the function when the submit is triggered, allowing it to get the current value at that time.

    The preSubmit event can also be used to modify the data submitted to the server and can provide a little more context - for example submitting the select's value on delete might not be so useful.

    Regards,
    Allan

  • mikepfly2mikepfly2 Posts: 17Questions: 7Answers: 0

    That is great. Thank you.
    (small typo: add quotes around d.action = 'insptypes')

This discussion has been closed.