Protect Post Content and Avoid Page Refresh using AJAX upon Password Submit - ajax

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.

Related

Why it is a bad request Ajax WordPress?

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
});

Wordpress Sending email through Ajax without page refresh hangs on admin_ajax.php

I have this test page on a website - https://piclits.com/test-slideshow/
It displays a bunch of images/PICLITS and grabs them randomly from a folder 12 at a time into a slideshow.
I want to email the main image without refreshing the page (which would bring up 12 new images) from the email button which opens up a popup to add email addresses.
All is good - I can grab the image and mail it but the script does something wacky where it flashes on the page and then hangs up at admin-ajax.php rather than just staying on the page and sending the email.
My Form:
<div class="ajax-form-container" style="float: left">
<form id="ajaxformid" action="" method="POST">
<p>Email this PIC-LIT to a friend.<br />You may include multiple emails if you separate them with a comma.</p>
<ul style="list-style-type: none;">
<li>Email: <textarea name="piclit_email" id="piclit_email" rows="4" cols="50" autofocus=""></textarea><input type="hidden" name="founder_piclit" id="founder_piclit" value=""></li>
<li><input type="hidden" name="piclit_bcc" class="piclit_bcc" value="0"></li>
<li>bcc: <input type="checkbox" name="piclit_bcc" class="piclit_bcc" value="1">
<?php wp_nonce_field( 'fiveb_ajax_nonce', 'fiveb_nonce_field' ); ?></li>
<li><input type="submit" name="submit" value="Send"></li>
</ul>
</form>
<div id="ajax_success" style="display: none">Email sent.</div>
<div id="ajax_error" style="display: none">There was an error. Sorry your email was not sent.</div>
</div>
Javascript
<script>
jQuery('#ajaxformid').submit(function(e) {
e.preventDefault();
var piclit_email = jQuery( "#piclit_email" ).val();
if (piclit_email == '')
alert("Please fill in all fields to send an email.");
else {
var founder_piclit = jQuery( "#founder_piclit" ).val();
// alert (founder_piclit);
var piclit_bcc = jQuery('.piclit_bcc').val();
var formData = {
piclit_email: piclit_email,
founder_piclit: founder_piclit,
piclit_bcc: piclit_bcc,
action: 'fiveb_ajax_mail',
};
jQuery.ajax({
type : 'POST',
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>',
dataType : 'json',
data : formData,
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
}
});
</script>
and php:
function fiveb_function() {
$subject = 'View A Founder PIC-LIT from piclits.com';
$piclit_email = strval($_REQUEST['piclit_email']);
$founder_piclit = strval($_REQUEST['founder_piclit']);
$piclit_bcc = strval($_REQUEST['piclit_bcc']);
if ($piclit_bcc) {
$headers[] = 'Bcc: '.$piclit_email;
}
$message = '<html><head><title>Founder PIC-LIT</title></head><body><table border="0" cellspacing="2" cellpadding="20" bgcolor="#ffffff" width="100%"><tbody><tr><td></td><td width="600"><p style="text-align: center">Hello!<br />View A Founder PIC-LIT from piclits.com.</p></td><td></td></tr><tr><td></td><td><img src="'.$founder_piclit.'" alt="Founder PIC-LIT" width="600" style="display:block;width:100%" /></td><td></td></tr></tbody></table></body></html>';
$headers[] = 'From: PIC-LITS <hello#piclits.com>';
$headers[] = 'Content-Type: text/html; charset=UTF-8';
if ($bcc) $sent_mail = wp_mail( "", "$subject", $message, $headers );
else $sent_mail = wp_mail( "$piclit_email", "$subject", $message, $headers );
if ($sent_mail) {
echo ('email sent');
die();
} else {
echo ('There was an error. Sorry your email was not sent.');
die();
}
}
add_action("wp_ajax_fiveb_function", "fiveb_function");
add_action("wp_ajax_nopriv_fiveb_function", "fiveb_function");
Seems like I am so close but I cannot get the script to stop hanging up on admin-ajax.php. Any help would be so appreciated! Maybe it has something to do with my popup? I am out of ideas
Your code will look like this.
Note - Form action should be blank.
<form action="" method="POST" id="ajaxformid">
</form>
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
wp_localize_script( 'custom-js', 'fiveb_ajax_mail', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
add_action("wp_ajax_fiveb_ajax_mail", "fiveb_ajax_mail");
add_action("wp_ajax_nopriv_fiveb_ajax_mail", "fiveb_ajax_mail");
function fiveb_ajax_mail()
{
$formdata = $_post['formdata'];
wp_mail($to,$subject,$message,$header);
return 'true';
wp_die();
}
//add below js in custom.js file
$('#ajaxformid').submit(function (e) {
e.preventDefault();
jQuery.ajax({
type: "post",
dataType: "json",
url: fiveb_ajax_mail.ajax_url,
data : {action: "fiveb_ajax_mail","formdata":"your form data variable place here"},
success: function(msg){
console.log(msg);
}
});
}
In my local system, it is working fine.

woocommerce product sort order change by our own weight value or menu order

I need to add a specified value or weight for a product so that product will display as per order on the woocommerce shop page. I think this can be done by product bulk edit. But not sure is it right or any conflict may arise in the future. can anyone suggest how I a custom sort function as per a given value for the bulk products? Currently, the drag and drop method is difficult in the case of thousand of products.
add_action( 'woocommerce_product_bulk_edit_start', 'custom_field_product_bulk_edit', 10, 0 );
function custom_field_product_bulk_edit() {
?>
<div class="inline-edit-group">
<label class="alignleft">
<span class="title"><?php _e('Custom Sort Weight', 'woocommerce'); ?></span>
<span class="input-text-wrap">
<select class="change_t_dostawy change_to" name="change_t_dostawy">
<?php
$options = array(
'' => __( '— No change —', 'woocommerce' ),
'1' => __( 'Change to:', 'woocommerce' ),
);
foreach ( $options as $key => $value ) {
echo '<option value="' . esc_attr( $key ) . '">' . $value . '</option>';
}
?>
</select>
</span>
</label>
<label class="change-input">
<input type="text" name="_t_dostawy" class="text t_dostawy" placeholder="<?php _e( 'Enter Weight Here ', 'woocommerce' ); ?>" value="" />
</label>
</div>
<?php
}
// Save the custom fields data when submitted for product bulk edit
add_action('woocommerce_product_bulk_edit_save', 'save_custom_field_product_bulk_edit', 10, 1);
function save_custom_field_product_bulk_edit( $product ){
if ( $product->is_type('simple') || $product->is_type('external') ){
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
if ( isset( $_REQUEST['_t_dostawy'] ) ){
// update_post_meta( $product_id, 'menu_order', sanitize_text_field( $_REQUEST['_t_dostawy'] ) );
$arg=array('ID' => $product_id,'menu_order' => $_REQUEST['_t_dostawy']);
$result = wp_update_post($arg);
}
}
}
I have added an option on quick edit and then update the menu order value by ajax. so that all the product having same menu order will be displayed on same row.But this is not a correct way.
So I have do other stuff that added text box in the product listing and where we can add a menu order for product.
//
Add product new column in administration
add_filter( 'manage_edit-product_columns', 'woo_product_weight_column', 20 );
function woo_product_weight_column( $columns ) {
$columns['sort_weight'] = esc_html__( 'Weight', 'woocommerce' );
return $columns;
}
// Populate weight column
add_action( 'manage_product_posts_custom_column', 'woo_product_weight_column_data', 2 );
function woo_product_weight_column_data( $column ) {
global $post;
if ( $column == 'sort_weight' ) {
$postval = get_post( $post->ID);
$menu_order_new = $postval->menu_order;
?>
<input type="text" name="menuorder" id="id_<?php echo $post->ID;?>" data-productid="<?php echo $post->ID;?>" value="<?php echo $menu_order_new; ?>" class="menuorder"/>
<?php
}
}
add_action('admin_head', 'my_column_width');
function my_column_width() {
echo '<style type="text/css">';
echo 'table.wp-list-table .column-sort_weight { width: 101px; text-align: left!important;padding: 5px;}';
echo 'table.wp-list-table .column-wpseo-score { width: 101px; text-align: left!important;padding: 5px;}';
echo'.menuorder{ width: 101px; }';
echo '</style>';
}
// this code adds jQuery script to website footer that allows to send AJAX request
add_action( 'admin_footer', 'misha_jquery_event' );
function misha_jquery_event(){
echo "<script>jQuery(function($){
var weight_val;
var pr_id;
jQuery('.menuorder').on('input', function(){
weight_val = $(this).val();
pr_id=$(this).attr('data-productid');
var dataVariable = {
'action': 'productmetasave',
'product_id': pr_id,
'value':weight_val
};
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: dataVariable,
success: function (response) {
if(response==1){
location.reload(true);
}else{
console.log('Failed To update menu-order ');
}
}
});
});
});</script>";
}
// this small piece of code can process our AJAX request
add_action( 'wp_ajax_productmetasave', 'misha_process_ajax' );
function misha_process_ajax(){
if($_POST['product_id'] && $_POST['value'] ){
$arg=array('ID' => $_POST['product_id'],'menu_order' => $_POST['value']);
$rs = wp_update_post($arg);
if($rs){
echo "1";
}else{
echo "0";
}
}
die();
}

