Reputation: 606
i am trying to upload file using ajax in wordpress.
i am trying following form:
<form class="form-horizontal" id="file_form">
<?php wp_nonce_field("ajax_file_nonce","security");
wp_localize_script( 'custom-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
?>
<input type="hidden" name="action" value="my_file_upload">
<input id="resume" name="resume" class="input-file form-control" type="file">
here is my function:
add_action('wp_ajax_my_file_upload', 'my_file_upload');
add_action('wp_ajax_nopriv_my_file_upload', 'my_file_upload');
function handle_file_upload()
{
$response['message'] = 'Done!';
echo json_encode($response); die();
check_ajax_referer('ajax_file_nonce', 'security');
if(!(is_array($_POST) && is_array($_FILES) && defined('DOING_AJAX') && DOING_AJAX)){
return;
}
if(!function_exists('wp_handle_upload')){
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$upload_overrides = array('test_form' => false);
$response = array();
foreach($_FILES as $file){
$file_info = wp_handle_upload($file, $upload_overrides);
// do something with the file info...
$response['message'] = 'Done!';
}
echo json_encode($response);
die();
}
here is my jquery:
jQuery(document).on(\'click\', \'#send\', function(e){
//alert();
e.preventDefault();
var ajax_url = "'.admin_url('admin-ajax.php').'"
var form_data = {};
$("#file_form").find(\'input\').each(function(){
form_data[this.name] = $(this).val();
//alert(this.name);
});
jQuery.ajax({
type: 'POST',
url: MyAjax.ajaxurl, //
data: form_data,
contentType: 'json',
success: function(response){
alert(response.message);
}
});
});
but this shows MyAjax not defined. when i tried "ajax_url" variable defined in same jquery, it return "undefined" message.
what is the problem in this code ? what modifications are needed. help me please.
Upvotes: 3
Views: 1110
Reputation: 173
Remove
contentType: 'json'
from jquery and give a try.
i have read somewhere in previous stack answers
Upvotes: 2
Reputation: 3848
It probably depends on how you load your jQuery script and how you use the wp_localize_script
function.
Try this in your functions.php file:
add_action( 'wp_enqueue_scripts', function(){
wp_enqueue_script( 'custom-ajax-request', get_stylesheet_directory_uri().'/js/custom-ajax-request.js', array('jquery') );
wp_localize_script( 'custom-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
} );
The wp_enqueue_script
function load your jQuery script (I named the file custom-ajax-request.js
) and wp_localize_script
pass the MyAjax variable to the script (make sure you use the same handle, in this case 'custom-ajax-request'
).
Also you should unquote the strings in your jQuery script, and remove the wp_localize_script
row from the form in your template file.
Upvotes: 3