Implementing CodeMirror into Widget backend form not updating texarea - javascript

I'm trying to wrap my head around how this actually works in wordpress on the admin back end for a widget I'm trying to create (similar to the custom HTML widget). I've read a few tutorials but the information seems to change and I feel I have just confused myself.
Everything works fine while initializing codemirror and it is applied to the textarea but the errors I'm having are:
When new html is entered into codemirror the save button for the widget doesn't activate.
If I change another field to activate the save button the data from codemirror is not sent or saved.
(function ($) {
$(document).ready( function(){
var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
editorSettings.codemirror = _.extend(
{},
editorSettings.codemirror,
{
lineNumbers: true,
mode: "text/html",
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
}
);
var editor = wp.codeEditor.initialize( $('#<?php echo $textarea_id; ?>'), editorSettings );
});
})(jQuery);
</script>
I've also tried adding:
$(document).on('keyup', '.CodeMirror-code', function(){
editor.codemirror.save();
$('#<?php echo $textarea_id; ?>').html(editor.codemirror.getValue());
});
but editor.codemirror.getValue() return empty when I display through console.log
Code for Textarea
<p>
<label for="<?php echo $textarea_id; ?>"><?php _e( 'Locked Content:' ); ?></label>
<textarea id="<?php echo $textarea_id; ?>" name="<?php echo $this->get_field_name( 'locked-content' ); ?>" class="widefat"><?php echo esc_textarea( $instance['locked-content'] ); ?></textarea>
</p>
Any help (links to a proper tutorial, advice etc) would be much appreciated JS isn't my strongest language.

I believe this came down to me being an idiot lol I was calling this same block of code from another widget as I was trying to make both widgets textareas into codemirrors.
I changed the name of 2 variables to be more specific towards the widget eg:
var editorSettings
var editor
where changed to:
var cm_editorSettings
var cm_editor
This allowed me to us cm.editor.codemirror.getValue() and return the actual value. Still not sure if this is the correct way to implement it so please correct me if I am wrong but currently the working code to update the textarea and enable save button is as follows
<script type="text/javascript">
(function ($) {
$(document).ready( function(){
var cm_editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
cm_editorSettings.codemirror = _.extend(
{},
cm_editorSettings.codemirror,
{
lineNumbers: true,
mode: "text/html",
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
}
);
var cm_editor = wp.codeEditor.initialize($('#<?php echo $textarea_id; ?>') , cm_editorSettings );
$(document).on('keyup', '.CodeMirror-code', function(){
$('#<?php echo $textarea_id; ?>').html(cm_editor.codemirror.getValue());
$('#<?php echo $textarea_id; ?>').trigger('change');
});
});
})(jQuery);

Related

How to add wp_editor in custom widget

