On AJAX call session is destroying WordPress plugin - php

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

Related

Can't load index.php in views

I can't load index.php file in view folder. The error displayed is
"Unable to load the requested file: calendar/index.php"
Here is the code
controller(Calendar.php):
*public function __construct() {
Parent::__construct();
$this->load->model("calendar_model");
}
public function index()
{
$this->load->view("calendar/index.php", array());
}*
model(Calendar_model.php):
*?php
class Calendar_Model extends CI_Model
{
}
?>*
view (index.php):
*<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Calendar</h1>
<div id="calendar">
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
});
});
</script>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
});
</script>*
Better rename your index.php like V_index.php
for this case remove .php from your code
public function __construct()
{
Parent::__construct();
$this->load->model("calendar_model");
}
public function index()
{
$this->load->view("calendar/index", array());
}

displaying codeigniter database error using ajax

I get error 500 internal server error
I want to display database error to view, so far i can produce the response only in chrome network response
Model classes, I omit the constructor
class Size_mdl extends MY_Model {
public function create($data) {
return $this->insert($data);
}
}
class MY_Model extends CI_Model {
public function insert($data) {
$success = $this->db->insert($this->table_name, $data);
if ($success) {
return true;
} else {
$msg = $this->db->error();
return $msg;
}
}
controller
$data['test_r'] = var_dump($this->Size_mdl->create($data));
$this->load->view('size/create_size_view',$data);
View
This is Welcome.php, the most outer with header and footer
<div class="page">
<!-- Page Header-->
<header class="page-head"></header>
<!-- Page Content-->
<main id="main_content" class="page-content"></main>
<!-- Page Footer-->
<footer class="page-foot section-60 section-xl-150 text-center text-lg-left">
Inside that page i have create_size_view loaded to main_content, previously it was homepage, bunch of stuff.
<head>
<style>
</style>
</head>
<body>
<div id="container">
<div id="content">
<h5>Create New Size</h5>
<div id="inner_container">
<div id="create_part">
<?php
if (isset($test_r)){
echo $test_r;
}?>
<?php echo validation_errors(); ?>
<?php
$attributes = array('id' => 'create_size_form');
echo form_open("size/create", $attributes);
?>
<p>
<?php echo lang('size_short_name_label', 'short_name'); ?>
<?php
$short_name = array(
'name' => 'short_name',
'id' => 'short_name',
'maxlength' => '100'
);
echo form_input($short_name);?>
</p>
<p>
<?php echo lang('size_long_name_label', 'long_name'); ?>
<?php
$long_name = array(
'name' => 'long_name',
'id' => 'long_name',
'maxlength' => '100',
);
echo form_input($long_name);?>
</p>
<p>
<?php echo form_submit('submit', lang('create_size_submit_btn')); ?>
</p>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
<script>
$('form#create_size_form').submit(function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('size/create'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function (result) {
$('#main_content').html(result);
},
});
});
</script>
</body>
Now i need the response for failed insert appear replacing main_content welcome.php or its children div from create_size_view.php. I can produce the successful insert by reloading create_size_view.php
In Codeigniter predefined error handler for MySQL.
if error encountered Codeigniter throw HTML content with 500 server site error
for avoiding this page 500 status code put Codeigniter ENVIRONMENT in production then your code will work properly.
change ajax url property. use url like "/size/create" dont use whith domain like "www.site.com/size/create";
use text for binding data
$.ajax({
type: "POST",
url: "<?php echo site_url('size/create'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function (result) {
$('#main_content').text(result);
}
});

Yii widget reload via ajax

I need to reload a content of my Yii widget via AJAX every XX seconds.
This is my widget code:
class UserOnlineWidget extends CWidget
{
public function init(){
}
public function run(){
$userOnline=User::getOnlineUser();
$this->render("userOnLineWidget", array('userOnline'=>$userOnline));
}
}
And this is the view userOnLineWidget.php:
<div class="userOnline">
<h5>User Online</h5>
<ul>
<?php
foreach($userOnline as $user) {
?>
<li>
<ul>
<li><?php echo CHtml::link($user['username'], array('/site/view/'.$user['id'])); ?></li>
<li><?php echo ($user['online'] != null)? 'online' : 'offline'; ?></li>
</ul>
</li>
<?php
}
?>
</ul>
</div>
How can I do this ? I use Yii 1.1.
Here a small example. I hope this help you. Widget which show time from server every second.
//SiteController
public function actionTest()
{
$this->render('my_view'); //just rendering view
}
public function actionContent()
{
$this->widget('time'); //return html of widget. use for ajax
}
//my_view.php
<script src="<?php echo $this->assetsBase ?>/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
$.get('/site/content', {}, function(data) {
$('#widget').html(data);
});
}, 1000); //update widget content every second
});
</script>
<div id="widget">
<?php $this->widget('time'); // render widget ?>
</div>
//widget
class Time extends CWidget
{
public function init(){
}
public function run(){
$date = new DateTime();
$this->render("test", array('time'=>$date->format('H:i:s')));
}
}
//view for widget test.php
<p><?= $time ?></p>

codeigniter ajax load table

I have write a some codeigniter code, when I click button add a data, and the table will ajax reload, not reload the page. How to modify my code? Thanks
This is my controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Big_category extends CI_Controller {
function __construct() {
...
}
function index() {
if($this->session->userdata('logged_in')) {
$this->page(0);
} else {
show_404('page');
}
}
function page($page) {
....
$data['pagelist']=$this->pagination->create_links();
$data["main_content"] = "big_category_view";
$this->load->view('template', $data);
}
This is my model
class Big_category_model extends CI_Model
{
...
function get_big_category($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get_where('category1', array('c1_status' => 1)); //SELECT * FROM category1
return json_encode($query->result());
}
This is my view
...
<? $data = json_decode($all_big_category); ?>
<? foreach($data as $key => $value): ?>
<tr class="modify_tr">
<td><?=($key+1)?></td>
<td id="td_id_<?=$value->c1_id?>" class="modify_td">
<span id="c1_id_<?=$value->c1_id?>"><?=$value->c1_name?></span>
<form class="form-search td_id_<?=$value->c1_id?>">
<input type="text" name="input_c1_id" id="input_c1_id_<?=$value->c1_id?>">
<button class="btn modify" id="button_c1_id_<?=$value->c1_id?>" c1-id="<?=$value->c1_id?>" type="button"><i class="icon-edit"></i></button></td>
</form>
<td><button class="btn btn-danger"><i class="icon-remove-sign"></i></button></td>
</tr>
<? endforeach ?>
</table>
<?=$pagelist?>
...
Here is a simple technique of how you can achieve this.
Layout(Template)
<html>
<body>
<div><!--other stuff here--></div>
<div id = 'form_id'>
<?php echo $content?>
</div>
</body>
</html>
Controller
function index()
{
if($this->input->is_ajax_request()){
//load form here
$this->load->view('form');
}else{
//this will load the form for the first time
//pass third parameter as TRUE so it will returned as string
//assigned to index content which will be displayed in layout
$data['content'] = $this->load->view('form',$data , TRUE);
//load template here
$this->load->view('template', $data);
}
}
JQuery
$.ajax({
type : 'POST',
url : '<?php echo site_url('controllername/index')?>',
data : '' // query string
success : function(formagain){
$('#form_id').html(formagain);
//this will replace the content of div with new form
}
});

Ajax not working in submit button

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

Categories