1

I'm trying to make booking - plugin with form on wordpress-admin site, where I can add new event in calender (made with JavaScript). I have to submit form with all data and insert data to MySQL Database.

My ajax.js file:

function ajaxSubmit(e){
var nazwa_szkolenia = document.getElementById("nazwa_szkolenia").value;
var Data_szkolenia = document.getElementById("Data_szkolenia").value;
var Godzina = document.getElementById("Godzina").value;
var Max_pacjent = document.getElementById("Max_pacjent").value;

// Returns successful data submission message when the entered information is stored in database.
var dataString = 'nazwa_szkolenia1=' + nazwa_szkolenia + '&Data_szkolenia1=' + Data_szkolenia + '&Godzina1=' + Godzina + '&Max_pacjent1=' + Max_pacjent;
if (nazwa_szkolenia == '' || Data_szkolenia == '' || Max_pacjent == '') {
alert("fill all fields");
} else {
    // prevent the default action.
    e.preventDefault();

    var myform= jQuery(this).serialize();

    jQuery.ajax({
        type:"POST",
        // Get the admin ajax url which we have passed through wp_localize_script().
        url: ajax_object.ajax_url,
        action: "submitAjaxForm",
        data: dataString,
        error: function(jqXHR, textStatus, errorThrown){                                        
        console.error("The following error occured: " + textStatus, errorThrown);                                                       
    },
        success:function(data){
            alert("process ok");
        }
    });
}
return false;
}

arcode-functions.php:

<?php
add_action('init', 'registerFormAction');

    function registerFormAction(){
        add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback');
        add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback');

    }

    function submitAjaxForm_callback(){
    global $wpdb;


$nazwa_szkolenia2 = $_POST['nazwa_szkolenia1'];
$Data_szkolenia2 = $_POST['Data_szkolenia1'];
$Godzina2 = $_POST['Godzina1'];
$Max_pacjent2 = $_POST['Max_pacjent1'];


    $wpdb->insert( $wpdb->modul_terminarz, array( 'proba' => $nazwa_szkolenia2, 'id' => '10', 'data_szkolenia' => $Data_szkolenia2, 'typ_szkolenia' => '1', 'ile_miejsc' => $Max_pacjent2, 'pelne' => '1', 'Ile_miejsc_akt' => '4' ) );


    wp_die();
}

?>

I've added admin-ajax.php with wp_localize_script function. The form button is made with JavaScript:

var Input_Form_Send = document.createElement('input');
     Input_Form_Send.value = 'Utwórz';
     Input_Form_Send.type = 'submit';
     Input_Form_Send.className = 'input-form-send'; 
Input_Form_Send.onclick = ajaxSubmit;

When I fill all fields from form, click on the button, then comes alert "process ok", but on the Database comes nothing new... nazwa_szkolenia, Data_szkolenia, Godzina, Max_pacjent -those are the names of the form fields.

Maybe you know what I've made wrong?

0

Why do you serialize the data with jQuery but don't pass that variable via AJAX? My guess is the data needs to be in array from, not a string of data like a URL.

You could verify if the data gets to the AJAX callback function by returning a data value and displaying it in the alert() in the success function.

What works for me is to put the data in a relational array and use GET instead of post.

var dataString = []; dataString['nazwa_szkolenia1'] = nazwa_szkolenia; // etc.

Hope this helps.

  • I don't serialize data as you see - code was before copierd from another function. I've made like you said - it didn't work...I've add also return for data in alert for succes, but it gives "0"... where it should be string success or error... – Adam J. Jun 16 '17 at 6:21
  • Just before wp_die() try echoing a static string, like echo "AJAX is working"; This debug should confirm that AJAX is working. If you're still getting 0, then I would guess you're using the wrong hook to register the submitAjaxForm action. – scott Jun 16 '17 at 18:02
  • The next debugging step is to make sure the data is being sent to the database. In my system, I have to create the SQL query, but it's easy to debug: I just echo the query to check for syntax mistakes. I do note that you always set the id of the record to 10. If you need it to create a new record, shouldn't that value auto-increment? – scott Jun 16 '17 at 18:04
0

I've cleaned everything a little bit. Now it looks like that:

ajax.js

function ajaxSubmit(e){
var nazwa_szkolenia = document.getElementById("nazwa_szkolenia").value;
var Data_szkolenia = document.getElementById("Data_szkolenia").value;
var Godzina = document.getElementById("Godzina").value;
var Max_pacjent = document.getElementById("Max_pacjent").value;

var dataString = [];
dataString['nazwa_szkolenia1'] = nazwa_szkolenia;
dataString['Data_szkolenia1'] = Data_szkolenia;
dataString['Godzina1'] = Godzina;
dataString['Max_pacjent1'] = Max_pacjent;

if (nazwa_szkolenia == '' || Data_szkolenia == '' || Godzina == '' || Max_pacjent == '') {
alert("Wypełnij wszystkie pola");
} else {
    // prevent the default action.
    e.preventDefault();

    //var myform= jQuery(this).serialize();

    jQuery.ajax({
        type:"GET",
        // Get the admin ajax url which we have passed through wp_localize_script().
        url: ajax_object.ajax_url,
        action: "submitAjaxForm",
        data: dataString,
        error: function(jqXHR, textStatus, errorThrown){                                        
        console.error("The following error occured: " + textStatus, errorThrown);                                                       
    },
        success:function(data){
console.log(dataString);
        }
    });
}
return false;
}

arcode-functions.php:

<?php

function registerFormAction(){
    add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback');
    add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback');
}

function submitAjaxForm_callback(){
   global $wpdb;

    $nazwa_szkolenia2 = $_GET['nazwa_szkolenia1'];
    $Data_szkolenia2 = $_GET['Data_szkolenia1'];
    $Godzina_szkolenia2 = $_GET['Godzina1'];
    $Max_pacjent2 = $_GET['Max_pacjent1'];

        $result = $wpdb->insert( $wpdb->modul_terminarz, array( 
                                  'Nazwa_szkolenia' => $nazwa_szkolenia2, 
                                  'Data_szkolenia' => $Data_szkolenia2, 
                                  'Godzina_szkolenia' => $Godzina_szkolenia2,
                                  'Typ_szkolenia' => '1',
                                  'Ile_miejsc_max' => $Max_pacjent2,
                                  'Pelna_obsada' => '0',
                                  ) );

    wp_die();   
}


add_action('init', 'registerFormAction');

?>

that code stays in my menu.php:

// Hook for adding admin menus

 add_action('admin_menu', 'create_Terminarz_menu');

 // action function for above hook

/**
 * Adds a new top-level page to the administration menu.
 */
function create_Terminarz_menu() {

     add_menu_page(
        'ARCode Terminarz',
        'Terminarz',
        'manage_options',
        'zarzadzanie-terminami',
        'tm_zarzadzanie_terminami_odp',
        plugins_url('images/terminarz.png', __FILE__),'2.2.10'
    );

     add_submenu_page( 'zarzadzanie-terminami', 'ARCode Terminarz' . 'Terminy szkoleń', '<b style="color:#E46500;">Terminy szkoleń</b>', 'manage_options', 'zarzadzanie-terminami', 'tm_zarzadzanie_terminami_odp');
     add_submenu_page( 'zarzadzanie-terminami', 'ARCode Terminarz' . 'Pacjenci', 'Pacjenci', 'manage_options', 'pacjenci', 'tm_zarzadzanie_pacjentami_odp');
      add_action('admin_enqueue_scripts','load_custom_wp_admin_js');
}

/**
 * Disply callback for the Unsub page.
 */
 function tm_zarzadzanie_pacjentami_odp() {

 }



 function load_custom_wp_admin_js($hook){
    wp_register_script( 'jquery.min.js', plugin_dir_url( __FILE__ ) . 'js/jquery.min.js', array('jquery'));
    wp_enqueue_script( 'jquery.min.js' );
    wp_enqueue_style( 'kalendarz',plugin_dir_url( __FILE__ ) . 'kalendarz.css',false,'1.1','all' );
    wp_register_script( 'ajax-script', plugin_dir_url( __FILE__ ) . 'ajax_js.js');
    wp_localize_script('ajax-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
    wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ) . 'ajax_js.js');
}


 /**
 * Disply callback for the Unsub page.
 */
 function tm_zarzadzanie_terminami_odp() {
     include_once( 'arcode-functions.php');
     include_once( 'kalendarz.php');

     ?>
     <div class="wrap" style="position: fixed;
  width: 85%;
  top: 40px;
  bottom: 80px;">

     </div>
     <?php




 }

In kalendarz.php I have all funktions for booking calender and forms, this is the form which I need to send:

this.createFormular = function () {
             var ob = this.o;

             var Admin_Form = document.createElement('form')
            Admin_Form.name='Formularz_Admin';
            Admin_Form.method='GET';
            Admin_Form.action='';

             var tabela = document.createElement('table');
            tabela.className = 'formular-table';

             var tr = document.createElement('tr');
             tabela.appendChild(tr);
             var td = document.createElement('td');
             td.appendChild(document.createTextNode('Nazwa szkolenia:   '));
             tr.appendChild(td);
             tr.appendChild(td);



             td.appendChild(Input_Name_Training);

             var tr = document.createElement('tr');
             tabela.appendChild(tr);
             var td = document.createElement('td');
             td.appendChild(document.createTextNode('Data szkolenia:   '));
             tr.appendChild(td);
             tr.appendChild(td);

             td.appendChild(Input_Date_Training);

             var tr = document.createElement('tr');
             tabela.appendChild(tr);
             var td = document.createElement('td');
             td.appendChild(document.createTextNode('Godzina szkolenia:   '));
             tr.appendChild(td);
             tr.appendChild(td);

             td.appendChild(Input_Hour_Training);

             var tr = document.createElement('tr');
             tabela.appendChild(tr);
             var td = document.createElement('td');
             td.appendChild(document.createTextNode('Max ilość osób:   '));
             tr.appendChild(td);
             tr.appendChild(td);

             td.appendChild(Input_How_Many_People);          


             var tr = document.createElement('tr');
             tabela.appendChild(tr);
             var td = document.createElement('td');
             td.appendChild(document.createTextNode('   '));
             tr.appendChild(td);
             tr.appendChild(td);

             td.appendChild(Input_Form_Send);       

             Admin_Form.appendChild(tabela);

             this.divForm.appendChild(Admin_Form);


         };

I've tried to check if submitAjaxFormis working, I've checked it with echo as scott said, but it gives nothing. DataString gives right Array, but data gives 0... I don't know what I make wrong ;/ I don't see if hook to register for submitAjaxForm is bad, in my opinion all hooks are ok...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.