我是WP世界中的新手。阅读大量帖子后,我仍然无法在WordPress上运行简单的Ajax文件。
我正在尝试的是存储在数据库中-名称,电子邮件和简历。如果删除输入文件字段,则名称和电子邮件将正确存储到数据库中。
当前,我的表单如下
<form method="post" id="applicantform" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name" />
<?php wp_nonce_field( 'my_nonce' ); ?>
<input type="email" name="email" placeholder="Email" />
<div class="upload">
<input type="file" id="upload-resume" name="upload-resume" />
</div>
<input type="submit" name="submit_form" id="submit_form" value="Send" />
</form>
js部分是
jQuery(document).ready(function($){
$('#submit_form').click(function(e){
var applyformData = document.getElementById("applicantform");
e.preventDefault();
//ajax call
$.ajax({
type: 'POST',
url: myajax.ajaxurl, // ajax url you assigned!
contentType: false,
cache: false,
processData:false,
dataType: 'json',
data: {
action: 'applyform',
formdata: applyformData,
},
// Displaying succes message
success: function( data ){
},
// Displaying error message
error: function( request ){
console.log(request);
}
});
});
});
这是我的function.php
add_action('wp_enqueue_scripts', 'my_ajax_scripts');
function my_ajax_scripts(){
wp_enqueue_script( 'myscript', get_template_directory_uri().'/assets/js/formSubmit.js', array('jquery'), '1.0', true );
wp_localize_script( 'myscript', 'myajax', array( 'ajaxurl' => admin_url( '/admin-ajax.php' ) ) );
}
function applyform(){
$valid_extensions = array('pdf' , 'doc' , 'ppt'); // valid extensions
$path = wp_basename( $uploads['baseurl'] ); // upload directory
if(!empty($_POST['name']) || !empty($_POST['email']) || $_FILES['upload-resume'])
{
$resume = $_FILES['upload-resume']['name'];
$tmp = $_FILES['upload-resume']['tmp_name'];
$ext = strtolower(pathinfo($resume, PATHINFO_EXTENSION));
$final_resume = rand(1000,1000000).$resume;
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_resume);
if(move_uploaded_file($tmp,$path))
{
$table = 'UPC_jobs';
$data = array(
'customer_name' => $formdata_array['name'],
'customer_email' => $formdata_array['email'],
'customer_resume' => $path
);
$format = array(
'%s',
'%s',
'%s'
);
$success=$wpdb->insert( $table, $data, $format );
}
}
else {
echo 'invalid';
}
}
}
admin-ajax.php当前错误为Status Code: 400
。
任何人都可以帮忙
答案 0 :(得分:1)
请检查代码中的以下内容
add_action('wp_ajax_applyform', 'applyform');
add_action('wp_ajax_nopriv_applyform', 'applyform');
有关Ajax文件上传的检查链接 WP admin ajax file upload
添加随机数
在您的js部分
data: {
action: 'applyform',
formdata: applyformData,
ajax_nonce : myajax.ajax_nonce
},
在您的function.php文件中
add_action('wp_enqueue_scripts', 'my_ajax_scripts');
function my_ajax_scripts(){
......
wp_localize_script( 'myscript', 'myajax', array( 'ajaxurl' => admin_url( '/admin-ajax.php' ), 'ajax_nonce' => wp_create_nonce('security') );
}
function applyform(){
check_ajax_referer( 'security', 'ajax_nonce' );
.......
}
进一步检查wordpress文档:WP admin ajax