samedi 29 novembre 2014

create post using Ajax


I want to create post using Ajax .


I had followed the process from Insert Post using Ajax But i couldn't make it work. please help me out .


Here is the things i did , Please see what I did wrong as i am just a learner .


In WordPress page Template



$j=jQuery.noConflict();
$j(document).ready(function(){
$j("#enqform").validate({
submitHandler: function () {
dataString = $j("#enqform").serialize();
$.ajax({
type: "POST",
url: "http://localhost/wso/wp-admin/admin-ajax.php",
data : {action: "admin_ajax_enqform" }

});
}
})
});
</script>

<form action="<?php the_permalink(); ?>" class="contact-box" id="enqform" method="post">
<label for="firstname">First Name<span class="req">*</span></label>
<input type="text" id="firstname" name="firstname" value="<?php if(isset($_POST['firstname'])) echo $_POST['firstname'];?>" class="required" />

<input type="hidden" name="submitted" id="submitted" value="true" />

<input type="hidden" name="action" value="admin_ajax_enqform" />
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'form-nonce' );?>" />

<input type="submit" id="submit-btn" value="Submit" />
</form>


In WordPress Function.php



add_action( 'admin_ajax_enqform', 'wpse_126886_ajax_handler' );

function wpse_126886_ajax_handler() {

if(isset($_POST['submitted'])) { //validations

if(trim($_POST['firstname']) === '') {
$hasError = true;
} else {
$firstname = trim($_POST['firstname']);
}


// maybe check some permissions here, depending on your app

global $wpdb;
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'form-nonce' ) ) {
die( 'Security check' );
} else {
$new_post = array(
'post_title' => $firstname,
'post_status' => 'publish',
'post_type' => 'post'
);
$pid = wp_insert_post($new_post);
if( $pid ) {
add_post_meta( $pid, 'cpt_firstname', $firstname, true );
}


// send some information back to the javascipt handler
$response = array(
'status' => '200',
'message' => 'OK',
'new_post_ID' => $pid
);


}




// normally, the script expects a json respone
header( 'Content-Type: application/json; charset=utf-8' );
echo json_encode( $response );

exit; // important
}
}


thanks in advance .





Aucun commentaire:

Enregistrer un commentaire