I try to use this function in a plugin, but is not working, maybe because javascript doesn't have time to execute after login an I end up redirected to homepage
public function onUserAfterLogin($text) {
$app = JFactory::getApplication();
$document = JFactory::getDocument();
$document->addScriptDeclaration('document.addEventListener("message", function(event) {
alert("test");
});
');
}
I have tried with even with echo
echo '<script type="text/javascript">
alert("test");
</script>';
One quick method is to redirect the user on login (this can be done at the menu item level) to a static HTML page/or a dynamic PHP page (depending on your needs) that contain the JavaScript code, and that page can then redirect to the page of your choice after firing the JS code.
thank you for the sugestion, but I've used the function in joomla
onAfterRender(), and inside the function you can do this:
//This event is triggered after the framework has rendered the application.
//When this event is triggered the output of the application is available in the response buffer.
public function onAfterRender() {
$app = JFactory::getApplication();
$user_id = JFactory::getUser()->id; // NOT 0
$is_guest = JFactory::getUser()->guest;
if ($user_id !== 0 && $is_guest !== 'guest') {
$myJScript = 'alert("Test");';
// retrieve all the response as an html string
$html = $app->getBody();
// Search and replace tag </body> with the new script+</body>
$html = str_replace('</body>','<script type="text/javascript">' . $myJScript . '</script></body>', $html);
// override the original response
$app->setBody($html);
}
}
Ok where to start, I will try and explain as much as I can.
I am using wordpress with contact form 7 and I am trying to populate 3 dropdown items on the contact form, I found some code that I was able to use with no problem but the problem with this was that it was getting the information from a excel file, the file is now to big and will not run on my website anymore so I would like to get the information from my database now.
I have made a table in my database "vehicle_information" with 3 columns "vehicle_type", "vehicle_make", vehicle_model"
I have code in my functions.php and code in my footer to be able to use the cf7 shortcodes.
Code from funtions.php
function ajax_cf7_populate_values() {
//MySQLi information
$db_host = '***';
$db_username = '***';
$db_password = '***';
$vehicles_makes_models = array();
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die('Error ' . mysqli_error());
//select MySQLi dabatase table
$vehicles_makes_models = mysqli_select_db($connection, 'vehicle_information') or die('Error ' . mysqli_error());
$sql = mysqli_query($connection, 'SELECT * FROM vehicle_type');
while($row = mysqli_fetch_array($sql)) {
$vehicles_makes_models[$row[0]][$row[1]][] = $row[2]; }
}
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'vehicles' => array_keys($vehicles_makes_models),
'makes' => array(),
'models' => array(),
'current_vehicle' => false,
'current_make' => false
);
// collect the posted values from the submitted form
$vehicle = key_exists('vehicle', $_POST) ? $_POST['vehicle'] : false;
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
// populate the $return_array with the necessary values
if ($vehicle) {
$return_array['current_vehicle'] = $vehicle;
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = $vehicles_makes_models[$vehicle][$make];
if ($model) {
$return_array['current_model'] = $model;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
Code from my footer
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $vehicles_dd = $('[name="vehicles"]');
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'vehicle' : $vehicles_dd.val(),
'make' : $makes_dd.val(),
'model' : $models_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
all_values = response;
$vehicles_dd.html('').append($('<option>').text(' -- choose vehicle -- '));
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$.each(all_values.vehicles, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_vehicle == this) {
$option.attr('selected','selected');
}
$vehicles_dd.append($option);
});
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
},'json');
}
})( jQuery );
The problem is I am still learning and this is the first time I have had to use this funtion.
and I am getting an error on my website
Warning: array_keys() expects parameter 1 to be array, null given in /customers/4/0/0/motobid.co.uk/httpd.www/wp-content/themes/storevilla-child/functions.php on line 38 {"vehicles":null,"makes":[],"models":[],"current_vehicle":false,"current_make":false}
any help would be very greatful.
Just like to say code was supplied by BDMW.
Where you use the method array_keys(), instead of:
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
Try this:
$return_array['makes'] = ! empty($vehicles_makes_models[$vehicle]) ? array_keys($vehicles_makes_models[$vehicle]) : [];
From what I've read, the array_keys() has been an issue depending on php versions. Hope this helps!
Hi I am trying to add a feature to my store that when someone clicks on a product instead of being redirected to the product page, the product page loads with ajax in the home page like in this website (click on one of the products): http://www.itsjustyes.com. This is my jquery:
jQuery(document).ready(function($){
$('.info_btn').on('click',function(){
var theId = $(this).attr('id');
var div = $('#product-container')
$.post('wp-admin/admin-ajax.php',{
action:'my_get_posts',post_id: theId
}, function(data){
console.log(data);
div.html(data);
})
return false;
});
});
This is my code in functions.php:
//Ajax call to product
function my_get_posts_return()
{
global $post;
$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
if ($post_id > 0) {
$the_query = new WP_query(array('p' => $post_id));
if ($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post();
wc_get_template_part( 'content', 'single-product' );
endwhile;
} else {
echo "There were no posts found";
}
}
wp_die();
}
add_action('wp_ajax_my_get_posts', 'my_get_posts_return');
add_action('wp_ajax_nopriv_my_get_posts', 'my_get_posts_return');
I keep getting that there were no posts found in the loop which is weird cause I know I am sending the right post id. By the way, if I try to get the individual parts of the product page with get_the_title( $post_id ) I get it just fine. It's only when I try to load the template part with the loop that I get this problem. Any idea what I am doing wrong??
Your WP_Query was not finding the correct post type.
$the_query = new WP_query(array('p' => $post_id));
The query above didn't return any post at all. By default, wordpress will assume that you're querying the post_type = 'posts' which is why you cannot find the product post.
Therefore, you need to specify what post_type you're looking for. With WooCommerce product, you can use:
$the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
P.S. It's a good practice to use wp_localize_script function to register your ajaxurl, rather than hard coded in your javascript. You can follow this post for more detail.
Hope this helps.
I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));
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>