TransWikia.com

How to add a javascript function after uploading file

Drupal Answers Asked by Ahmed on December 9, 2020

I make a form using FAPI, and this form contains a file managed field. I want to show an alert after uploading the file (“uploaded successfully”), and a confirmation (“Are you sure you want to delete file”) when deleting the file.

This my code.

$form['my_file_fid'] = array(
  '#type' => 'managed_file',
  '#title' => t('Files'),
  '#default_value' => variable_get('my_file_fid', ''),
  '#upload_location' => 'public://',
); 

I tried to add #file_value_callbacks, but I don’t know how to use it.

I tried to make a javascript just to alert when I click upload,remove button but it doen not work I tried to make it general to all input to check that js is correct now all inputs are clickable but upload and remove button not

jQuery(document).ready(function() {
         jQuery('input').bind('click',function() { alert("hi") });
 });  

I make this js to check jquery ajaxSuccess function

2 Answers

Hope this will help, use hook_file_presave inside that you can use drupal set message.

/**
 * implementing hook_node_presave 
 */
function mymodule_file_presave($file) {
//dpm($file);
// 
 if (isset($file->source) && $file->source=='field_preview_image_file_und_0')//make condition like this for ur file
{
//use the drupal set message or java script alert  on successful upload
drupal_add_js(drupal_get_path('module','mymodule') . '/test.js');
}
}

create a js file on same module folder as test.js

(function ($) {
$(document).ready(function(){
alert('this is alert message');  
});
})(jQuery);

Answered by madhurjya on December 9, 2020

You could just bind something to the jQuery ajax success event on the page where your form is displayed.

You can bind ajaxSuccess to any jQuery object, try something like this if you're experimenting:

<script>
  (function ($) {
    $(function () {
      jQueryObject = $({});
      jQueryObject.ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions) {
        /* do something whenever an ajax call is successful */
      });
    });
  })(jQuery);
</script>

Answered by David Meister on December 9, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP