Answer the question
In order to leave comments, you need to log in
Why are posts not being created without reloading?
Good afternoon! For a day now I can not understand why it does not work.
On the main page of the site, I created a form for adding 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="Наименование" autocomplete="off">
</fieldset>
</div>
<button type="button" id="custom_button" class="btn btn-primary col-12">Добавить</button>
</form>
if(!function_exists('my_custom_script')):
function my_custom_script(){
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');
}
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);
}
});
});
});
Answer the question
In order to leave comments, you need to log in
You don't understand how ajax works. You sent the data, the post was created. But in order to see updates on the page / pages that are ALREADY loaded in the browser, you need to either manually update them, or generate the necessary html from the response received via Ajax and insert it into these pages (you can only in the one from which you initiated the download). If you want open pages in other tabs to update themselves when new data appears on the backend, then you need other technologies. Read about web sockets.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question