0

As Salamu Alaikum, I am working wp_ajax and try to upload a file through ajax. When I processData: true it returns error illegal invocation on file upload. But when I set processData: false it returns error 400 bad request. But, I have double-checked that everything is fine in PHP. But if I do not upload file all data get saved successfully.

Here is my form...

 <form action="" method="POST" enctype="multipart/form-data">
            <div class="form-group">
            <input id="f-title" name="f-title" placeholder="Flyer Title" class="form-control" required="" type="text">
            </div>
            <div class="form-group">
            <input id="f-validity" name="f-validity" placeholder="Valid Till" class="form-control" required="" type="date">
            </div>
            <div class="form-group">
            <input id="f-ID" name="f-ID" placeholder="Flyer ID" class="form-control" required="" type="text">
            </div>
            <div class="form-group">
            <input id="f-thumbnail" name="f-thumbnail" class="form-control" required="" type="file">
            </div>
            <div class="form-group">
            <input id="f-company" name="f-company" class="form-control" placeholder="Company ID" required="" type="text">
            </div>
            <div class="form-group">
            <div class="row">
            <div class="col-md-6">
            <select id="f-category" name="f-category" class="form-control" required="">
            <?php 
                $limit = 50;
                $terms = apply_filters( 
                    'taxonomy-images-get-terms',  
                    '',
                    array( 
                        'taxonomy' => 'flyer-cat',
                    ) 
                );
                foreach ($terms as $term) {
                  $term_link = get_term_link( $term );

                }
            ?>
            <?php foreach($terms as $term) { ?>
                <?php $term_link = get_term_link( $term ); $limit++; ?>
                <option><?php _e($term->name); ?></option>
            <?php } ?>
            </select>
            </div>
            <div class="col-md-6">
            <button class="form-control" name="f-submit" id="f-submit" type="button">Save Flyer</button>
            </div>
            </div>
            </div>
        </form>

Here is my javascript

jQuery(document).ready(function(e) {
    jQuery('#f-submit').on('click', function(e) {
      e.preventDefault();
      var f_title = jQuery('#f-title').val();
      var f_validity = jQuery('#f-validity').val();
      var f_ID = jQuery('#f-ID').val();
      var f_company = jQuery('#f-company').val();
      var f_category = jQuery('#f-category').val();
      var f_thumbnail = jQuery('#f-thumbnail').prop('files')[0];
      console.log(f_thumbnail);
      //SaveFlyer(f_title, f_validity, f_ID, f_company, f_category, f_thumbnail);
    });

    function SaveFlyer(f_title, f_validity, f_ID, f_company, f_category, f_thumbnail) {
        jQuery.ajax({
            type: "POST",
            url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
            cache: false,
            contentType: 'json',
            dataType: false,
            data: { 'action':'save_flyer', 'f_title':f_title, 'f_validity':f_validity, 'f_ID':f_ID, 'f_company':f_company, 'f_category':f_category, 'f_thumbnail':f_thumbnail }, 
            beforeSend: onLoading,
            success: onSuccesPing,
            crossDomain:true
        });

    }
    function onLoading() {
    }
    function onSuccesPing(data, status) {
        alert('Success!!');
    }
  });

And in my functions.php, I have...

