Good day! Which day can not understand why is not working.
On the main page of the website has created a form to add a post:
<form action="#" method="post" enctype="multipart/form-data">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
<fieldset>
<input type="text" class="form-control" name="titleObject" id="titleQ" placeholder="Name" autocomplete="off">
</fieldset>
</div>
<button type="button" id="custom_button" class="btn btn-primary col-12">Add</button>
</form>
In function.php put this code:
if(!function_exists('my_custom_script')):
my_custom_script function(){
wp_enqueue_script( 'jquery' );
wp_enqueue_script('customajax', get_stylesheet_directory_uri() . '/js/custom.js', array(), 1.0,false
);
wp_localize_script('customajax', 'ajjax', array(
'url' => admin_url( 'admin-ajax.php' ),));
}
endif;
add_action('wp_enqueue_scripts','my_custom_script');
if(!function_exists('ret')) {
function ret()
{
$asd = $_POST["titleObject"];
$my_post = array(
'post_title' => $asd,
'post_content' => 'test',
'post_type' => 'post',
'post_status' => 'publish',
'post_author' => '1'
);
$post_ID = wp_insert_post( $my_post );
echo $post_ID;
wp_die();
};
}
if( defined('DOING_AJAX') ) {
add_action('wp_ajax_qwas', 'ret');
add_action('wp_ajax_nopriv_qwas', 'ret');
}
In the js file:
jQuery(function(jQuery) {
jQuery('#custom_button').click(function () {
var titleObject = jQuery("#titleQ").val();
jQuery.ajax({
type: "POST",
data: {
action: 'qwas',
titleObject: titleObject,
},
url: ajjax.url
cache: false,
success: function ( response ) {
console.log(response);
}
});
});
});
When I enter this into the box and press the button in the console see a message which displays the id of the post, but in admike and post database is not created immediately, but only after updating the data pages. But there should be using ajax to create posts without a reboot. Can't understand why. I would be grateful for help.