I want to publish wordpress post from front end but I am getting error 400 bad request. I have added both hooks in my php file as well. Please let me know where I am mistaken.
PHP code has two functions. 1 for adding form on front end and my ajax handler for handling ajax request. If I use core PHP, I got no error but I want to use ajax just to avoid reloading. Here I am stuck and need help from an expert. I would appreciate any help, hint or link to to useful resource.
AJAX Code:
jQuery(document).ready(function($) {
$('#submit').on('click', function(e){
e.preventDefault();
let title = $('#title').val();
let content = $('#content').val();
var formData = new FormData();
formData.append('image', document.getElementById('image-input').files[0]);
formData.append('var1', title);
formData.append('var2', content);
$.ajax({
url: 'http://localhost/wpdemo/wp-admin/admin-ajax.php',
type: 'POST',
data: formData,
processData: false, //add this
contentType: false, //and this
success: function(response) {
console.log(response);
}
});
})
});
PHP Code:
<?php
/*
Plugin Name: Notification Plugin Beta Version
Plugin URI: https://www.amirsandila.com/
Description: My first ever plugin n history of technology. You will love this plugin.
Version: 1.0
Author: Amir Sandila
Author URI: https://www.amirsandila.com
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: amirsandila
Domain Path: /languages
*/
define("version", strtotime(date("Ymd")));
function my_theme_enqueue_scripts() {
wp_enqueue_script( 'custom-jquery', 'https://code.jquery.com/jquery-3.5.1.min.js', array(), version, true );
wp_enqueue_script('ajax-script', '/wp-content/plugins/wp-plugin-demo/js/script.js',array(), version, true );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( '/admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
function my_ajax_handler() {
if (isset($_FILES['image'])){
$post_title = $_POST['var1'];
$image = $_FILES['image'];
$post_content = $_POST['var2'];
$new_post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_name' => 'pending',
);
$pid = wp_insert_post($new_post);
add_post_meta($pid, 'meta_key', true);
if (!function_exists('wp_generate_attachment_metadata'))
{
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES)
{
foreach ($_FILES as $file => $array)
{
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK)
{
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $pid );
}
}
if ($attach_id > 0)
{
//and if you want to set that image as Post then use:
update_post_meta($pid, '_thumbnail_id', $attach_id);
}
}
}
add_action("wp_ajax_my_ajax_handler", "my_ajax_handler");
add_action("wp_ajax_nopriv_my_ajax_handler", "my_ajax_handler");
function form_shortcode_func() {
$output = '<style>
.form-container {
width: 70%;
margin: 0 auto;
border: 1px solid #ccc;
padding: 20px;
}
.form-container input[type="text"], .form-container textarea {
width: 100%;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
.form-container input[type="submit"] {
background-color: #333;
color: #fff;
border: 0;
padding: 10px 20px;
cursor: pointer;
}
</style>
<h2> Sumit Your Article! </h2>
<div class="form-container">
<form method="POST" enctype="multipart/form-data">
<input type="text" id="title" name="title" placeholder="Post Title">
<textarea name="message" id="content" rows="20" cols="30" placeholder="Post Body"></textarea>
<input type="file" id="image-input" name="image">
<button id="submit"> submit </button>
</form>
</div>';
return $output;
}
add_shortcode('form', 'form_shortcode_func');
?>
you are missing the action parameter so wordpress doesnt know which function you want.
in your js:
var formData = {
'action' : 'my_ajax_handler',
image: document.getElementById('image-input').files[0],
var1: title,
var2: content
};
$.ajax({
//Do your ajax
});
you should really be defining your ajax url differently:
$.ajax({
url: my_ajax_object.ajax_url,
//Do your ajax
});
Related
This is for WordPress, just to make that clear. I'm asking here since I suspect that I need to provide a bounty on this question (worth 400).
I need to add AJAX to my form submit to avoid page reload / page refresh. I have tried several different versions and none of them are working.
The general idea here is to protect parts of a post whereof that part is code wrapped in <pre> and <code> tags.
These tags are from the prismjs highlighter and looks like this:
<pre><code class="language-php">code here</code></pre>
These tags have four different classes;
PHP
HTML
CSS
JS
This is why the preg_replace uses the ('/(<pre[^>]*>\s*<code[^>]*>) formatting as it needs to cover (handle) the class added.
Furthermore, a cookie is set so that once the user has provided a correct password, the password is remembered. The user should not have to re-enter the password each time they view a post with protected content.
I have an empty DIV acting as a placeholder for showing messages (success and error). The idea here is to show an error if the user submits an incorrect password. If the password match, show the content (code).
This is the code I am working on:
add_filter( 'the_content', 'wrap_code_in_shortcode' , 9 );
function wrap_code_in_shortcode( $content ) {
if ( ! in_category( 'premium' ) ) return $content;
$content = preg_replace('/(<pre[^>]*>\s*<code[^>]*>)/',"[protected]$1", $content);
$content = preg_replace('/(<\/code>\s*<\/pre>)/', "$1[/protected]", $content);
return $content;
}
add_shortcode( 'protected', 'protected_function' );
function protected_function($atts, $content=null){
$userpass = isset( $_REQUEST['password']) ? $_REQUEST['password'] : (isset($_COOKIE['userpass']) ? $_COOKIE['userpass'] : NULL );
if ( in_array( $userpass, array('testpw') ) ) {
$return_code = do_shortcode( $content );
} else {
$return_code = '<div style="margin-top:20px; font-size:15px">Submit password to view.</div>
<div id="errorPWdata"></div>
<form method="post" onsubmit="protectedFunction(this);">
<input required style="display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;" type="text" placeholder=" Password Here" name="password" id="userpass">
<input style="display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;" id="protectedButton" type="submit" value="Submit">
</form>';
?>
<script>
function protectedFunction(form) {
$('#protectedButton').on( 'click', function(e) {
e.preventDefault();
$.ajax({
success: function(data) {
$("#errorPWdata").html(data);
},
error: function() {
alert("Password record error. Contact the administrator.");
}
});
document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
}
}
</script>
<?php
}
return $return_code;
}
I learned to details your code snippet and notice mistakes.
Please, read everything firstly, then you could try.
Mistake 1
Shortcode has been defined with a wrong function name
add_shortcode( 'protected', 'shortcode_protected' );
Should be replaced with
add_shortcode( 'protected', 'bio_protected_function' );
Mistake 2
Script tag should be replaced by the enqueueing system to guarantee script sequences.
The snippet
<script>
function protectedFunction(form) {
$('#protectedButton').on('click', function (e) {
e.preventDefault();
$.ajax({
success: function (data) {
$("#errorPWdata").html(data);
},
error: function () {
alert("Password record error. Contact the administrator.");
}
});
document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
}
}
</script>
Should be replaced with this one
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script(
'bio-shortcode-protected',
get_theme_file_uri( 'assets/js/bio-shortcode-protected.js' ),
[ 'jquery' ],
'1',
true
);
} );
wp_enqueue_scripts();
An appropriate bio-shortcode-protected.js file should be created
path-to-your-theme/assets/js/bio-shortcode-protected.js (Content of the file in next mistake)
Mistake 3
By default WordPress loads jQuery as a global JavaScript object
jQuery should works meanwhile $ probably won't. The script should start with jQuery wrapper to guarantee $ alias working.
Provided Script has incorrect syntax. There should be a close
parentese symbol )
Better to use submit handler instead of click handler. I simplified your handler by handling submit instead of click. Clicking input button triggers submit and click handler not required.
Finally, the bio-shortcode-protected.js content should be
jQuery(function($){
const settings = window.bioShortcodeData;
function init() {
$('#protectedForm').on( 'submit', function(e) {
e.preventDefault();
const form = this;
$.post({
url: settings['endpoint'],
data: {
'action': settings['action'],
'bio-post-id': settings['post-id'],
'nonce': settings['nonce'],
'password': form.userpass.value,
},
success: function(data) {
if (!data.status) {
alert(data.message);
$('#errorPWdata')
.empty()
.append(data.message);
return;
}
if (data.isValidPassword) {
document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
}
$('#bio-protected-content').replaceWith(data.content);
init() // for reattach submission handler
},
error: function() {
alert("Server error");
}
});
})
}
init();
})
And appropriate little bit improved shortcode template should look like:
function bio_protected_function( $atts, $content = null ) {
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script(
'bio-shortcode-protected',
get_theme_file_uri( 'assets/js/bio-shortcode-protected.js' ),
[ 'jquery' ],
'1',
true
);
wp_localize_script(
'bio-shortcode-protected',
'bioShortcodeData',
[
'post-id' => get_the_ID(),
'nonce' => wp_create_nonce( 'bio-shortcode' ),
'endpoint' => admin_url( 'admin-ajax.php' ),
'action' => 'bio_protected_code'
]
);
} );
wp_enqueue_scripts();
if ( bio_validate_the_password() ) {
return do_shortcode( $content );
}
ob_start();
?>
<div class="bio-protected-content" id="bio-protected-content">
<div style="margin-top:20px; font-size:15px">Submit password to view.</div>
<div id="errorPWdata"></div>
<form method="post" id="protectedForm">
<input required
style="display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;"
type="text" placeholder=" Password Here" name="password" id="userpass">
<input style="display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;"
id="protectedButton" type="submit" value="Submit">
</form>
</div>
<?php
return ob_get_clean();
}
Mistake 4
If the form will be submitted what would heppend - is WordPress starts to build content of the page, firstly header, the content (the_content filter), then footer. And checking password inside shortcode not so good idea. This way sending unnecessary page chunks. The only thing need to fetch by AJAX is clean apropriate post content.
This is where ajax-endpoint comes into play. Endpoint should be created by placing the snippet to functions.php file:
add_action( 'wp_ajax_nopriv_bio_protected_code', 'bio_protected_code_endpoint' );
add_action( 'wp_ajax_bio_protected_code', 'bio_protected_code_endpoint' );
function bio_protected_code_endpoint() {
$is_valid_nonce = wp_verify_nonce( $_REQUEST['nonce'], 'bio-shortcode' );
if ( ! $is_valid_nonce ) {
wp_send_json(
[
'status' => false,
'message' => 'Invalid nonce',
]
);
exit;
}
$post_id = $_REQUEST['bio-post-id'];
$post_type = get_post_type( $post_id );
$available_post_type = 'your-post-type';
if ( $available_post_type !== $post_type ) {
wp_send_json(
[
'status' => false,
'message' => 'Not available post type',
]
);
exit;
}
global $post;
$post = get_post( $post_id );
$content = apply_filters( 'the_content', $post->post_content );
wp_send_json(
[
'status' => true,
'isValidPassword' => bio_validate_the_password(),
'content' => $content
]
);
exit;
}
And password validation function
function bio_validate_the_password() {
$userpass = $_REQUEST['password'] ?? $_COOKIE['userpass'] ?? null;
return in_array( $userpass, [ 'testpw' ] );
}
Last words:
I don't recommend set password in Cookie. It's potential security breach.
Better to set Session password variable. But this way not much better.
There is a good answer why not to store password in Session and what to do instead.
Is it secure to store a password in a session?
Please try with below code.
Shortcode handling part:
// add [protected] shortcode to content.
add_filter( 'the_content', 'wrap_code_in_shortcode' , 9 );
function wrap_code_in_shortcode( $content ) {
if ( ! in_category( 'premium' ) ) return $content;
$content = preg_replace('/(<pre[^>]*>\s*<code[^>]*>)/',"[protected]$1", $content);
$content = preg_replace('/(<\/code>\s*<\/pre>)/', "$1[/protected]", $content);
return $content;
}
// function to check if password is valid
function is_user_password_valid($userpass, $post_id) {
return in_array( $userpass, array('test') );
}
// define shortcode. you can combine(merge) this section with wrap_code_in_shortcode()
add_shortcode( 'protected', 'shortcode_protected' );
function shortcode_protected($atts, $content=null){
$userpass = isset( $_REQUEST['password']) ? $_REQUEST['password'] : (isset($_COOKIE['userpass']) ? $_COOKIE['userpass'] : NULL );
$post_id = get_the_ID();
if ( is_user_password_valid($userpass, $post_id) ) {
$return_code = do_shortcode( $content );
} else {
$return_code =
'<div id="protected-area">
<div style="margin-top:20px; font-size:15px">Submit password to view.</div>
<form method="post" onsubmit="getProtectedContent(event);">
<input required type="text" placeholder=" Password Here" name="password">
<input type="submit" value="Submit">
</form>
</div><!-- end of #protected-area -->';
$return_code .= '<script>
function getProtectedContent(event) {
event.preventDefault();
let password = event.target.elements.password.value;
jQuery.ajax({
url: "' . admin_url('admin-ajax.php') . '" ,
method: "POST",
data: {
action: "get_protected_content",
post_id: ' . $post_id . ',
password
},
success: function(result) {
if (result.success) {
jQuery("#protected-area").html(result.data);
document.cookie = "userpass=" + password + "; path=/";
} else {
alert(result.data);
}
},
error: function() {
alert("Something is wrong.");
}
});
return false;
}
</script>';
}
return $return_code;
}
Ajax Request Handling Part:
add_action( 'wp_ajax_get_protected_content', 'get_protected_content' );
add_action( 'wp_ajax_nopriv_get_protected_content', 'get_protected_content' );
function get_protected_content() {
// validation
if ( empty( $_POST['post_id'] ) ) {
wp_send_json_error( 'Wrong Post ID' );
}
$post_id = (int)$_POST['post_id'];
if ( empty( $_POST['password'] ) || ! is_user_password_valid( $_POST['password'], $post_id ) ) {
wp_send_json_error( 'Wrong Password' );
}
$content = get_post_field( 'post_content', $post_id );
// var_dump($content);
if ( preg_match( '/(<pre[^>]*>\s*<code[^>]*>.*<\/code>\s*<\/pre>)/', $content, $matches ) ) {
wp_send_json_success( apply_filters( 'the_content', $matches[1] ) );
} else {
wp_send_json_error( 'No Protected Content Found' );
}
}
Hope this code help you.
Good day. I want to make my column char working with database but I got this error says "Uncaught ReferenceError: year is not defined". here is my code.
JAVASCRIPT
function year()
{
var e = document.getElementById("selectyear");
var year = e.options[e.selectedIndex].text;
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('chartcontroller/chart/')?>/" + year,
type: "GET",
dataType: "JSON",
success: function(data)
{
drawChart1(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1(data) {
var data = google.visualization.arrayToDataTable([
['Courses', 'S.Y. 2011-2012', 'S.Y. 2012-2013','S.Y. 2013-2014'],
for(var i = 1; i < data.length; i++) {
comment = data[i];
[comment.Course, comment.year_a, comment.year_b, comment.year_c],
}
]);
var options = {
title: 'ColumnChart',
hAxis: {title: 'Courses', titleTextStyle: {color: 'blue'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
//ajax end
and my view html
<div class="grid text-center" style="display: block;">
<h1 style=" color: black; font-size: 18px;">Summary of Daily Utilization of Library Holdings per Department</h1>
<div class="input-group">
<span class="input-group-addon">#</span>
<select id="selectyear" class="form-control selectyear" data-mobile="true" name="year" onchange="year();">
<?php
for ($i=$min_year; $i <= $max_year; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
</div>
<h1 style=" color: gray; font-size: 14px;">S. Y. 2011-2012, 2012-2013 & 2013-2014</h1>
<div id="chart_div1" class="chart" style="height: 400px; width: 100%;"></div>
<div id="chart_div2" class="chart" style="height: 400px; width: 100%;"></div>
in my controller
public function chart($year)
{
$data = $this->views->chart($year);
//Either you can print value or you can send value to database
echo json_encode($data);
}
no problem with ajax because when I do a debugging ajax successfully retrieve the value from database, the problem is when I put that value to my column chart like what I did in my code I've got that error.. help me please. this is the last problem I have to my thesis project.. thanks. I want to change the column chart value if the drop down has change.
I have the following ajax call:
$( document ).ready(function() {
$( "#fform" ).submit(function( event ) {
//alert( "Handler for .submit() called." );
event.preventDefault();
$.ajax({
type: "POST",
url: "apply.php",
data: "email="+$("#emaill").val()
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
}).fail(function() {
alert("Sorry. Server unavailable. ");
});
});
});
and in apply.php:
$con=mysqli_connect("some_server","some_usename","some_pass","some_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$r=mysqli_query($con,"INSERT INTO some_table (email, join_date) VALUES ('".$_POST['email']."', CURDATE() )");
if($r)
{
echo 'true';
}
else
{
echo 'false';
}
mysqli_close($con);
The wierd thing is that I get the email in the DB but I'm not getting any alert! please help!
UPDATE:
The form:
<form method="POST" id="fform" >
<fieldset class="clearfixx" style="width: 552px; height: 40px;">
<div class="lp-pom-form-field clearfixx" style="width: 552px; height: 42px; top: 0px;">
<input placeholder="Email Address" type="email" id="emaill" name="email" class="textt" style="top: 0px; left: 58px; width: 520px; font-size: 15px; height: 38px; padding-left: 11px; padding-right: 11px; lineheight: 15px;" required>
</div>
</fieldset>
<input type="submit" class="lp-element lp-pom-button" id="lp-pom-button-25" value="Submit dude"/>
</form>
I get the data on DB after clicking the submit button but I don't get any alerts. Thank you
UPDATE 2:
error: Uncaught TypeError: Object # has no method 'done'
SOLVED
I was using an old version of JQuery thank you all
well the ajax function will only work if the form #fform is submitted.
put a submit button in your form:
<input type="submit" value="submit" />
clicking on the submit button should trigger your function
http://jsfiddle.net/Ashkanvb/4HpG5/
You have a little mistake in your jQuery AJAX call, try this :
$.ajax({
type: "POST",
url: "apply.php",
data: "email="+$("#emaill").val()
}).done(function( msg ) {
alert( "Data Saved: " + msg );
}).fail(function() {
alert("Sorry. Server unavailable. ");
});
I suggest you to use a debug tool like firebug or the chrome developper tool, which permit to easily detect this kind of syntax errors.
I have this code for form submit:
index.php
<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
var tvyalner = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "postForm.ajax.php",
data: tvyalner,
dataType: "json",
success: function(data){
$("#formResponse").removeClass('error');
$("#formResponse").addClass(data.status);
$("#formResponse").html(data.message);
if(data.status === 'success'){$("#myForm table").hide();}
},
error: function(){
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>
<style type="text/css">
.success{
border: 2px solid #009400;
background: #B3FFB3;
color: #555;
font-weight: bold;
}
.error{
border: 2px solid #DE001A;
background: #FFA8B3;
color: #000;
font-weight: bold;
}
</style>
</head>
<body>
<div class="mfm">
<form id="myForm" name="myForm" method="post" action="" style="margin: 0 auto; width: 300px;">
<div id="formResponse"></div>
<table>
<tr><td>Name:</td><td><input name="name" type="text" value=""></td></tr>
<tr><td>Email:</td><td><input name="email" type="text" value=""></td></tr>
<tr><td>Message:</td><td><textarea name="message" rows="5" cols="20"></textarea></td></tr>
<tr><td> </td><td><input type="submit" name="submitForm" value="Submit Form"></td></tr>
</table>
</form>
</div>
</body>
</html>
postForm.ajax.php
<?php
//function to validate the email address
//returns false if email is invalid
function checkEmail($email){
if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = split("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the email field
} elseif(!checkEmail($_POST['email'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
//check the message field
} elseif(empty($_POST['message'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated. send email
} else {
//send the email
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
After first submit displaying:
Name is blank.
Filling field and submitting again. displaying
There was an error submitting the form. Please try again.
and that's all.
Code not working in localhost.
What is the problem?
I suggest using this error-function to see what the error is:
$.ajax({
/* ... */
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown); // Or use alert()
console.log(textStatus);
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
i have problem using form in codeigneter when to submit value from div html,
example view
<label for="title">Title:</label>
<input type="text" class="form_field" id="title" name="title" size="30" value="<?php echo set_value('title', isset($default['title']) ? $default['title'] : ''); ?>" />
<div class="form_field" name="contentbox" id="contentbox" contenteditable="true">
<?php echo set_value('contentbox', isset($default['contentbox']) ? $default['contentbox'] : ''); ?></div>
in div id="contentbox" is set contenteditable="true", and i will get dinamic value,
controller
....
$data = array( 'title' => $this->input->post('title'),
'content' => $this->input->post('contentbox'));
$this->my_model->add($data);
....
but in controller i can't get value div id="contentbox" , i have problem input to database,when i'm typing "sometext" in div id="contentbox" value always "0"
You can use the jquery cookie plugin to grab CI csrf token and include it before this function
jQuery
(function($){
var do_ajax = function(data, scope){
// depending on your version of CI csrf token name will differ
// newer versions of CI use the name in your application/config file
data = {content : data, csrf_token : $.cookie('csrf_token')}
$.ajax({
url : BASE_PATH + 'some_class/some_method',
data: data,
context : scope,
type : 'POST',
dataType : 'json',
success : function(callback){
//check the status first!
var $this = $(this);
$this.find(".msg").fadeIn();
$this.find("#contentbox").html(data);
}
});
}
var contents = {
init: function(){
if($("#editme"))
this.contentEditable();
},
contentEditable : function(){
var scope = $("#editme"),
eicon = $(".icon-editable").hide(),
emessage = $(".msg").hide(),
econtent = $("#contentbox");
econtent.hover(function(){
eicon.show();
}, function(){
eicon.hide();
});
econtent.blur(function(){
do_ajax($(this).html(), scope);
});
}
}
$(function(){
contents.init();
});
})(jQuery);
HTML
<div id="editme" class="editme">
<span class="icon-editable">✎</span>
<span class="msg">Content updated!</span>
<h4>Some relevant title</h4>
<div id="contentbox" class="contentbox" contenteditable="true">
This is editable...
</div>
</div>
CSS
div.editme{
position:relative;
background:#ffffff;
padding:30px 8px 8px 8px;
}
span.icon-editable, span.msg{
position:absolute;
top:0;
}
span.icon-editable{
left:0;
border:1px solid #d1d1d1;
border-top:0;
border-left:0;
font-size:1em;
line-height:1.2em;
}
span.msg{
right:0;
font-size:0.8em;
line-height:1.2em;
color:#fafafa;
background:green;
padding:3px;
}
PHP
class some_class extends Controller{
public function some_method(){
if($this->input->is_ajax_request())
{
$data = array(
'content' => $this->input->post('content')
);
if($this->my_model->add($data))
{
$responce = array(
'status' => 'ok'
);
}
else
{
$responce = array(
'status' => 'notok'
);
}
echo json_encode($responce);
}
else
{
show_404();
}
}
}
Test version without ajax request
CLICK HERE