Ajax not working in submit button - php

I am creating this wordpress plugin it works well but the issue here in subimt data using ajax. I already created the ajax code but it doesn't work.
Please help to figure it out
Thank You
Here is the code
<script>
var data = {
action: 'join_mailinglist',
email: email
};
jQuery("#mailinglistsubmit").hide();
jQuery(".ajaxsave").show();
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data,
function(response){
jQuery(".ajaxsave").hide();
jQuery("#mailinglistsubmit").show();
});
return false;
</script>
<?php
/*
Plugin Name: MyFirst
Plugin URI: http://zachis.it
Description: ajax form.
Version: 1.0
Author: Zachary Smith
Author URI: http://zachis.it
License: GPL2
*/
?>
<?php
/* What to do when the plugin is activated? */
register_activation_hook(__FILE__,'my_first_plugin_install');
/* What to do when the plugin is deactivated? */
register_deactivation_hook( __FILE__, 'my_first_plugin_remove' );
function my_first_plugin_install() {
/* Create a new database field */
add_option("my_first_data", 'Testing !! My Plugin is Working Fine.', 'This is my first plugin panel data.', 'yes');
}
function my_first_plugin_remove() {
/* Delete the database field */
delete_option('my_first_data');
}
add_action('admin_menu', 'my_first_admin_menu');
function my_first_admin_menu() {
add_options_page('Plugin Admin Options', 'My Plugin Settings', 'manage_options',
'my-first', 'plugin_admin_options_page');
}
?>
<?php
function plugin_admin_options_page() {
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2>Plugin Options Admin Page</h2>
</div>
<div class="content">
<div class="output"><p><?php echo get_option('my_first_data'); ?></p></div>
<p>
<form method="post" action="options.php">
<?php wp_nonce_field('update-options'); ?>
<h2>Enter Text: </h2>
<textarea name="my_first_data" id="my_first_data" cols="200" rows="20"></textarea>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="my_first_data" /><br />
<input style="position: fixed; left: 40%;" id="mailinglistsubmit" type="submit" value="Save Changes" /><img src="<?php admin_url(); ?>/wp-admin/images/wpspin_light.gif" alt="" class="ajaxsave" style="display: none;" />
</form>
</p>
</div>
<?php
}
?>
<?php add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
?>
<?php function join_mailinglist_callback() {
$email = $_POST['email'];
if(!empty($email)) {
$yourEmail = 'c#bavotasan.com';
$subject = 'Add me to your mailing list';
$success = mail($yourEmail, $subject, $email);
if(!empty($success)) {
echo 'Your email is subscribed to our mailing list.';
} else {
echo 'There was a problem. Please try again.';
}
}
die();
} ?>
<style>
.content { padding-left:150px;}
.output p {width:700px; height:auto;}
</style>

I see several things wrong with this plugin of yours.
Firstly, why is your JavaScript code appended to the top of the plugin? The right way to include JS in WordPress is to have it in a separate .js file and loaded by enqueing it using wp_enqueue_script(). Same for your styles at the bottom.
An example is as follows:
function my_scripts_method() {
wp_enqueue_script(
'your-script-name',
plugins_url( 'js/your-script.js' , __FILE__ ),
array('jquery')
);
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
Secondly, your PHP plugin file MUST NOT be outputting any content and that means you shouldn't see any ?> tags after the headers as that would output a few linebreaks.
Next, in order to get the admin-ajax-url in your static JS file, you should use this function:
wp_localize_script( 'ajax_get_permalink', 'ajax_get_permalink', array(
ajax_url => admin_url( 'admin-ajax.php' )
));
In your JS file, you should wrap your main code in a function that is called when the form submits.
function mailingListSubmit() {
var data = {
action: 'join_mailinglist',
email: jQuery('#mailingListEmail')
};
jQuery("#mailinglistsubmit").hide();
jQuery(".ajaxsave").show();
jQuery.post(ajax_get_permalink.ajax_url, data,
function(response){
jQuery(".ajaxsave").hide();
jQuery("#mailinglistsubmit").show();
});
}
And finally, your action hooks are wrong too. You copied it from the codex (or who knows where) but didn't even bother to read the docs.
add_action('wp_ajax_my_action', 'my_action_callback');
You need to change my_action_callback to reflect your function name join_mailinglist_callback and wp_ajax_my_action to wp_ajax_join_mailinglist -- the action you defined in your JS file.
The above codes aren't tested for syntax errors but should point you in the right direction. You shouldn't expect your plugin to magically work even if you copy and paste these code in.
Read more about AJAX in WordPress plugins here: http://codex.wordpress.org/AJAX_in_Plugins

Related

Adding a Settings Field to my WP Sub Menu Page

Hello I'm currently following a guide on how to add input to my created Sub Menu Pages. Here is a pic of what is showing up. http://imgur.com/a/St9wj .When I view the sub-menu page. No Errors, just not showing the text field. The Function function mytheme_general_name() is not getting called in the 2nd add_submenu_page, but I don't see what is wrong with it.
I copied the Here is my Current two php files in use
File Name: function-admin.php
/*
#package Jeron
========================
ADMIN PAGE
========================
*/
function mytheme_add_theme_options() {
// Generate Theme Options Page
add_menu_page('My Themes Theme Options', 'Theme Options', 'manage_options', 'theme2_options', 'mytheme_create_page', get_template_directory_uri().'/img/themeoptionsicon.png', 110);
// Generate Theme Options Sub Pages
add_submenu_page('theme2_options', 'Theme Options', 'General', 'manage_options', 'theme2_options', 'mytheme_create_page');
add_submenu_page('theme2_options', 'Typography', 'Typography', 'manage_options', 'theme_options_typography', 'mytheme_create_typography_page');
}
add_action('admin_menu', 'mytheme_add_theme_options');
// Activate Custom Settings
add_action('admin_init', 'mytheme_custom_settings');
function mytheme_custom_settings() {
register_setting('mytheme-settings-group', 'first_name');
add_settings_section('mytheme-general-options', 'General Settings', 'mytheme_general_options', 'theme2_options');
add_settings_field('general-name', 'First Name', 'mytheme_general_name', 'theme2_options', 'mytheme_settings_group');
}
function mytheme_general_options() {
echo 'Customize Your Theme Options Below';
}
function mytheme_general_name() {
$firstName = esc_attr(get_option('first_name'));
echo '<input type="text" name="first_name" value="'.$firstName.'" placeholder="First Name" />';
}
function mytheme_create_page() {
require_once(get_template_directory().'/inc/templates/mytheme-admin.php');
}
function mytheme_create_typography_page() {
echo '<h1>My Theme Typography</h1>';
}
?>
File Name: mytheme-admin.php
<h1>My Theme Options</h1>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php settings_fields('mytheme_settings_group');?>
<?php do_settings_sections( 'theme2_options' ); ?>
<?php submit_button(); ?>
</form>

Yii: run a function when a submitButton is pressed

I'm very new to Yii, and trying to understand an existing web app, so please bear with me.
I've been having issues with a certain function, that seems to fail retaining data whenever actionView is calledhere, but I thought perhaps I was going about this problem all wrong.
Instead, I thought perhaps the button could directly run the function from the controller, instead of... whatever it was doing prior.
I looked at a sample here that had this:
<?php echo CHtml::submitButton('CSV Report', array('submit'=>'getReport')); ?>
Where getReport is the function in my controller (actionGetReport).
Unfortunately, it's not working. Here's the code of my _commentform.php:
<?php $post = $forum; ?>
<?php $comment = $model; ?>
<div id="comment_form<?=$post->id?>" class="other-member-comment-box">
<?php
$user=Persons::model()->findByAttributes(array('party_id'=>Yii::app()->user->id));
$country=Lookup_codes::model()->findByAttributes(array('id'=>$user->country));
$location = empty($country) ? '' : 'from '.$country->name;
?>
<div class="user-profilepic">
<a href="<?php echo Yii::app()->createUrl('persons/view/id/'.$user->showViewLinkId())?>"><img src="<?php
if(!empty($user->image) AND file_exists( Yii::getPathOfAlias('webroot').'/images/profile_picture/'.$user->party_id . $user->image)){
echo Yii::app()->request->baseUrl.'/images/profile_picture/'.$user->party_id . $user->image;
} else echo Yii::app()->request->baseUrl.'/images/profile_picture/NA.jpg';
?>"></a>
</div>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'action'=>Yii::app()->createUrl('forum/view/id/'.$forum->id),
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->hiddenField($model,'node_type_id',array('value'=>'7')); ?>
<?php echo $form->error($model,'node_type'); ?>
</div>
<div class="row">
<?php echo $form->hiddenField($model,'content_id',array('value'=>$forum->id)); ?>
<?php echo $form->error($model,'content_id'); ?>
</div>
<div class="row">
<?php echo $form->hiddenField($model,'category',array('value'=>$forum->category)); ?>
<?php echo $form->error($model,'category'); ?>
</div>
<div class="row">
<?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>90),array('id'=>'sample')); ?>
<?php echo $form->error($model,'content'); ?>
</div>
<input type="hidden" value="<?php echo $view; ?>" id="view" name="view"/>
<div class="row buttons">
<?php
if ($view == 'view'){
if ($model->isNewRecord) {
echo CHtml::submitButton('Reply', array('id'=>'comment'.$comment->id));
} else {
echo CHtml::button('Save', array('submit'=>'updatecomment'));
}
}?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
</div>
And here's the UpdateComment function from my controller:
public function actionUpdateComment()
{
Yii::log(CVarDumper::dumpAsString("ForumController: Update COMMENT!"));
Yii::log(CVarDumper::dumpAsString($_POST['Comment']));
exit();
}
I'm not exactly sure what I'll get by the $_POST['Comment'], but if the code worked, I'd very least expect it to log out the "ForumController: Update COMMENT!". It doesn't.
I tried changing the submitButton to button, but that just kills the button function entirely.
Next, I tried this answer here.
So I changed the submitButton code to this:
echo CHtml::submitButton($model->isNewRecord ? 'Reply' : 'Save',array('id'=>'comment'.$comment->id));
And added this to the end:
<script>
$(document).ready(function() {
$('#text_form_submit').click(function(ev) {
ev.preventDefault();
$.ajax({ type: 'POST', dataType: 'JSON',
url: '<?php echo Yii::app()->createUrl("forum/UpdateComment"); ?>',
success:function(data){
if(data !== null) {
$('#Text_group').val(data);
$('#text-form').submit();
}
},
error: function() {
alert("Error occured!!!.");
},
});
return false;
});
});
</script>
Not exactly sure what the code does, other than call a function as well, but as well, it doesn't work (I also changed POST from GET and back).
Any suggestions? I feel like CActiveForm is to blame here, but even modifying that causes the site to fail in loading pages.
You have a long question and could be you should split your question in more question with simple question each ..
A firts answer the submit button don't contain the target function see this doc
http://www.yiiframework.com/doc/api/1.1/CHtml#submitButton-detail
the target function (php controller/action) is defined in form .. this is from html .. is the form definition that define the target for the submitted data ..
if you want execute the actionGetReport you should define the target in form action
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'action'=>Yii::app()->createUrl('yourController/actionGetReport'),
'enableAjaxValidation'=>false,
)); ?>

