I'm trying to learn php and WP developing. My goal is to mark posts done/read on button click. I found this great ajax tutorial plugin. Here is the link of the tutorial, and for the plugin. I have successfully manage to edit the plugin form my needs. On click it checks if there is already that id in the array, if it is it deletes that element from the array. If there is not id in the array, or the array is empty it adds post id into the array. Afterwards the array is updated into db.
Here is the code for the button, that is added after the post content:
public function rml_button( $content ) {
$rml_post_id = get_the_id();
// Show read me later link only when user is logged in
if( is_user_logged_in() && get_post_type() == post ) {
if( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
$value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
}
if( $value ) {
if (in_array($rml_post_id, $value)) {
$html .= 'DONE';
$content .= $html;
}
else {
$html .= 'MARK AS DONE';
$content .= $html;
}
}
else {
$html .= 'MARK AS DONE';
$content .= $html;
}
}
return $content;
}
Here is the code for updating the db:
public function read_me_later() {
check_ajax_referer( 'rml-nonce', 'security' );
$rml_post_id = $_POST['post_id'];
$echo = array();
if( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
$value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
}
if( $value ) {
if (in_array($rml_post_id, $value)) {
foreach (array_keys($value, $rml_post_id, true) as $key) {
unset($value[$key]);
}
$echo = $value;
}
else {
$echo = $value;
array_push( $echo, $rml_post_id );
}
}
else {
$echo = array( $rml_post_id );
}
update_user_meta( wp_get_current_user()->ID, 'rml_post_ids', $echo );
// Always die in functions echoing Ajax content
die();
}
Finally, here is the .js for the ajax call:
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'id' );
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
data : {
action : 'read_me_later',
security : rml_obj.check_nonce,
post_id : rml_post_id
},
success : function( response ) {
jQuery('.rml_contents').html(response);
}
});
//jQuery(this).hide();
});
});
What I cannot figure out, and sorry if it is a stupid question, is how to change button text after the ajax? From "MARK AS DONE" to "DONE" and vice versa. How to call this function rml_button(), inside read_me_later() so that button text will be changed after the db update.
Thank you.
Added if else statements inside ajax success function to be able to change a tag text from MARK AS DONE to DONE and vice versa.
Try:
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'id' );
var ts = jQuery(this);
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
data : {
action : 'read_me_later',
security : rml_obj.check_nonce,
post_id : rml_post_id
},
success : function( response ) {
if(ts.html()=="DONE") { ts.html("MARK AS DONE"); } // ts.html()=="DONE" - maybe changed based on response
else { ts.html("DONE"); }
jQuery('.rml_contents').html(response);
}
});
//jQuery(this).hide();
});
});
I want to display custom option price with name in price box in product detail page.
I also try this link but not getting success this is link i use
So please suggest me any solution.
first of all you have to put button calculateprice
then onclick of calculateprice you have to call function chkprice()
function chkpice()
{
var a=document.getElementById("options_1_text").value;
var b=document.getElementById("options_2_text").value;
var c=document.getElementById("options_3_text").value;
var d=document.getElementById("options_4_text").value;
var e=<?php echo $_product = $this->getProduct()->getPrice()?>;
var f=(a+b+c+d)+e;
var e=document.getElementById(('product-price-'+<?php echo $_product = $this->getProduct()->getId()?>)).innerHTML;
$('product-price-'+<?php echo $_product = $this->getProduct()->getId()?>).innerHTML =''+e.replace(<?php echo $_product = $this->getProduct()->getPrice()?>,d)+'</span>';
}
insted of options_1_text,options_2_text,options_3_text,options_4_text put your id it will get your result
First you do the function that takes care of updating the charges:
function updateCharges(){
var tmpText="";
$("input[type='select']").each(function{
tmpText+=$("#"+this.id+"option:selected").text()+"<br>";
});
$("#detailDiv").html(tmpText)
}
Then you just bind the selects to that function
$("input[type='select']").change(updateCharges)
Now you just have to make sure to include in your template a <div id="detailDiv"></div>
I would just create a custom block with the above code and place it inside the product detail page. Also you should check the selectors used, they will look for absolutelty ALL selects on the page, so thats not what you may want. But its just a matter of firebug-ging untill the aproppiate selector is found
Recently I need something similar. Perhaps it is helpful for you.
Block class:
class Foo_Bar_Block_Baz extends Mage_Catalog_Block_Product_View {
protected function getOptionDataCollection($options) {
$optionDataCollection = array();
foreach ($options as $option) {
$optionDataCollection[$option->getData('option_id')] = array_filter($option->getData());
}
return $optionDataCollection;
}
protected function getOptionValueDataCollection($options) {
$optionValueDataCollection = array();
foreach ($options as $option) {
$optionType = $option->getType();
if ($optionType == 'drop_down') {
$optionValues = $option->getValues();
foreach ($optionValues as $valueItem) {
// here you could also use the option_type_id (in my case I needed the sku)
$optionValueDataCollection[$valueItem->getData('sku')] = array_filter($valueItem->getData());
}
} else {
//Mage::throwException('Unexpected input. Processing for this optionType is not implemented');
}
}
return $optionValueDataCollection;
}
public function getOptionsJson() {
$data = array(
'options' => array(),
'optionValues' => array()
);
$options = $this->getProduct()->getOptions();
array_push($data['options'], $this->getOptionDataCollection($options));
array_push($data['optionValues'], $this->getOptionValueDataCollection($options));
$optionsJson = json_encode($data);
return $optionsJson;
}
}
Template
<script id="optionsJson" type="application/json">
<?php echo $this->getOptionsJson(); ?>
</script>
JS
var json = JSON.parse(document.getElementById("optionsJson").innerHTML),
options = json.options[0],
optionValues = json.optionValues[0];
optionValues['<optionValueSKU>'].default_title
optionValues['<optionValueSKU>'].price
-----------Create controller-------------
<?php
class Magento_Guys_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
echo "Thank you !";
}
public function genCartAction()
{
$id = $this->getRequest()->getParam('pid');
$_product = Mage::getModel('catalog/product')->load($id);
$buy = Mage::helper('checkout/cart')->getAddUrl($_product);
echo $qty = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
//echo $id;
//echo $this->getRequest()->getParam('id');;
}
}
?>
----------------Change Add to cart code-------------------
<?php if ($_product->isAvailable()): ?>
<b class="available_quanity" style="display: none">Available Quantity :</b> <span id="simplestock" class="simplestock">Please select a color to view the quantity</span>
<?php endif; ?>
</div>
<?php if(!$_product->isGrouped()): ?>
<div class="qty">
<label for="qty"><?php echo $this->__('Qty:') ?></label>
<?php $i = 0; ?>
<select id="qty" class="input-text" name="qty" style="width:50px;">
<?php while($i<=(int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()):?>
<option value="<?php echo $i; ?>"><?php echo $i++; ?></option>
<?php endwhile; ?>
</select>
</div>
<?php endif; ?>
----------------Add Ajax for get Quantity---------------
<script>
jQuery(document).ready(function() {
jQuery(".product-options select[id^='attribute']").on('change', function() {
var id = getSimpleProductId();
var qty = "";
jQuery('.available_quanity').show();
jQuery("#fancybox-loading").show();
jQuery.ajax({
type: "POST",
data: 'pid=' + id,
url:'https://www.thewirelesscircle.com/guys/index/genCart',
success:function(response){
if (response) {
qty = response;
var x = document.getElementById("qty");
var i;
removeOptions(x);
for(i=1;i<=qty;i++) {
var option = document.createElement("option");
option.text = i;
option.value = i;
x.add(option);
}
}
jQuery("#fancybox-loading").hide();
}
});
});
});
</script>
---------------Get Selected Option Id in Magento-------------------
<script type="text/javascript">
function removeOptions(selectbox)
{
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--)
{
selectbox.remove(i);
}
}
function getSimpleProductId() {
var productCandidates = [];
jQuery.each(spConfig.settings, function (selectIndex, select) {
var attributeId = select.id.replace('attribute', '');
var selectedValue = select.options[select.selectedIndex].value;
jQuery.each(spConfig.config.attributes[attributeId].options, function(optionIndex, option) {
if (option.id == selectedValue) {
var optionProducts = option.products;
if (productCandidates.length == 0) {
productCandidates = optionProducts;
} else {
var productIntersection = [];
jQuery.each(optionProducts, function (productIndex, productId) {
if (productCandidates.indexOf(productId) > -1) {
productIntersection.push(productId);
}
});
productCandidates = productIntersection;
}
}
});
});
return (productCandidates.length == 1) ? productCandidates[0] : null;
}
</script>
Open page: app\code\core\Mage\Catalog\Block\Product\View\Options.php find protected function _getPriceConfiguration($option) function and add $data['title'] = $option->getTitle(); before return $data; statement.
Now, open app\design\frontend\YOUT_TEMPLATE_PATH\default\template\catalog\product\view\options.phtml
Add <div id="optiontitle"></div> top of the page.
Then find this:
$A(element.options).each(function(selectOption){
if ('selected' in selectOption && selectOption.selected) {
if (typeof(configOptions[selectOption.value]) != 'undefined') {
curConfig = configOptions[selectOption.value];
}
}
});
Replace by:
$A(element.options).each(function(selectOption){
if ('selected' in selectOption && selectOption.selected) {
if (typeof(configOptions[selectOption.value]) != 'undefined') {
curConfig = configOptions[selectOption.value];
optionTitle = curConfig.title + "<br>";
$("optiontitle").insert(optionTitle);
}
}
});
After searching for a long time I've decided to just ask it here, since the things I found either don't work(or I can't get them to work ;)) - or require me to change things on my server, which I would like to avoid.
I want below function to show the output after each result, so the function doesn't have to be loaded first, which takes a long time. My idea, as you can see below, was to try this with jQuery(1.8.2).
It doesn't work and I simply can't get it to work. Is there a better way to do this? Did I make a mistake somewhere causing it not to work?
If you need additional information, please ask.
<?php
print_r($_POST);
if(isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option']))
{ error_reporting(0);
define('INCLUDE_CHECK',true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.',$_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
if ($_POST['loop']==40)
{ print 'Laatste loop dus .. STOP : .'.$ext[41]; }
else
{ print 'Loop: '.$_POST['loop'].' - zoek op : .'.$ext[$_POST['loop']];
?>
<script>
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $_POST['loop']+1; ?>'},
function(data){
$('#domresults2').css('display','block').html(data);
$('#domloading').css('display','none');
});
</script>
<?php
}
}
?>
//Start JS
<script>
$('#domsubmit.complete').click( function() {
var dom = escape($('#domsearch').val());
var opt = escape($('#option').val());
$('#domresults2').css('display','none').html('');
$('#domloading').css('display','inline');
$.post('test.php', { p:'full', domain:dom, option:opt, loop:0},
function(data){
$('#domloading').css('display','none');
$('#domresults2').css('display','block').html(data);
});
return false;
});
</script>
//end JS
///////////////////////////
update : solved!
so, what went wrong? -> the php function in core.inc.php referred to a incompatible with jQuery 1.8.2 lib ('qTip2'). Thanks for the support!
<?php
print_r($_POST);
if (isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option'])) {
error_reporting(0);
define('INCLUDE_CHECK', true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.', $_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
$loop = $_POST['loop'];
DomCheck($_POST['domain'],$ext[$_POST['loop']]);
if ($loop != count($ext)) {
$loop++;?>
<script type="text/javascript">
var opt = '<?php echo $_POST['option']; ?>';
var dom = '<?php echo $_POST['domain']; ?>';
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $loop; ?>'},
function(data){
$('#domresults2').css('display','block').append(data);
<?php if ($loop < count($ext)) {
echo "$('#domloading').css('display','none');";
} ?>
});
</script>
<?php
}
}
?>
One thing you need to understand is that PHP executes on the server and JavaScript (jQuery) executes on the client.
This means that by the time jQuery starts executing, PHP is done.
However, I don't see a loop anywhere in your code. I think this is more of what you wanted. You're not doing a "PHP loop using jQuery," you're outputting jQuery code in a PHP loop:
<?php
if (isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option'])) {
error_reporting(0);
define('INCLUDE_CHECK', true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.', $_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
foreach ($_POST['loop'] as $loop) {
if ($loop == 40) {
print "Laatste loop dus .. STOP : .{$ext[41]}";
} else {
print "Loop: {$loop} - zoek op : .{$ext[$loop]}";
?> <script>
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $loop; ?>'},
function(data){
$('#domresults2').css('display','block').html(data);
$('#domloading').css('display','none');
});
</script>
<?php }
}
}
?>
I am trying to submit a form without leaving the page using json.
However, the method below ignores the data I have entered into the CKEditor.
Any ideas (and feel free to correct my terminology)?
<script type="text/javascript">
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
</script>
<form name="addStory" action="" method="post" id="addStory">
<label for="story_story">Story: </label><textarea id="story_story" name="story_story"><p></p></textarea>
<?php
// Include the CKEditor class.
include("ckeditor/ckeditor.php");
// Create a class instance.
$CKEditor = new CKEditor();
$CKEditor->basePath = '/ckeditor/'
$CKEditor->replace("story_story");
?>
<input type="submit" value="Submit" />
</form>
_posteddata.php:
include 'connection.php';
function check_input($value, $quoteIt)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (is_null($value) || $value=="") {
$value = 'NULL';
} else if (!is_numeric($value) && $quoteIt == 1) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// CKEDITOR STUFF FOR STORY_STORY
if (isset($_POST)) {
$postArray = &$_POST;
}
foreach ( $postArray as $sForm => $value )
{
if($sForm == "story_story") {
$story_story = check_input($value, 1);
}
}
$query = "INSERT INTO story_table (story) VALUES ($story_story)";
mysql_query($query) or die(mysql_error() . $query);
$return = array();
$return['adminList'] = "New story added with ID: " . mysql_insert_id();
header('application/json');
echo json_encode($return);
mysql_close();
In this kind of situation you must force CKEditor to update the contents of the textarea
So your function would be something like this:
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
CKEDITOR.instances.story_story.updateElement(); // Update the textarea
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
I know this is a very basic question, but i couldnt figure how to fix the code even after crawling the web for past 1 hour.
I have an unordered list containing the information about the categories in the database, with cat_id as primary key. and a subject table with cat_id as its foreign key, so i want to access the subjects table through ajax request for given category ID. below is the code i used to generate categories. Where i am stuck is, i dont know which DOM element to fetch in order to send the unique id in the url parameter ..
thanks ..
<ul id="search_form">
<?php
$cat = Category::find_all();
foreach($cat as $category) {
echo '<li id="';
echo $category->cat_id;
echo '"><a href="subject.php?id=';
echo $category->cat_id;
echo'">';
echo $category->category;
echo '</a></li>';
}
?>
</ul>
<div id="results">
<!-- ajax contents goes here -->
</div>
the ajax file is
window.onload = init;
function init() {
if (ajax) {
if (document.getElementById('results')) {
document.getElementById('search_form').onclick = function() {
ajax.open('get', 'subject.php?id='+id ); // subject.php?id=
// how will i pass the variable
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
}
}
function handleResponse(ajax) {
if (ajax.readyState == 4) {
if ((ajax.status == 200) || (ajax.status == 304) ) {
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
results.style.display = 'block';
}
}
}
and the subject.php
<?php
//include("tpl/header.php");
include("includes/initialize.php");
?>
<h2></h2>
<?php
if (isset($_GET['id'])) {
$id= mysql_real_escape_string($_GET['id']);
$subject = Subject::find_subject_for_category($id);
foreach($subject as $subj) {
echo $subj->subject_title;
}
} else {
echo "No ID Provided";
}
?>
I have used Jquery to do these kind of things and it works fine for me.
$.ajax({
type: GET,
url: "subject.php",
data: {id: $('#search_form :selected').val()},
success: function(result){
// callback function
}
});