function save_flyer()
{
    $f_title        = $_POST['f_title'];
    $f_validity   = $_POST['f_validity'];
    $f_ID         = $_POST['f_ID'];
    $f_company    = $_POST['f_company'];
    $f_category   = $_POST['f_category'];
    $f_thumbnail  = $_POST['f_thumbnail'];

    $new_post = array(
        'post_title'    => $f_title,
        'tags_input'    => $f_category,
        'post_status'   => 'publish',       
        'post_type'     => 'soldy-flyer'
    );

    $post_id = wp_insert_post($new_post);

    add_post_meta($post_id, 'sf_flyer-id', $f_ID);
    add_post_meta($post_id, 'sf_flyer-company', $f_company);
    add_post_meta($post_id, 'sf_flyer-valid', $f_validity);

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attahment_id = media_handle_upload( 'f_thumbnail', $post_id );

    set_post_thumbnail($post_id, $attahment_id);
}
add_action('wp_ajax_save_flyer', 'save_flyer');
add_action('wp_ajax_nopriv_save_flyer', 'save_flyer');
  • "contentType" is a the type of content you send then try with "contentType" : false, – Kaperto Jan 2 at 9:07
  • @Kaperto I tried but did not work, Thanks brother. is There Anything I can try? – Allen Titan Jan 2 at 9:08
  • try without "crossdomain". what I use for years is $.ajax({"url" : ajaxurl, "type" : "POST", "data" : formData, "processData" : false, "contentType" : false, "dataType"" : "html"}) – Kaperto Jan 2 at 9:16
  • oh, I forget something, to send files use FormData let formData = new FormData(); formData.append("action", "save_flyer"); formData.append("f_title", f_title); $.each(jQuery('#f-thumbnail').files, function (i, file) { formData.append("f_" + i, file); }); – Kaperto Jan 2 at 9:19
  • @Kaperto thanks, brother. But the same result as before. Data is not being sent correctly, anyway if 'processData' set to false otherwise error as 'illegal invocation' – Allen Titan Jan 2 at 9:46
0

You can upload file using ajax using below code:

First : Add attributes name="f-form" and id="f-form" in your <form> tag.

After that, In js script, get form data using new FormData() and send to ajax data,

Note : change url: ajax_object.ajaxurl with your ajax url path

jQuery(document).ready(function(e) {
    jQuery('#f-submit').on('click', function(e) {
      e.preventDefault();
      var form = jQuery('#f-form')[0];
      var varform = new FormData(form);
      varform.append("action", "save_flyer");
      SaveFlyer(varform);
    });

    function SaveFlyer(varform) {
        jQuery.ajax({
            type: "POST",
            url: ajax_object.ajaxurl,
            dataType: "JSON",
            data: varform,
            processData: false,
            contentType: false,
            cache: false,
            beforeSend: onLoading,
            success: onSuccesPing,
            crossDomain:true
        });

    }
    function onLoading() {
    }
    function onSuccesPing(data, status) {
        if(data.result == 'true')
        {
            alert('Success!!');
        }
        if(data.result == 'false')
        {
            alert('Fail!!');
        }
    }
  });

Finaly, ajax handel request :

function save_flyer()
{
    $f_title        = $_POST['f-title'];
    $f_validity   = $_POST['f-validity'];
    $f_ID         = $_POST['f-ID'];
    $f_company    = $_POST['f-company'];
    $f_category   = $_POST['f-category'];

    $new_post = array(
        'post_title'    => $f_title,
        'tags_input'    => $f_category,
        'post_status'   => 'publish',       
        'post_type'     => 'soldy-flyer'
    );

    $post_id = wp_insert_post($new_post);
    if($post_id)
    {
    add_post_meta($post_id, 'sf_flyer-id', $f_ID);
    add_post_meta($post_id, 'sf_flyer-company', $f_company);
    add_post_meta($post_id, 'sf_flyer-valid', $f_validity);

        if(empty($_FILES['f-thumbnail']['error'])){
          require_once( ABSPATH . 'wp-admin/includes/image.php' );
          require_once( ABSPATH . 'wp-admin/includes/file.php' );
          require_once( ABSPATH . 'wp-admin/includes/media.php' );

           $attahment_id = media_handle_upload( 'f-thumbnail', $post_id );

          if(!empty($attahment_id))
          { 
             set_post_thumbnail($post_id, $attahment_id);
          }
         }   
         $result1 = 'true';
    }
    else
    {
            $result1= 'false';
    }   

     echo json_encode(array('result'=>$result1));
    die();  
}
add_action('wp_ajax_save_flyer', 'save_flyer');
add_action('wp_ajax_nopriv_save_flyer', 'save_flyer');

let me know if this helps to you.

  • Whats wrong in my answer ? why answer was downvoted ? – Chetan Vaghela Jan 16 at 11:33

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.