When a file is uploaded to my page I make an ajax call to add an entry in a database. I then want to send a string back to the client using wp_localize_script but when I try to access it I just get an error saying "Uncaught Reference Error: pw_script_vars is not defined".
I know I can send something back with wp_die but this is a bit of a work around that I don't think is the correct way. So the question is why is the wp_localize_script not working? Any help appreciated.
script.js:
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery(function($) {
var i;
for(i=1;i<21;i++){
$('body').on('change', '#file'+i, function() {
var file_data = $(this).prop('files')[0];
var id = $(this).attr('id');
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', 'file_upload');
jQuery.ajax({
url: ajaxurl,
type: 'POST',
contentType: false,
processData: false,
data: form_data,
success: function (response) {
alert( pw_script_vars.alert );
}
});
});
}
});
functions.php:
add_action('wp_enqueue_scripts','owr_scripts_function');
add_action( 'wp_ajax_file_upload', 'file_upload_callback' );
add_action( 'wp_ajax_nopriv_file_upload', 'file_upload_callback' );
function owr_scripts_function() {
wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/script.js', array('jquery'), time(), false);
}
function file_upload_callback(){
wp_localize_script('script', 'pw_script_vars', array(
'alert' => __('Hey! You have clicked the button!', 'pippin'),
'message' => __('You have clicked the other button. Good job!', 'pippin')
)
);
wp_die("upload success");
}
`