• Resolved mortenamdk

    (@mortenamdk)


    Hi

    I have a problem with Ajax for update my data in database.
    I get the right data in my ajax call, but nothing happening.

    Her is my code for call my update php function:

    global $wpdb;
      $table_name = $wpdb->prefix . 'topbanner';
    
        $outPut = $wpdb->get_results(
      "
      SELECT *
      FROM $table_name
      "
    );
    
      foreach ( $outPut as $(Hidden)_top_banner ) { ?>
    ?>
    
    <script>
    (function($) {
     $(document).on('click', '#submit_update<?php echo $(Hidden)_top_banner->id; ?>', function () {
       var (Hidden)_top_banner_name = tinymce.get('(Hidden)_top_banner_name<?php echo $(Hidden)_top_banner->id; ?>').getContent();
       var (Hidden)_top_banner_name_color = $('#(Hidden)_top_banner_name_color<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_text_line = $('#(Hidden)_top_banner_name_top_text_line<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_height = $('#(Hidden)_top_banner_name_top_height<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_start_date = $('#(Hidden)_top_banner_name_top_start_date<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_stop_date = $('#(Hidden)_top_banner_name_top_stop_date<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_media = $('#(Hidden)_top_banner_name_media<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_image_attachment_id = $('#(Hidden)_image_attachment_id<?php echo $(Hidden)_top_banner->id; ?>').val();
    
           var data = {
           (Hidden)_top_banner_name : (Hidden)_top_banner_name,
           (Hidden)_top_banner_name_color : (Hidden)_top_banner_name_color,
           (Hidden)_top_banner_name_top_text_line : (Hidden)_top_banner_name_top_text_line,
           (Hidden)_top_banner_name_top_height : (Hidden)_top_banner_name_top_height,
           (Hidden)_top_banner_name_top_start_date : (Hidden)_top_banner_name_top_start_date,
           (Hidden)_top_banner_name_top_stop_date : (Hidden)_top_banner_name_top_stop_date,
           (Hidden)_top_banner_name_media : (Hidden)_top_banner_name_media,
           (Hidden)_image_attachment_id : (Hidden)_image_attachment_id
           };
    $.ajax({
        type: 'post',
        url: '<?php echo plugin_dir_url( __FILE__ ) . 'ajax_update.php'; ?>',
        data: data,
        success : function( response ){
            $('body').fadeTo(1000, '0.4');
        },
        complete : function( response ) {
            location.reload()
          console.log(data); },
          error:function(response){
    alert("Fejl");
                }
    
    });
    
          });
    })(jQuery);
    </script>
    <?php
    }
    

    My php function to $_POST update:

    
    define( 'WP_USE_THEMES', false );
    
    require_once( '../../../wp-load.php' );
    global $wpdb;
      $table_name = $wpdb->prefix . 'topbanner';
    
        $outPut = $wpdb->get_results(
      "
      SELECT *
      FROM $table_name
      "
    );
      foreach ( $outPut as $(Hidden)_top_banner ) {
    
        $(Hidden)_top_banner_name                  = wp_kses_post($_POST['(Hidden)_top_banner_name'.$(Hidden)_top_banner->id'']);
        $(Hidden)_top_banner_name_color            = sanitize_hex_color($_POST['(Hidden)_top_banner_name_color'.$(Hidden)_top_banner->id'']);
        $(Hidden)_top_banner_name_top_text_line    = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_text_line'.$(Hidden)_top_banner->id'']);
        $(Hidden)_top_banner_name_top_height       = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_height'.$(Hidden)_top_banner->id'']);
        $(Hidden)_top_banner_name_top_start_date   = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_start_date'.$(Hidden)_top_banner->id'']);
        $(Hidden)_top_banner_name_top_stop_date    = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_stop_date'.$(Hidden)_top_banner->id'');
        $(Hidden)_top_banner_name_media            = sanitize_text_field($_POST['(Hidden)_top_banner_name_media'.$(Hidden)_top_banner->id'']);
        $(Hidden)_image_attachment_id              = sanitize_text_field($_POST['(Hidden)_image_attachment_id'.$(Hidden)_top_banner->id'']);
    
    $wpdb->update(
      $table_name,
      array(
            '(Hidden)_top_banner_name'                   => $(Hidden)_top_banner_name,
            '(Hidden)_top_banner_name_color'             => $(Hidden)_top_banner_name_color,
            '(Hidden)_top_banner_name_top_text_line'     => $(Hidden)_top_banner_name_top_text_line,
            '(Hidden)_top_banner_name_top_height'        => $(Hidden)_top_banner_name_top_height,
            '(Hidden)_top_banner_name_top_start_date'    => $(Hidden)_top_banner_name_top_start_date,
            '(Hidden)_top_banner_name_top_stop_date'     => $(Hidden)_top_banner_name_top_stop_date,
            '(Hidden)_top_banner_name_media'             => $(Hidden)_top_banner_name_media,
            '(Hidden)_image_attachment_id'               => $(Hidden)_image_attachment_id,
      ),
      array( 'id' => $(Hidden)_top_banner->id ),
      array(
        '%s',
        '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%d',
      ),
      array( '%d' )
    );
    }

    I have done the right thin with my ajax_insert.php there does it work, just not when i try to update.

    Best Regards
    Morten

    The page I need help with: [log in to see the link]

Viewing 15 replies - 1 through 15 (of 21 total)
  • Moderator bcworkz

    (@bcworkz)

    Your jQuery data still needs to be serialized or converted into a new FormData object, as I had explained previously. Maybe your previous effort failed for some other reason? It’s certainly not going to work if you don’t address serialization in some manner. You could use .post() instead of .ajax(), it’s a sort of shortcut which serializes passed data objects for you.

    Why are you requesting your own PHP file and including wp-load.php instead of going through admin-ajax.php? You had it right earlier, but now you’re Doing It Wrong®. I’m not saying doing so would not work, but it’s not a recommended practice because it’s not portable to other WP sites whose plugins and themes legitimately reside in a non-standard location.

    mortenamdk

    (@mortenamdk)

    Hi

    I am using admin-ajax.php now, i hear you ;o) but i can not get it to work when i try update.
    Have done it before in the database, with admin-ajax.php but now :o/

    You say “WP sites whose plugins and themes legitimately reside in a non-standard location.”
    I will really love if i could do some right things. So i am really happy you help me here.

    global $wpdb;
      $table_name = $wpdb->prefix . 'topbanner';
    
        $outPut = $wpdb->get_results(
      "
      SELECT *
      FROM $table_name
      "
    );
    
      foreach ( $outPut as $(Hidden)_top_banner ) { ?>
    ?>
    
    <script>
    (function($) {
     $(document).on('click', '#submit_update<?php echo $(Hidden)_top_banner->id; ?>', function (e) {
    e.preventDefault();
    
       var (Hidden)_top_banner_name = tinymce.get('(Hidden)_top_banner_name<?php echo $(Hidden)_top_banner->id; ?>').getContent();
       var (Hidden)_top_banner_name_color = $('#(Hidden)_top_banner_name_color<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_text_line = $('#(Hidden)_top_banner_name_top_text_line<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_height = $('#(Hidden)_top_banner_name_top_height<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_start_date = $('#(Hidden)_top_banner_name_top_start_date<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_top_stop_date = $('#(Hidden)_top_banner_name_top_stop_date<?php echo $(Hidden)_top_banner->id; ?>').val();
       var (Hidden)_top_banner_name_media = $('#(Hidden)_top_banner_name_media<?php echo $(Hidden)_top_banner->id; ?>').val();
    
           var data = {
             action : 'ajax_(Hidden)_update_top_banner',
             (Hidden)_top_banner_name : (Hidden)_top_banner_name,
             (Hidden)_top_banner_name_color : (Hidden)_top_banner_name_color,
             (Hidden)_top_banner_name_top_text_line : (Hidden)_top_banner_name_top_text_line,
             (Hidden)_top_banner_name_top_height : (Hidden)_top_banner_name_top_height,
             (Hidden)_top_banner_name_top_start_date : (Hidden)_top_banner_name_top_start_date,
             (Hidden)_top_banner_name_top_stop_date : (Hidden)_top_banner_name_top_stop_date,
             (Hidden)_top_banner_name_media : (Hidden)_top_banner_name_media,
           };
    $.ajax({
        type: 'post',
        url: ajaxurl.ajax_count,
        data: data,
        success : function( response ){
            $('body').fadeTo(1000, '0.4');
        },
        complete : function( response ) {
            $('body').fadeTo(1000, '1');
          console.log(data); },
          error:function(response){
    alert("Fejl");
                }
    
    });
    
          });
    })(jQuery);
    </script>
    add_action('wp_ajax_ajax_(Hidden)_update_top_banner', 'ajax_(Hidden)_update_top_banner');
    add_action('wp_ajax_nopriv_ajax_(Hidden)_update_top_banner', 'ajax_(Hidden)_update_top_banner');
    function ajax_(Hidden)_update_top_banner() {
      global $wpdb;
        $table_name = $wpdb->prefix . 'topbanner';
    
          $outPut = $wpdb->get_results(
        "
        SELECT *
        FROM $table_name
        "
      );
        foreach ( $outPut as $(Hidden)_top_banner ) {
    
          $(Hidden)_top_banner_name                  = wp_kses_post($_POST['(Hidden)_top_banner_name'.$(Hidden)_top_banner->id]);
          $(Hidden)_top_banner_name_color            = sanitize_hex_color($_POST['(Hidden)_top_banner_name_color'.$(Hidden)_top_banner->id]);
          $(Hidden)_top_banner_name_top_text_line    = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_text_line'.$(Hidden)_top_banner->id]);
          $(Hidden)_top_banner_name_top_height       = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_height'.$(Hidden)_top_banner->id]);
          $(Hidden)_top_banner_name_top_start_date   = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_start_date'.$(Hidden)_top_banner->id]);
          $(Hidden)_top_banner_name_top_stop_date    = sanitize_text_field($_POST['(Hidden)_top_banner_name_top_stop_date'.$(Hidden)_top_banner->id]);
          $(Hidden)_top_banner_name_media            = sanitize_text_field($_POST['(Hidden)_top_banner_name_media'.$(Hidden)_top_banner->id]);
          $(Hidden)_image_attachment_id              = sanitize_text_field($_POST['(Hidden)_image_attachment_id'.$(Hidden)_top_banner->id]);
    
      $wpdb->update(
        $table_name,
        array(
              '(Hidden)_top_banner_name'                   => $(Hidden)_top_banner_name,
              '(Hidden)_top_banner_name_color'             => $(Hidden)_top_banner_name_color,
              '(Hidden)_top_banner_name_top_text_line'     => $(Hidden)_top_banner_name_top_text_line,
              '(Hidden)_top_banner_name_top_height'        => $(Hidden)_top_banner_name_top_height,
              '(Hidden)_top_banner_name_top_start_date'    => $(Hidden)_top_banner_name_top_start_date,
              '(Hidden)_top_banner_name_top_stop_date'     => $(Hidden)_top_banner_name_top_stop_date,
              '(Hidden)_top_banner_name_media'             => $(Hidden)_top_banner_name_media,
              '(Hidden)_image_attachment_id'               => $(Hidden)_image_attachment_id,
        ),
        array( 'id' => $(Hidden)_top_banner->id ),
        array(
          '%s',
          '%s',
              '%s',
              '%s',
              '%s',
              '%s',
              '%s',
              '%d',
        ),
        array( '%d' )
      );
      }
    }

    Best Regards
    Morten

    mortenamdk

    (@mortenamdk)

    (function($) {
     $(document).on('click', '#insert_submit', function (e) {
            e.preventDefault();
    
            var (hidden)_top_banner_name                  = $('#(hidden)_top_banner_name').val();
            var (hidden)_top_banner_name_color            = $('#(hidden)_top_banner_name_color').val();
            var (hidden)_top_banner_name_top_text_line    = $('#(hidden)_top_banner_name_top_text_line').val();
            var (hidden)_top_banner_name_top_height       = $('#(hidden)_top_banner_name_top_height').val();
            var (hidden)_top_banner_name_top_start_date   = $('#(hidden)_top_banner_name_top_start_date').val();
            var (hidden)_top_banner_name_top_stop_date    = $('#(hidden)_top_banner_name_top_stop_date').val();
            var (hidden)_top_banner_name_media            = $('#(hidden)_top_banner_name_media').val();
            var (hidden)_image_attachment_id              = $('#(hidden)_image_attachment_id').val();
    
            var data = {
                action: 'ajax_insert_(hidden)_top_banner',
                (hidden)_top_banner_name : (hidden)_top_banner_name,
                (hidden)_top_banner_name_color : (hidden)_top_banner_name_color,
                (hidden)_top_banner_name_top_text_line : (hidden)_top_banner_name_top_text_line,
                (hidden)_top_banner_name_top_height : (hidden)_top_banner_name_top_height,
                (hidden)_top_banner_name_top_start_date : (hidden)_top_banner_name_top_start_date,
                (hidden)_top_banner_name_top_stop_date : (hidden)_top_banner_name_top_stop_date,
                (hidden)_top_banner_name_media : (hidden)_top_banner_name_media,
                (hidden)_image_attachment_id : (hidden)_image_attachment_id,
            };
    $.ajax({
        type: 'post',
        url: ajaxurl.ajax_url,
        data: $('#insert_form_data').serialize(),
        beforeSend: function( response ) {
            // setting a timeout
            $('body').fadeTo(1000, '0.4');
        },
        success : function( response ){
            $('body').fadeTo(1000, '0.4');
        },
        complete: function( response ) {
             $('body').fadeTo(4000, '1');
            console.log(data); },
        error : function( response ){
            alert("fejl")
    
        }
    });
    
          });
    })(jQuery);
    
    mortenamdk

    (@mortenamdk)

    Hi

    have tryed this

    (function($) {
     $(document).on('click', '#insert_submit', function (e) {
            e.preventDefault();
    
            // Get form
            var form = $('#insert_form_data')[0];
    
           // Create an FormData object
            var data = new FormData(form);
            data.append("action", "ajax_insert_(hidden)_top_banner");
    $.ajax({
        type: 'post',
        url: ajaxurl.ajax_url,
        enctype: 'multipart/form-data',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        timeout: 800000,
        beforeSend: function( response ) {
            // setting a timeout
            $('#contact-msg').html("Loading...")
        },
        success: function (data) {
    
                    $("#contact-msg").text(data);
    
                },
        complete: function( response ) {
    
             $('body').fadeTo(4000, '1');
            console.log(data); },
        error : function( response ){
            alert("fejl")
    
        }
    });
    
          });
    })(jQuery);

    But so comes it with all there is on pages all code.

    • This reply was modified 1 week ago by mortenamdk.
    • This reply was modified 1 week ago by bcworkz.
    Moderator bcworkz

    (@bcworkz)

    What code is it you see on pages?

    Lets verify that your PHP Ajax handler is at least getting reached. Insert something like echo 'Ajax handler was reached'; as the first line inside the function declaration. The output should show up in your browser’s console if the ajax.url and action values are correct.

    You should also insert code to confirm the current user is logged in and is allowed to alter the table. Something like:
    if ( ! current_user_can('manage_options')) wp_die('Invalid user permissions');
    Additionally, you should be supplying a nonce to jQuery similar to how ajax_url is supplied. Submit the nonce as part of the Ajax data and verify it is correct in the Ajax handler. It’s not essential to do this right now, but you should add it in once you get some basic functionality going.

    Your Ajax handler function needs to call wp_die(); or similar at the very end. There’s probably more, but the first task is to simply get a request and reply working correctly. Once that works, everything else usually falls into place without too much fuss.

    Hi
    I get my values in my console. But not in my database.

    The text I get when I try to formdata is all tekst on the page. Eks. A link and so.

    Best regards
    Morten

    This if try the formdata
    <!DOCTYPE html> <!–[if IE 8]> <html xmlns=”http://www.w3.org/1999/xhtml&#8221; class=”ie8 wp-toolbar” lang=”da-DK” > <![endif]–> <!–[if !(IE 8) ]><!–> <html xmlns=”http://www.w3.org/1999/xhtml&#8221; class=”wp-toolbar” lang=”da-DK” > <!–<![endif]–> <head> <meta http-equiv=”Content-Type”

    so have i uset serialize()
    And get some output

    (function($) {
     $(document).on('click', '#insert_submit', function (e) {
            e.preventDefault();
    
           // Create an FormData object
           var form_data = $( "#insert_form_data" ).serialize();
        $( "#results" ).text( form_data );
    $.ajax({
        type: 'post',
        url: ajaxurl.ajax_url,
        data: {
          action: 'ajax_insert_teenstyle_top_banner',
          form_data: form_data},
        cache: false,
        processData: false,
        contentType: false,
        beforeSend: function( response ) {
            // setting a timeout
            $('#contact-msg').html("Loading...")
        },
        success: function (form_data) {
              console.log(form_data);
                },
        complete: function( response ) {
    
             $('body').fadeTo(4000, '1');
             },
        error : function( response ){
            alert("fejl")
    
        }
    });
    
          });
    })(jQuery);

    output: ajax_count.js?ver=5.2.4:30 (hidden)_top_banner_name=&(hidden)_top_banner_name_color=%23c9c9c9&(hidden)_top_banner_name_media=&(hidden)_image_attachment_id=&(hidden)_top_banner_name_top_height=28&(hidden)_top_banner_name_top_text_line=1.8&(hidden)_top_banner_name_top_start_date=11-11-2019&(hidden)_top_banner_name_top_stop_date=12-11-2019

    This is my function:

    <?php
    add_action('wp_ajax_ajax_(hidden)_update_top_banner', 'ajax_(hidden)_update_top_banner');
    add_action('wp_ajax_nopriv_ajax_(hidden)_update_top_banner', 'ajax_(hidden)_update_top_banner');
    function ajax_(hidden)_update_top_banner() {
      echo 'Ajax handler was reached';
      global $wpdb;
        $table_name = $wpdb->prefix . 'topbanner';
    
          $outPut = $wpdb->get_results(
        "
        SELECT *
        FROM $table_name
        "
      );
        foreach ( $outPut as $(hidden)_top_banner ) {
    
          $(hidden)_top_banner_name                  = wp_kses_post($_POST['(hidden)_top_banner_name'.$(hidden)_top_banner->id]);
          $(hidden)_top_banner_name_color            = sanitize_hex_color($_POST['(hidden)_top_banner_name_color'.$(hidden)_top_banner->id]);
          $(hidden)_top_banner_name_top_text_line    = sanitize_text_field($_POST['(hidden)_top_banner_name_top_text_line'.$(hidden)_top_banner->id]);
          $(hidden)_top_banner_name_top_height       = sanitize_text_field($_POST['(hidden)_top_banner_name_top_height'.$(hidden)_top_banner->id]);
          $(hidden)_top_banner_name_top_start_date   = sanitize_text_field($_POST['(hidden)_top_banner_name_top_start_date'.$(hidden)_top_banner->id]);
          $(hidden)_top_banner_name_top_stop_date    = sanitize_text_field($_POST['(hidden)_top_banner_name_top_stop_date'.$(hidden)_top_banner->id]);
          $(hidden)_top_banner_name_media            = sanitize_text_field($_POST['(hidden)_top_banner_name_media'.$(hidden)_top_banner->id]);
          $(hidden)_image_attachment_id              = sanitize_text_field($_POST['(hidden)_image_attachment_id'.$(hidden)_top_banner->id]);
    
      $wpdb->update(
        $table_name,
        array(
              '(hidden)_top_banner_name'                   => $(hidden)_top_banner_name,
              '(hidden)_top_banner_name_color'             => $(hidden)_top_banner_name_color,
              '(hidden)_top_banner_name_top_text_line'     => $(hidden)_top_banner_name_top_text_line,
              '(hidden)_top_banner_name_top_height'        => $(hidden)_top_banner_name_top_height,
              '(hidden)_top_banner_name_top_start_date'    => $(hidden)_top_banner_name_top_start_date,
              '(hidden)_top_banner_name_top_stop_date'     => $(hidden)_top_banner_name_top_stop_date,
              '(hidden)_top_banner_name_media'             => $(hidden)_top_banner_name_media,
              '(hidden)_image_attachment_id'               => $(hidden)_image_attachment_id,
        ),
        array( 'id' => $(hidden)_top_banner->id ),
        array(
          '%s',
          '%s',
              '%s',
              '%s',
              '%s',
              '%s',
              '%s',
              '%d',
        ),
        array( '%d' )
      );
      }
      print_r($_POST);
      wp_die();
    }
    

    My form:

    <div>
    <form method="post" id="insert_form_data" enctype="multipart/form-data">
    
        <div class="plugin_(hidden)_banner">
    
            <div><label for="(hidden)_top_banner_name"><b>Banner tekst</b></label></div>
            <?php
    
                      $(hidden)_top_banner_name = $(hidden)_top_banner->(hidden)_top_banner_name;
            wp_editor( $(hidden)_top_banner_name, '(hidden)_top_banner_name', array(
                'wpautop'       => true,
                'media_buttons' => true,
                'textarea_rows' => 1,
            ) );?>
        </div>
        <div class="plugin_(hidden)_top_banner">
          <div><label><b>Baggrundsfarve</b><br></label><input type="text" class="color-picker" data-alpha="true" name="(hidden)_top_banner_name_color" id="(hidden)_top_banner_name_color<?php echo $(hidden)_top_banner->id; ?>" value="" /></div>
            <label><b>Baggrundsbillede</b></label>
            <div class='image-preview-wrapper'>
    			<img id='image-preview' src='<?php echo wp_get_attachment_url( $(hidden)_top_banner->(hidden)_top_banner_name_media  ); ?>' width='100%'>
    		</div>
            <input hidden name="(hidden)_top_banner_name_media" id="(hidden)_top_banner_name_media" value="<?php echo wp_get_attachment_url( $(hidden)_top_banner->(hidden)_top_banner_name_media  ); ?>"/>
    
    		<input id="upload_image_button" name="upload_image_button<?php echo $(hidden)_top_banner->id; ?>" type="button" class="button" value="<?php _e( 'Upload banner billede' ); ?>" />
    <label><b>Vis billede</b></label>
    		<input type='checkbox' name='(hidden)_image_attachment_id' id='(hidden)_image_attachment_id' value='' checked><br><br>
    <div><b>Height på banner linjen</b></div>
            <input type="number" maxlength="4" size="4" name="(hidden)_top_banner_name_top_height" id="(hidden)_top_banner_name_top_height" value="">
    <div><b>Tekst linje højde</b></div>
            <input type="text" size="4" name="(hidden)_top_banner_name_top_text_line" id="(hidden)_top_banner_name_top_text_line" value="">
            <div><b>Start</b></div>
            <input type="text" class="date_picker plugin_(hidden)_top_banner_dato" name="(hidden)_top_banner_name_top_start_date" id="(hidden)_top_banner_name_top_start_date" value="">
            <div><b>Slut</b></div>
            <input type="text" class="date_picker plugin_(hidden)_top_banner_dato" name="(hidden)_top_banner_name_top_stop_date" id="(hidden)_top_banner_name_top_stop_date" value=""><br><br>
    		<input type="submit" name="insert_submit" id="insert_submit" value="Tilføj banner" class="button-primary">
    	</div>
    
            </form>
            <div id="results">
    
            </div>
    </div>

    I don’t get any output from function, and i don’t know where i should find them.

    Best regards
    Morten

    (function($) {
     $(document).on('click', '#insert_submit', function (e) {
            e.preventDefault();
    
           // Create an FormData object
           var form_data = $( "#insert_form_data" ).serialize();
                            $( "#results" ).text( form_data );
    $.ajax({
        type: 'post',
        url: ajaxurl.ajax_url,
        data: {
          action: 'ajax_insert_(hidden)_top_banner',
          (hidden)_top_banner_name : (hidden)_top_banner_name,
          (hidden)_top_banner_name_color : (hidden)_top_banner_name_color,
          (hidden)_top_banner_name_top_text_line : (hidden)_top_banner_name_top_text_line,
          (hidden)_top_banner_name_top_height : (hidden)_top_banner_name_top_height,
          (hidden)_top_banner_name_top_start_date : (hidden)_top_banner_name_top_start_date,
          (hidden)_top_banner_name_top_stop_date : (hidden)_top_banner_name_top_stop_date,
          (hidden)_top_banner_name_media : (hidden)_top_banner_name_media,
          (hidden)_image_attachment_id : (hidden)_image_attachment_id},
        cache: false,
        processData: false,
        contentType: false,
        beforeSend: function( response ) {
            // setting a timeout
            $('#contact-msg').html("Loading...")
        },
        success: function (response) {
            console.log(form_data);
                },
        complete: function( response ) {
    
             $('body').fadeTo(4000, '1');
             },
        error : function( response ){
            alert("fejl")
    
        }
    });
    
          });
    })(jQuery);

    So now i get a clean line: output: ajax_count.js?ver=5.2.4:30 (hidden)_top_banner_name=&(hidden)_top_banner_name_color=%23c9c9c9&(hidden)_top_banner_name_media=&(hidden)_image_attachment_id=&(hidden)_top_banner_name_top_height=28&(hidden)_top_banner_name_top_text_line=1.8&(hidden)_top_banner_name_top_start_date=11-11-2019&(hidden)_top_banner_name_top_stop_date=12-11-2019

    • This reply was modified 6 days, 4 hours ago by mortenamdk.
    • This reply was modified 6 days, 4 hours ago by mortenamdk.

    Insert function to ajax but does not work:

    <?php
    add_action('wp_ajax_ajax_ajax_(hidden)_insert_top_banner', 'ajax_(hidden)_insert_top_banner');
    add_action('wp_ajax_nopriv_ajax_(hidden)_insert_top_banner', 'ajax_(hidden)_insert_top_banner');
    
    function ajax_(hidden)_insert_top_banner() {
      echo 'Ajax handler was reached';
    global $wpdb;
      $table_name = $wpdb->prefix . "topbanner";
    
        global $wpdb;
    
        $(hidden)_top_banner_name                  = wp_kses_post($_POST['(hidden)_top_banner_name']);
        $(hidden)_top_banner_name_color            = sanitize_hex_color($_POST['(hidden)_top_banner_name_color']);
        $(hidden)_top_banner_name_top_text_line    = sanitize_text_field($_POST['(hidden)_top_banner_name_top_text_line']);
        $(hidden)_top_banner_name_top_height       = sanitize_text_field($_POST['(hidden)_top_banner_name_top_height']);
        $(hidden)_top_banner_name_top_start_date   = sanitize_text_field($_POST['(hidden)_top_banner_name_top_start_date']);
        $(hidden)_top_banner_name_top_stop_date    = sanitize_text_field($_POST['(hidden)_top_banner_name_top_stop_date']);
        $(hidden)_top_banner_name_media            = sanitize_text_field($_POST['(hidden)_top_banner_name_media']);
        $(hidden)_image_attachment_id              = sanitize_text_field($_POST['(hidden)_image_attachment_id']);
    
    $wpdb->query($wpdb->prepare(
    	"
    		INSERT INTO $table_name
            ( (hidden)_top_banner_name, (hidden)_top_banner_name_color, (hidden)_top_banner_name_top_text_line, (hidden)_top_banner_name_top_height, (hidden)_top_banner_name_top_start_date, (hidden)_top_banner_name_top_stop_date, (hidden)_top_banner_name_media, (hidden)_image_attachment_id )
    		VALUES ( %s, %s, %s, %s, %s, %s, %s, %d )
    	",
        array(
            $(hidden)_top_banner_name,
            $(hidden)_top_banner_name_color,
            $(hidden)_top_banner_name_top_text_line,
            $(hidden)_top_banner_name_top_height,
            $(hidden)_top_banner_name_top_start_date,
            $(hidden)_top_banner_name_top_stop_date,
            $(hidden)_top_banner_name_media,
            $(hidden)_image_attachment_id
            )
    )
    
    );
        print_r($_POST);
        wp_die();
      } ?>
    
    • This reply was modified 6 days, 1 hour ago by mortenamdk.
    Moderator bcworkz

    (@bcworkz)

    Output from jQuery by setting .text() isn’t very informative from my standpoint, it’s what is logged in the browser console, if anything, that is informative. OTOH it doesn’t do any harm if you find it useful. .serialize() is the correct approach if you want to submit input from a form, but you cannot then easily add in the action value afterwards. To include the action value in the data sent to the server, add a hidden input field named “action” to your form HTML which is assigned the desired value.

    When you get around to implementing a nonce, include this value as a hidden field as well. It’s a little simpler if the field name is “_ajax_nonce” because WP looks for this automatically when you check the nonce in PHP.

    With the added hidden fields, this is fine: var form_data = $( "#insert_form_data" ).serialize();

    In the .ajax() call then, pass the serialized data: data: form_data,
    You should then at least see the server response in your browser console.

    Hi

    Now is there this in the console:
    action=ajax_insert_(hidden)_top_banner&(hidden)_top_banner_name=&(hidden)_top_banner_name_color=%23dd9933&(hidden)_top_banner_name_media=http%3A%2F%2Flocalhost%2Fwordpress_(hidden)%2Fwp-content%2Fuploads%2F2019%2F11%2FTS_logo.png&(hidden)_image_attachment_id=115&(hidden)_top_banner_name_top_height=28&(hidden)_top_banner_name_top_text_line=1.8&(hidden)_top_banner_name_top_start_date=11-11-2019&(hidden)_top_banner_name_top_stop_date=12-11-2019&_ajax_nonce=ajax_insert_(hidden)_top_banner

    Best regards
    Morten

    (function($) {
     $(document).on('click', '#insert_submit', function (e) {
            e.preventDefault();
    
           var form_data = $( "#insert_form_data" ).serialize();
    $.ajax({
        type: 'post',
        url: ajaxurl.ajax_url,
        data: form_data,
        beforeSend: function( response ) {
            // setting a timeout
            $('#results').html("Loading...")
        },
        success: function (data) {
            console.log(form_data);
                },
        complete: function( response ) {
    
             $('body').fadeTo(4000, '1');
             },
        error : function( response ){
            alert("fejl")
    
        }
    });
    
          });
    })(jQuery);
    Moderator bcworkz

    (@bcworkz)

    OK! That console content came from your PHP Ajax handler, so the data has made an out and back trip and demonstrates that the Ajax portion is working as expected. Cause for celebration in itself!

    Now we can focus on why the table INSERT is not working. Remove any existing echo or print_r() lines from the Ajax handler. We have something else to output to console now. Add echo $wpdb->last_query; just before the wp_die(); line.

    Get into phpMyAdmin and navigate to your DB. If you already have important data in the table, I recommend you export a backup file for safety’s sake. Go to the DB’s SQL tab. Submit the form again to trigger the Ajax code. Be sure the last_query string that appears in the console is as you expect. Copy the last_query string from the console and paste it into the Run SQL field of the SQL tab in phpMyAdmin. Click Go.

    The query will either succeed or phpMyAdmin will give you a better idea of what is wrong with the query.

    Something else you could try if you have trouble with your SQL query is to use wpdb->insert() instead. You don’t need prepare() because it’s done internally with this method. This will require rearranging how your fields and data are coded so that it is structured as required and described on the linked docs page.

    Hi

    I can only see echo output if i takes the handler a please i can se it, eks. between

    function (hidden)_top_banner_option_page() { ?>
    
    <?php (hidden)_show_update_teenstyle_banner(); ?>
    <?php (hidden)_insert_top_banner(); ?>
    <?php (hidden)_delete_top_banner(); ?>
    <strong><?php ajax_(hidden)_insert_top_banner(); ?></strong>
    <?php }

    There can i see the output
    INSERT INTO wp_topbanner ( (hidden)_top_banner_name, (hidden)_top_banner_name_color, (hidden)_top_banner_name_top_text_line, (hidden)_top_banner_name_top_height, (hidden)_top_banner_name_top_start_date, (hidden)_top_banner_name_top_stop_date, (hidden)_top_banner_name_media, (hidden)_image_attachment_id ) VALUES ( ”, ‘#000000’, ‘1.8’, ’28’, ’18-10-2019′, ’19-10-2019′, ”, 0 )

    There is nothing in console

Viewing 15 replies - 1 through 15 (of 21 total)
  • You must be logged in to reply to this topic.