I an trying to create a image widget with wp editor. I see the editor but i cant the text like make it bold or bigger nither i see the tab switch from visual to text. Following is my code:
Thanks in advance.
<input type="hidden" id="<?php echo esc_attr($this->get_field_id('description')); ?>" name="<?php echo esc_attr($this->get_field_name('description')); ?>" value="<?php echo esc_attr($instance['description']); ?>" />
<?php
$edi_name = esc_attr($this->get_field_name('description'));
$content = $instance['description'];
$editor_id_new = esc_attr($this->get_field_id('description'));
$settings = array( 'media_buttons' => false,
'textarea_rows' => 6,
'textarea_name' => $edi_name,
'teeny' => false,
'menubar' => false,
'default_editor' => 'tinymce',
'quicktags' => false
);
wp_editor( $content, $editor_id_new, $settings );
?>
<script>
(function($){
tinyMCE.execCommand('mceAddEditor', false, '<?php echo $this->get_field_id('description'); ?>');
})(jQuery);
</script>
Short answer: Because there is a hidden widget where the TinyMCE appears first.
Long answer (sorry, a very long answer):
Go to the Codex and copy the example widget Foo_Widget to make sure we are talking about the same code. Now open your IDE (not an editor) and write a short testing widget as plugin. Starting with a minimal plugin header...
<?php
/*
Plugin Name: Widget Test Plugin
Description: Testing plugincode
*/
... adding the widget code from the codex and registering the widget with the add_action() call. Now modify the form method within the widget class as shown here:
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'text_domain' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
/*** add this code ***/
$content = 'Hello World!';
$editor_id = 'widget_editor';
$settings = array(
'media_buttons' => false,
'textarea_rows' => 3,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings );
/*** end editing ***/
}
Go to your blog, activate the plugin, go to the widget page and drag the Foo Widget into a sidebar. You will see it will fail.
Do you see the Foo Widget description on the left side? Do a right click on the description and choose 'Inspect' from your developer tools (you have some developer tools like FireBug or Chrome DevTools, huh? In FireFox you can also choose the build in 'Inspect Element'). Browse through the HTML code and you will see there is an editor wrap inside the 'hidden' widget.
You can see one editor in the sidebar on the right and there is an editor in the 'hidden' widget on the left. This cannot work properly because TinyMCE don't know which editor should be used.
What do we need?
We need a unique ID for our editor.
/*** add this code ***/
$rand = rand( 0, 999 );
$ed_id = $this->get_field_id( 'wp_editor_' . $rand );
$ed_name = $this->get_field_name( 'wp_editor_' . $rand );
$content = 'Hello World!';
$editor_id = $ed_id;
$settings = array(
'media_buttons' => false,
'textarea_rows' => 3,
'textarea_name' => $ed_name,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings );
/*** end edit ***/
Modify the code within the form method again with the code above. We create a unique number with rand() and append this number to the id and name attributes. But stop, what about saving the values???
Go to the update method and add die(var_dump($new_instance)); in the first line. If you press Save on the widget, the script will die and print out the submitted values. You will see there is a value like wp_editor_528. If you reload the page and save the widget again, the number will be changed to something else because it is a random number.
How will I know which random number was set in the widget? Simply send the random number with the widget data. Add this to the form method
printf(
'<input type="hidden" id="%s" name="%s" value="%d" />',
$this->get_field_id( 'the_random_number' ),
$this->get_field_name( 'the_random_number' ),
$rand
);
In the update routine, we can now access the random number with $new_instance['the_random_number']; and so we can access the editor content with
$rand = (int) $new_instance['the_random_number'];
$editor_content = $new_instance[ 'wp_editor_' . $rand ];
die(var_dump($editor_content));
As you can see, the editor content will be submitted and you can save it or do anything else with it.
Caveat
The editor content is only submitted correctly if the TinyMCE is not in visual mode (WYSIWYG mode). You have to switch to the text mode befor press 'Save'. Otherwise the predefined content (in this case $content = 'Hello World!';) is submitted. I don't now why, but there is a simple workaround for this.
Write a small jQuery script that triggers the click on the 'text' tab before saving the widget content.
JavaScript (saved as widget_script.js somewhere in your theme/plugin folders):
jQuery(document).ready(
function($) {
$( '.widget-control-save' ).click(
function() {
// grab the ID of the save button
var saveID = $( this ).attr( 'id' );
// grab the 'global' ID
var ID = saveID.replace( /-savewidget/, '' );
// create the ID for the random-number-input with global ID and input-ID
var numberID = ID + '-the_random_number';
// grab the value from input field
var randNum = $( '#'+numberID ).val();
// create the ID for the text tab
var textTab = ID + '-wp_editor_' + randNum + '-html';
// trigger a click
$( '#'+textTab ).trigger( 'click' );
}
);
}
);
And enqueue it
function widget_script(){
global $pagenow;
if ( 'widgets.php' === $pagenow )
wp_enqueue_script( 'widget-script', plugins_url( 'widget_script.js', __FILE__ ), array( 'jquery' ), false, true );
}
add_action( 'admin_init', 'widget_script' );
That's it. Easy, isn't it? ;)
Actual Credit Goes To The Author Of Writting This Test Plugin #Ralf912
Reference URL : Why Can't wp_editor Be Used in a Custom Widget?
I made some improvements to this code in case somebody needs it:
on the form function of the widget I updated the code:
$rand = !empty( $instance['the_random_number']) ? $instance['the_random_number'] : rand( 0, 999 );
$ed_id = $this->get_field_id( 'wp_editor_' . $rand );
$ed_name = $this->get_field_name( 'wp_editor_' . $rand );
$content = !empty( $instance['the_random_number']) ? $instance['wp_editor_' . $rand] : 'Content goes here!';
$editor_id = $ed_id;
$settings = array(
'media_buttons' => true,
'textarea_rows' => 3,
'textarea_name' => $ed_name,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings ); `
And I also reinitialized the editor because it was broken after save
jQuery(document).on('widget-updated', function(e, widget){
if(widget[0].id.includes("cw_pa_text_widget")) { // if it is the right widget
let editor ="widget-" + widget[0].id.substring(widget[0].id.indexOf('_') + 1);
let randNum = editor + "-the_random_number";
let wpEditorId = editor + "-wp_editor_" + document.getElementById(randNum).value;
var settings = {
quicktags: true,
};
wp.editor.initialize(wpEditorId, settings);
//create the ID for the text tab
var textTab = wpEditorId + '-tmce';
// trigger a click
document.getElementById(textTab).click();
}});
Thank you.

(WP) Code works in standalone codepen, but not on live site

I'm working on a gallery of sorts in Wordpress right now and I'm a bit stuck.
The idea is to change the post thumbnail on hover. The replacement image will be coming from a field generated by the Advanced Custom Fields plugin.
Now, I've managed to pull in both URLs and stored them in variables, but I still won't work. It works on a standalone CodePen, but not on the Wordpress site itself.
Wordpress code:
jQuery(document).ready(function() {
var firstthumb = '<?php echo the_post_thumbnail_url(); ?>';
var secondthumb = '<?php if( get_field('multiple_thumbs') ): ?><?php echo the_field('multiple_thumbs'); ?><?php endif; ?>';
jQuery('.member-thumbnail').hover(function() {
jQuery('.attachment-thumbnail').attr('src', secondthumb);
}, function() {
jQuery('.attachment-thumbnail').attr('src', firstthumb);
});
});
And it returns this:
jQuery(document).ready(function() {
var firstthumb = 'http://www.cozeh.com/wp2/wp-content/uploads/2016/01/pic2.png';
var secondthumb = 'http://www.cozeh.com/wp2/wp-content/uploads/2016/01/multiple2.png';
jQuery('.member-thumbnail').hover(function() {
jQuery('.attachment-thumbnail').attr("src", secondthumb);
}, function() {
jQuery('.attachment-thumbnail').attr("src", firstthumb);
});
});
Here's a link to the beta version.
And here's the codepen.
Would appreciate any explanation as to why this doesn't work or if you have any alternative solutions.
Edit: Updated code
The problem is that in the codepen you are not wrapping the img in an a tag, but you are doing it on the WordPress site. So to make it work in wordpress you need to remove the link that is wrapping the image or change you jQuery code, replacing this code:
jQuery('.member-thumbnail').hover(function() {
...
});
To this one:
jQuery('.member-thumbnail a').hover(function() {
...
});
Marking as solved.
Turns out it wasn't a script issue after all.
WP 4.4.+ was appending srcsetto the images as part of their move to make all images responsive. The img srcwas changing but not the srcsethence the problem.
Found a workaround to disabling the responsive images for now.
And I edited the code so it only affects one of the thumbnails, not every single one.
<?php if ( has_post_thumbnail() ) { ?>
<div class="member-<?php the_ID(); ?>-thumbnail">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
var firstthumb = '<?php the_post_thumbnail_url(); ?>';
var secondthumb = '<?php if( get_field('multiple_thumbs') ): ?><?php echo the_field('multiple_thumbs'); ?><?php endif; ?>';
jQuery('.member-<?php the_ID(); ?>-thumbnail').hover(function() {
jQuery('.member-<?php the_ID(); ?>-thumbnail .attachment-thumbnail').attr('src', secondthumb);
}, function() {
jQuery('.member-<?php the_ID(); ?>-thumbnail .attachment-thumbnail').attr('src', firstthumb);
});
});
</script>
Thanks for the input everybody.

Load Wordpress Editor Via Ajax Plugin

I have researched several similar questions on stackoverflow about this topic that already have answers.
Some of the answers don't seem to fully work and some are just over my head.
I have been reading and reworking my code for over a week so I though I would try asking again with more detail than the other questions had.
I've written a very simple WordPress plugin that's only purpose in life is to load a fully functional editor via ajax.
Here is a screencast of this plugin working (with errors):
http://screencast.com/t/eyrTdbUy
I think that if my question can be answered it will help a lot of people.
Here is exactly what the plugin does.
It loads my custom page template instead of the theme template. In this template there is a editor created with the wp_editor function (to load the required files) and a link to add a new editor.
When you click the "add editor" link a new editor is created using the wp_editor function via ajax then initialized with javascript and new link is added to add another.
This only works if a user is logged in.
I wouldn't advise installing this on your active website because it will take over your pages. This plugin is for example only so it should only be installed on tester sites.
Here's the problems...
The first instance of the ajax loaded editor works but there is the following errors when you click the tabs to switch back and forth from visual to text
"TypeError: e is undefined"
"TypeError: c is undefined"
The "TypeError: e is undefined" also happens when the first new editor is loaded.
After the first instance is loaded another editor cannot be added.
So my question is... What is wrong with my code?
The plugin is made up of 4 files.
File 1 is the plugin file "load_editor.php" (it just includes the functions):
include('functions.php');
File 2 is the functions file "functions.php":
<?
// load custom editor template
function load_editor_template( $template )
{
$template = plugin_dir_path( __FILE__ ) . 'template.php';
return $template;
}
add_filter( 'template_include', 'load_editor_template' );
// load javascript
function load_editor_scripts() {
wp_enqueue_script( 'load_editor', plugins_url() . '/load_editor/js/load_editor.js', array(), '', true );
wp_enqueue_script( 'jquery');
}
add_action( 'wp_enqueue_scripts', 'load_editor_scripts' );
// create new editor
function load_editor_new_editor() {
$id = $_POST['id'];
$number = $_POST['number'];
$next = $number + 1;
$full_id = $id.$number;
echo "<h1>Editor $number</h1>";
$content = '<p>This is example content.</p>';
wp_editor($content, $full_id, array('textarea_rows' => 3));
// initiate new editor
echo "<script>
tinyMCE.execCommand('mceAddEditor', true, $full_id);
tinyMCE.init(tinyMCEPreInit.mceInit[$full_id]);
</script>";
// create "add new" text
echo "<div><a onclick=\"load_new_editor('editor', $next);\" href='javascript:void(0);'>Click here</a> to add another editor</div>";
die();
}
add_action( 'wp_ajax_load_editor_new_editor', 'load_editor_new_editor' );
File 3 is the template file "template.php" :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Load Editor</title>
<?php wp_head(); ?>
</head>
<body>
<? wp_editor('Ecample content', 'id', array('textarea_rows' => 3)); ?>
<div id="add"><a onClick="load_new_editor('editor', 1);" href="javascript:void(0);">Click here</a> to add an editor</div>
<div id="editor_container">
<!-- Editors will load here -->
</div>
<script>
<?
echo 'ajaxurl = "'.admin_url('admin-ajax.php').'";';
?>
</script>
<?php wp_footer(); ?>
</body>
</html>
And file 4 is the javascript file "load_editor.js":
function load_new_editor(id, number){
// remove click to add
jQuery('#add').remove();
var fullId = id + number;
var data = {
'action': 'load_editor_new_editor',
'number': number,
'id': id
};
jQuery.post(ajaxurl, data, function(response) {
//add new editor
jQuery('#editor_container').append(response);
});
}
I've also put it on github here:
enter link description here
Thank you so much for any help that you can give. I've been trying to get this to work for so long it's frying my brain. I even hired a programmer via elance and he was unable to get as far as I did.
This is the best I can come up with and I think it is good enough for me.
Everything is working except the quicktags and I can live without them.
I removed the javascript from funtions.php
<?
// load custom editor template
function load_editor_template( $template )
{
$template = plugin_dir_path( __FILE__ ) . 'template.php';
return $template;
}
add_filter( 'template_include', 'load_editor_template' );
// load javascript
function load_editor_scripts() {
wp_enqueue_script( 'load_editor', plugins_url() . '/load_editor/js/load_editor.js', array(), '', true );
wp_enqueue_script( 'jquery');
}
add_action( 'wp_enqueue_scripts', 'load_editor_scripts' );
// create new editor
function load_editor_new_editor() {
$id = $_POST['id'];
$number = $_POST['number'];
$next = $number + 1;
$full_id = $id.$number;
echo "<h1>Editor $number</h1>";
$content = '<p>This is example content.</p>';
wp_editor($content, $full_id, array('textarea_rows' => 3));
// create "add new" text
echo "<div id='add'><a onclick=\"load_new_editor('editor', $next);\" href='javascript:void(0);'>Click here</a> to add another editor</div>";
die();
}
add_action( 'wp_ajax_load_editor_new_editor', 'load_editor_new_editor' );
Then I changed the following on load_editor.js
Added the quicktags function to get the tabs to work without error
Called tinymce.init with the settings that WordPress uses
I think that's it.
// JavaScript Document
function load_new_editor(id, number){
// remove click to add
jQuery('#add').remove();
var fullId = id + number;
var data = {
'action': 'load_editor_new_editor',
'number': number,
'id': id
};
jQuery.post(ajaxurl, data, function(response) {
//add new editor
jQuery('#editor_container').append(response);
// this is need for the tabs to work
quicktags({id : fullId});
// use wordpress settings
tinymce.init({
selector: fullId,
theme:"modern",
skin:"lightgray",
language:"en",
formats:{
alignleft: [
{selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'left'}},
{selector: 'img,table,dl.wp-caption', classes: 'alignleft'}
],
aligncenter: [
{selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'center'}},
{selector: 'img,table,dl.wp-caption', classes: 'aligncenter'}
],
alignright: [
{selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'right'}},
{selector: 'img,table,dl.wp-caption', classes: 'alignright'}
],
strikethrough: {inline: 'del'}
},
relative_urls:false,
remove_script_host:false,
convert_urls:false,
browser_spellcheck:true,
fix_list_elements:true,
entities:"38,amp,60,lt,62,gt",
entity_encoding:"raw",
keep_styles:false,
paste_webkit_styles:"font-weight font-style color",
preview_styles:"font-family font-size font-weight font-style text-decoration text-transform",
wpeditimage_disable_captions:false,
wpeditimage_html5_captions:true,
plugins:"charmap,hr,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs,wpview",
selector:"#" + fullId,
resize:"vertical",
menubar:false,
wpautop:true,
indent:false,
toolbar1:"bold,italic,strikethrough,bullist,numlist,blockquote,hr,alignleft,aligncenter,alignright,link,unlink,wp_more,spellchecker,fullscreen,wp_adv",toolbar2:"formatselect,underline,alignjustify,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help",
toolbar3:"",
toolbar4:"",
tabfocus_elements:":prev,:next",
body_class:"id post-type-post post-status-publish post-format-standard",
});
// this is needed for the editor to initiate
tinyMCE.execCommand('mceAddEditor', false, fullId);
});
}
Here is a screencast of it working.
http://screencast.com/t/Psd9IVVY
If anyone knows how to get the quicktags to show, I would love to know.
Also, if you spot something wrong with my code let me know.
I have updated the github if you want to download it here:
https://github.com/ccbgs/load_editor
( Answer found here: https://wordpress.stackexchange.com/questions/51776/how-to-load-wp-editor-through-ajax-jquery/192132 )
1) in functions.php,add:
add_action('init','my_wpEditOUPUTT'); function my_wpEditOUPUTT(){
if (isset($_POST['Give_me_editorrr'])){
wp_editor( '' , 'txtrID_'.$_POST['myNumber'], $settings = array( 'editor_class'=>'my_class', 'textarea_name'=>'named_'. $_POST['myNumber'], 'tinymce'=>true , 'media_buttons' => true , 'teeny' => false,));
exit;
}
}
2) inside dashboard HTML page:
<div id="MyPlace"></div> Click to load
<script type="text/javascript">
startNumber = 1;
function myLoad(){ alert('wait 1 sec');
startNumber ++;
jQuery.post('./index.php', '&Give_me_editorrr=1&myNumber='+startNumber ,
function(data,status){
if (status == "success") {
document.getElementById('MyPlace').innerHTML += data; alert("Inserted!");
tinymce.init({ selector: 'txtrID_'+startNumber, theme:'modern', skin:'lightgray'}); tinyMCE.execCommand('mceAddEditor', false, 'txtrID_'+startNumber);
}
});
}
</script>

passing php array to javascript variable, then to server

I realize this has been asked numerous times here, but I just can't figure it out. I'm certain it is simple, but I've been banging my head a little. I have search results that are php arrays, displayed in a jquery window. I need to eventually get them back to the server, but first need to pass them to jquery variables. This is where I am stuck.
You will see I have made an attempt to via $book_title, trying to pass that to a jquery variable "title"
<script>
$(function() {
$( "#dialog" ).dialog({
height: 550, width: 450});
$( ".btn" ).click(function(){
//assign values to each variable
//var title = $("#returnvalues").val();
var title = <?php echo json_encode($book_title);?>;
var author = $("#returnvalues").val();
var published = $("#returnvalues").val();
var description = $("#returnvalues").val();
var pages = $("#returnvalues").val();
var publisher = $("#returnvalues").val();
var ISBN = $("#returnvalues").val();
//book_title = $item['volumeInfo']['title'];
$.ajax({
type: "POST",
url: 'book-meta.php',
dataType: 'json',
//assign values to the variables to be passed to the server via data
data: { title : title, author : author, published : published,
description : description, pages : pages, publisher : publisher, ISBN : ISBN},
success: function(data)
{
//alert(data);
//identify the variables for unique handing on the server side
$("input[name='bbp_topic_title']").val(data.title);
$("input[name='bbp_extra_field1']").val(data.author);
$("input[name='bbp_extra_field2']").val(data.published);
$("input[name='bbp_extra_field3']").val(data.description);
$("input[name='bbp_extra_field4']").val(data.pages);
$("input[name='bbp_extra_field5']").val(data.publisher);
$("input[name='bbp_extra_field6']").val(data.ISBN);
//$("#displayResults").html(data);
},
error: function(errorThrown){
alert('error');
}
});
$( "#dialog" ).dialog( "close" );
});
});
</script>
<strong><p style="font-size: 16px; text-align: center";>Top 10 Results for "<?php echo #$_POST['q']; ?>"</p></strong>
<strong><p style="font-size: 14px; text-align: center";>choose a book to select as your topic</p></strong>
<table style="width:400px">
<col width="325">
<col width="75">
<?php $i=0; foreach ($data['items'] as $item) { $i++; ?>
<tr>
<td>
<strong><u><div style="font-size: 14px";><?php printf($item['volumeInfo']['title'])?></u></div></strong>
<strong>Author: </strong><?php printf( $item['volumeInfo']['authors'][0])?><br />
<strong>Published: </strong><?php printf( $item['volumeInfo']['publishedDate']); ?><br />
<strong>Page(s): </strong><?php printf( $item['volumeInfo']['pageCount']); ?><br />
<strong>Publisher: </strong><?php printf( $item['volumeInfo']['publisher']); ?><br />
<strong>Category: </strong><?php printf( strtolower($item['volumeInfo']['printType']).', '.strtolower($item['volumeInfo']['categories'][0])); ?>
<strong>ISBN: </strong><?php printf( $item['volumeInfo']['industryIdentifiers'][0]['identifier']); ?></td>
<td><p><input type="submit" method="post" name="selectbook" value="Select" class="btn" id="returnvalues" /></p>
<img src="<?php printf( rawurldecode($item['volumeInfo']['imageLinks']['smallThumbnail'])); ?>" />
</td>
<tr><td style="width:420px"><p><strong>Description: </strong><?php printf( $item['volumeInfo']['description']); ?><br /></p></td>
<?php $book_title=$item['volumeInfo']['title'];
//$book_meta=array($item['volumeInfo']['title']=>"$book_title",$item['volumeInfo']['authors'][0]=>"$book_author");
//print(json_encode($book_meta));
Any help is appreciated. If this gets marked as a duplicate question, please also give this newbie some specific direction. Thanks.
I figured this out! Thanks to XQDev and Uttara for the help! I had to create a separate script, within the loop where my php results are displayed. In this separate script I declare my javascript variables only.
<script>
var title = <?php echo json_encode($book_title); ?>;
</script>
Issue is resolved! Hopefully this thread will help someone in the future with a similar issue.
var title = "<?php echo $book_title; ?>" could cause your wanted result.
The result can be checked by using alert(title) after the assignment.
Your variable are no "jQuery Variables", by the way. They are ordinary Javascript variables. But you pass and access them by using jQuery methods.
But: Your way, in case $book_title contains a string, should be fine, too.. What exactly isn't working?
If you are trying to assign php array to javascript variable then do this
var title = <?php echo json_encode($book_title); ?>;
considering that your $book_title is an array
Eg: <?php
$book_title = array('one', 'two');
?>
javascript: title = ['one', 'two']

Sending value in jquery to php and returning page

I'm struggling on using simplemodal to load a edit textarea for my blog. I have it working lovely but i need to send a value somehow to the php page loading the content. Let me show the code and explain more.
Ok a tag to load the editor
<a class="blog_btns" id="edit" href="">Edit</a>
JQuery to load into simple modal window
jQuery(function($) {
var contact = {
message: null,
init: function() {
$('#edit').click(function(e) {
e.preventDefault();
// load the contact form using ajax
$.get("../_Includes/edit.php", function(data) {
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%", ],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
},
open: function(dialog) {
dialog.overlay.fadeIn(200, function() {
dialog.container.fadeIn(200, function() {
dialog.data.fadeIn(200, function() {
$('#contact-container').animate({
height: h
}, function() {
$('#contact-container form').fadeIn(200, function() {
});
});
});
});
});
},
show: function(dialog) {
//to be added later
},
close: function(dialog) {
dialog.overlay.fadeOut(200, function() {
$.modal.close();
});
},
};
contact.init();
});
The php page that loads the content and textarea
<?php
session_start();
define('HOSTNAME', '#');
define('DB_USERNAME', '#');
define('DB_PASSWORD', '#');
define('DATABASE', '#');
$link = mysql_connect(constant('HOSTNAME'), constant('DB_USERNAME'), constant('DB_PASSWORD')) or die("Database connection error, please check!");
mysql_select_db(constant('DATABASE'), $link) or die("Connection to the defined database not possible, please check!");
$sessionid = base64_decode($_SESSION['id']);
$sql = mysql_query("SELECT * FROM blogs WHERE id=233 LIMIT 1") or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
$id = $row['id'];
$title = $row['title'];
$body = $row['body'];
$tag_array = array();
$result = mysql_query("SELECT tag FROM tags WHERE blog_id='$id' LIMIT 5") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$rtag = str_replace(' ', '', $row['tag']);
$tag_array[] = $rtag;
}
$tag_array = implode($tag_array, ",");
}
?>
<div class="content">
<div class="reply" style="display:none;"></div><form name="editblog" id="editblog" action="#" method="post"><font color="#FFF"><strong>Title: </strong></font><input name="blogtitle" id="blogtitle" type="text" id="title" size="80" maxlength="255" value="<?php echo $title; ?>" /><br /><br />
<textarea cols="60" id="editblogbody" name="editblogbody" rows="20"><?php echo $body; ?></textarea><br />
Please separate tages with a <strong>comma</strong>.<br />
<font color="#FFF"><strong>Tags:</strong></font><input name="tags" id="tags" type="text" size="80" maxlength="255" value="<?php echo $tag_array; ?>" /><br /><br />
<input type="submit" value="Post Blog" />
<span id="blogFormProcessGif" style="display:none;"><img src="../_Images/loading.gif" width="28px" height="28px" alt="Loading" /></span></form>
<script>CKEDITOR.replace("editblogbody");</script> </div>
So the window loads fine the content from the sql query works but i need to make the sql query dynamic by sending the blog id via the a link clicked at the start. i was thinking of using the rel attribute to return the value. i need to send this value to the php page for the sql query to load the correct blog somrthing like
$blogid = $_GET['blogig'];
$sql = mysql_query("SELECT * FROM blogs WHERE id='$blogid' LIMIT 1") or die(mysql_error());
but I'm racking my head to work out how to do it.
Can anyone help???
Putting it in rel will work. Using data-id="123" and getting it using $(this).data('id') is better. Using the href is fine, e.g. href="#123".
<a class="blog_btns" id="edit" href="#" data-id="123">Edit</a>
<a class="blog_btns" id="edit" href="#" rel="123">Edit</a>
<a class="blog_btns" id="edit" href="#123">Edit</a>
You the add this to the URL querystring
$('#edit').click(function(e) {
var url="../_Includes/edit.php?blog_id=" + $(this).data('id');
// var url="../_Includes/edit.php?blog_id=" + this.rel;
// var url="../_Includes/edit.php?blog_id=" + this.href.replace('#', '');
$.get(url, function(data){
// etc
And get it in PHP using $_GET['blog_id']
Please note If there is more than one link to open an edit modal, using the id edit will not work, you will need to use a class.
did you try to use a GET parameter in your jQuery $.get() , like:
"../_Includes/edit.php?blog_id=" + $('#edit').attr('rel')
you can get this value in php using something similar:
$_GET['blog_id']
H i,
Within your function
$('#edit').click(function (e) {
e.preventDefault();
// load the contact form using ajax
$.get("../_Includes/edit.php", function(data){ ...
You could send the id with
$('#edit').click(function (e) {
e.preventDefault();
// load the contact form using ajax
$.get("../_Includes/edit.php?blogid=BLOGID", function(data){ ...
and php can pick it up as a regular parameter.
I am assuming that the page you are calling this function from knows what the blog id is , as it is the current page ?
On that, when PHP is rendering the page initially, it might be neat to add the blog id to the page body.
<body id="BLOGID">
....
so now your function can grab it dynamically :
$('#edit').click(function (e) {
e.preventDefault();
var blogid = $("body").attr("id);
// load the contact form using ajax
$.get("../_Includes/edit.php?blogid="+blogid, function(data){ ...
or similar variation ..
??

Categories