Autocomplete Jquery dataSource with JSON

I'm using the autocomplete widget of JQuery using JSON to parsed the db information but doesn't work. There are lots of questions like mine but I've not been able to find a solution. My php file with JSON parsed is this:
This error appears in a browser console, in first line of php:
Uncaught SyntaxError: Unexpected token <
The php file peliculas.php
<?php
function makeSqlConnection()
{
$SERVIDOR_MYSQL = "localhost";
$BASE_DATOS = "db";
$USUARIO_MYSQL = "root";
$PASSWORD_MYSQL = "";
$con = mysql_connect($SERVIDOR_MYSQL,$USUARIO_MYSQL,$PASSWORD_MYSQL) or die(mysql_error());
mysql_select_db($BASE_DATOS,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
$con = makeSqlConnection();
$term = trim(strip_tags($_GET['term']));
$result = mysql_query("SELECT PYS_STR, PYS_TITULO FROM pys WHERE PYS_STR LIKE '%".$term."%';", $con);
$informacion = array();
while($row = mysql_fetch_assoc($result))
{
array_push($informacion, array('label' => $row['PYS_TITULO'], 'value' => $row['PYS_STR']));
}
echo json_encode($informacion);
?>
JSON returns this:
[{"label":"Reservoir Dogs","value":"reservoirdogs"},{"label":"Machete","value":"machete"},{"label":"Wall Street","value":"wallstreet"},{"label":"Django Desencadenado","value":"djangodesencadenado"},{"label":"The Wire","value":"thewire"},{"label":"This Is England '88","value":"thisisengland88"}]
This is my script:
$(function() {
$( "#peliculas" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/bundles/pys/php/peliculas.php",
dataType: "json",
data: {terms: request.term},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.label,
value: item.value
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
and this is my html code:
<div class="ui-widget">
<label for="peliculas">Peliculas: </label>
<input id="peliculas" />
</div>
<div class="ui-widget" style="margin-top: 2em; font-family: Arial;">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
SOLUTION
I've solved the error. The problem was in the location of peliculas.php; Symfony2 was detecting this php file like js file in the /resource/public/js directory. When I've changed the php file to a new directory and I've updated the url parameter in the script, it has worked fine.
The second problem was in the dataparameter:
data: {terms: request.term}, when I replaced terms with term the filtering worked fine.
It seems that it is not working as expected because comma is missing
label: item.label,
value: item.value
Two things to check:
1) Please check your editor if it automatically inserts a Unicode Signature (BOM) in your files.
http://www.w3.org/International/questions/qa-byte-order-mark#detect
You may have a BOM (byte-order-mark) character at the beginning of your php file peliculas.php that causes problems to the output.
Quick fix for this if you cant find setting to remove BOM:
Copy - Paste all the contents of your php file to an empty file in notepad++, and save the file as UTF-8 (notepad++ does not write BOM)
2) add the application/json header before the json_encode
header('Content-Type: application/json');
echo json_encode($informacion);

submit form from <div> html value in codeigneter

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

Resources