On AJAX call session is destroying WordPress plugin

I am calling an AJAX function from WordPress plugin through admin-ajax.php. But when the request is send, its destroying the session.
I have an array where data is saved on every request, but on every request previous data is destroyed.
AJAX code i am calling:
function cartbox()
{
var url = {
'action':'my_cart_action',
'rnd':Math.random(),
};
$.ajax({
type:'POST',
data:url,
url: "http://localhost/vmlogic/wp-admin/admin-ajax.php",
success : function(response)
{
$("#cartdiv").html(response);
}
});
}
On plugin index file i am calling this:
class cloud_calculator{
// Call a cation on link click
function cloud_calculator()
{
add_action('init' , array($this,'cloud_init'));
}
public function cloud_init()
{
add_action('wp_head' , array($this, 'plugin_jquery_func'));
add_action('admin_menu', array($this,'my_menu'));
add_shortcode('cloud_calculator', array($this,'my_calculator'));
add_action('the_content', array($this,'the_content_action'));
add_action( 'wp_ajax_my_unique_action', array($this,'my_unique_action_callback'));
add_action( 'wp_ajax_nopriv_my_unique_action', array($this,'my_unique_action_callback'));
add_action( 'wp_ajax_my_cart_action', array($this,'my_cart_action_callback'));
add_action( 'wp_ajax_nopriv_my_cart_action', array($this,'my_cart_action_callback'));
}
public function plugin_jquery_func()
{
$plugins_url = plugins_url().'/cloud-calculaor/';
?>
<script type="application/javascript">
var PluginUrlJs = '<?php echo $plugins_url ;?>';
</script>
<?php }
public function the_content_action($content)
{
$content = str_replace('[cloud_calculator]',do_shortcode('[cloud_calculator]') ,$content );
return $content;
}
// Menu call function
public function my_menu() {
add_menu_page('Cloud Calculator', 'Cloud Calculator', 'manage_options', 'cloud-calculaor/cloud-calculaor.php', array($this, 'my_function'));
}
// action to call on admin menu
public function my_function() {
wp_enqueue_style('style', '/wp-content/plugins/cloud-calculaor/style/admincalculator.css');
echo
'<div class="wrap">
<h2>Cloud Calculator</h2>
<div class="plugincode">
<div style=" padding:10px 10px 10px 50px;">
<p style="margin:5px 0px">
To Insert <strong>CLOUD CALCULATOR</strong> shortcode inside a page or post:<br>
<br>
Use: <code><strong>[cloud_calculator]</strong></code><br>
<br>
For more queries contact the administrator!<br>
</p>
</div>
</div>
</div>
';
}

Pre-Populate wp-login.php Username

I have a WP site whereby i send customers an email with a link to /my-quotes/ this then, has the following code:
<?
if (!is_user_logged_in()): ?>
<meta http-equiv="refresh" content="0;URL=<? echo wp_login_url(get_permalink()); ?>">
<? endif; ?>
What i want to do is, give the link in the email like:
/my-quotes/?login=myusername
and that 'myusername' is the login fields value to save the user re-typing it.
I've had a look in wp-login.php and cant work out where to populate the login fields using $_GET, can anyone advise on a solution?
Thanks in advance.
You should do it by hooking in to the login_form action, rather than modifying wp-login.php, which will get overwritten at next update.
You can add this code to your theme's functions.php file:
// As part of WP login form construction, call our function
add_filter ( 'login_form', 'login_form_prepop' );
function login_form_prepop(){
// Output jQuery to pre-fill the box
if ( isset( $_REQUEST['myusername'] ) ) { // Make sure a username was passed
?>
<!-- Small jQuery script to set the value of the input field to your variable -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$("#user_login").val( '<?php echo( $_REQUEST['myusername'] ); ?>' );
});
</script>
<?php
}
}
Then update your code to include the variable:
<?
if (!is_user_logged_in()): ?>
<meta http-equiv="refresh" content="0;URL=<? echo wp_login_url(get_permalink()); ?>?myusername=username">
<? endif; ?>
If the jQuery footprint is too much, you can achieve the same with JavaScript:
<script type="text/javascript">
var el = document.getElementById("user_login");
el.value = "<?php echo( $_REQUEST['myusername'] ); ?>";
</script>

How to integrate AJAX to avoid page redirection of PHP CMS

I have used a CMS built with PHP and MySQL. It works great and I have fully customized it to my liking. The only thing now to do is make a more efficient way of loading the data. When a user wants to select an article I want the browser to stay on the same exact page/url without reloading or redirecting. Here is a demo of the CMS: DEMO LINK
For example, the above line of code was exerted from the homepage.php script. It is an anchor tag for the user to select to view the whole content of a particular article, which was only partially displayed in the homepage. When this link is clicked, the user is directed away from the homepage and taken to the article's specific URL. How can I get the full article content page to load inside of the homepage and hide the original homepage content to avoid the page redirect problem. Is this something that can be done with this particular CMS? I can provide any PHP script from the CMS if needed. Thanks in advance.
ARCHIVE.php SCRIPT:
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
If you can get the content of the article using ajax and put that content below that title of that article, for ex let say you have a php function in backend which you can call to get the content of article given the article id then you can make a GET ajax request to get the article content and put in the desired div. something like:
<script language="javascript">
$("#view_more").click(function(){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('div #description').html(response);
}
});
return false;
});
</script>
update:27-11-2012
you can try something like this, if that helps you understanding better. it may not be exactly what you want but I hope it will help you understanding how you can proceed.
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary" id="<?php echo $article->id?>">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
<script language="javascript">
function viewFullArticle(article_ID){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('p #'+article_ID).html(response); //assuming response is everything you want to display within summary paragraph
}
});
return false;
};
</script>

Categories