Creating a PHP log without database - php

I'm working on a WordPress plugin which logs bruteforce attacks, but this is my second plugin ever and I'm unsure how to do this.
I grab the IP of the machine who is bruteforce attacking the wp-admin form by using guard_get_ip_address().
But now I'm stuck on how to save the actual IP at the moment of when the user is bruteforce attacking. Is there any way to save this to a table like I created below?
function logs() {
?>
<table>
<tr>
<th>IP</th>
</tr>
<tr>
<td><?php echo guard_get_ip_address(); ?></td>
</tr>
</table>
<?php
}
function add_logs() {
wp_add_dashboard_widget('dashboard_widget', 'Logs', 'logs');
}
add_action('wp_dashboard_setup', 'add_logs' );
Edit: the function guard_get_ip_address() only attempts to grab IPs;
function guard_get_ip_address() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}

// LOG DATA WILL STORE IN FOLDER WITH YOURFILENAME.DOC USE TO PRINT THIS CODE , CALL THIS FUNCTION WITH ANCHOR TAG FROM YOUR VIEW PAGE
public function file_log()
{
$id = YOURFILENAME;
$file = APPPATH.'yourfile/'.$id.'.doc';
$content = file_get_contents($file);
echo '<html><body style="background-color:white; padding-
left:20px; padding-top:40px;">'.$content.'</body></html>';
}
// create Base.php file
function get_file_force_contents($contents,$LogfileName,$logUserName){
if($contents){
date_default_timezone_set("Asia/Kolkata");
$logtime = Date('d-M-Y h:i A');
$dir = APPPATH.'yourfile/';
#$file = $dir.'/'.$LogfileName.'.doc';
if(!is_dir($dir)) mkdir($dir, 0777, TRUE);
#$current = file_get_contents(#$file);
$current .= '<br>'.$logtime.' - '.'<strong>'.$logUserName.'</strong> - '.$contents;
file_put_contents($file, $current);
}
}
// controller
require_once(APPPATH.'/Base.php');
function log{
$logUserName = 'logged in UserName';
$LogfileName = YourFILEName;
$LogData = json_decode($this->input->post('something1'), true);
$LogArray = array();
if(is_array($LogData)){
foreach($LogData as $key => $log){
foreach($log as $key1 =>$v){
$LogArray[$key1] = $v;
}
}
$array = array_unique($LogArray, SORT_REGULAR);
foreach ($array as $key => $value) {
$output = $value."<br>";
$contents = $output;
//print_r($contents);
get_file_force_contents($contents,$LogfileName,$logUserName);
}
}
}
// your jquery code
// for input change start
<script type="text/javascript">
var arr = [];
var InputPrevVal;
var InputCurrentVal;
$("input").on("focus",function () {
}).change(function() {
var InputID = $(this).attr('id');
var InputPrevVal = $('#'+InputID).attr('value');
var InputCurrentVal = $(this).val();
if(InputID == 'refrence_name'){
var ValueChangesForInput = 'Enquiry Person: ';
var value = $('#something').html('Updated '+ValueChangesForInput+' '+InputPrevVal+' To '+InputCurrentVal);
arr.push({Reference_Name:$('#something').val()});
}
$('#something1').val(JSON.stringify(arr));
//console.log('Input Changes : '+InputPrevVal+' To '+InputCurrentVal);
});
// for dropdown
var PreviousValue;
var SelectedIdChng;
$("select").on("focus",function () {
var SelectedId = $(this).attr("id");
var PreviousValue = $(this).attr("attr");
}).change(function() {
var SelectedIdChng = $(this).attr("id");
var CurrentValue = $(this).find("option:selected").text();
var PreviousValue = $(this).attr("attr");
if(SelectedIdChng == 'destination'){
var ValueChangesFor = 'Destination: ';
var value = $('#something').html('Updated '+ValueChangesFor+'
'+PreviousValue+' To '+CurrentValue);
arr.push({Destination:$('#something').val()});
}
console.log(arr);
$('#something1').val(JSON.stringify(arr));
});
</script>
// VIEW PAGE
<textarea id="something" name="something" class="" style="width:
1300px; height: 100px;">
</textarea>
<textarea id="something1" name="something1" class=""
style="width: 1300px; height: 100px;"></textarea>
<select name="destination" id="destination" required="" attr="At your
works/Door Delivery">
<option value="">Select</option>
<option value="1" selected="">At your works/Door Delivery</option>
<option value="2">At our works</option>
<option value="3">Godown Delivery</option>
</select>
<input type="text" class="form-control valid" name="refrence_name"
id="refrence_name" placeholder="refrence_name" value="Sonu Vishwakarma">

Sorry, I misunderstood the question.
in your plugin, you will need to save the server data into a javascript element, in which you can use JQUERY to execute.
The fastest way I know in my head at the moment is Cookies.
Create a cookie in PHP and pull it in JS:
$cookie_name = "IP";
$cookie_value = "127.0.0.1"; //add your value here
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
var x = document.cookie;
from there, you can use JQUERY to add to the table:
$('tableid tr:first td').html(x);

Related

Magento : How to display selected custom option price in product detail page In price box

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

Google map show marker not working when called you dropdown select using ajax

I have a contact page where they have multiple branches in countries. So trying to filter the location and on city select it should show the marker with info window. My problem is if I select the city directly it works but when going thru the filer dropdown it doesnt work. Please advice on what am I doing wrong.
This is my link http://www.safarikidindia.com/demo_map.html
here is my code
On country drop down I call onchange='generatestate(this)'> & generate city on state drop down. here is the ajax function code
function generatestate(o)
{
set_current_date_time()
http.abort();
document.getElementById('locationstate').innerHTML = '';
document.getElementById('locationcity').innerHTML = '';
var url = "common_ajax.php?action=showstate&countryid="+o.options[o.selectedIndex].value;
//alert(url);
http.open("GET", url, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
//alert(http.responseText);
//var response = http.responseText;
document.getElementById('locationstate').innerHTML = http.responseText;
// alert(http.responseText);
}
}
http.send(null);
}
function geneeratecity(o)
{
set_current_date_time()
http.abort();
document.getElementById('locationcity').innerHTML = '';
var url = "common_ajax.php?action=geneeratecuty&stateid="+o.options[o.selectedIndex].value;
//alert(url);
http.open("GET", url, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
//alert(http.responseText);
//var response = http.responseText;
document.getElementById('locationcity').innerHTML = http.responseText;
//alert(http.responseText);
}
}
http.send(null);
}
////////////////////////////////
In common_ajax we have following php function
if($action=="showstate")
{
$countryid = trim(filter_var($_REQUEST['countryid'], FILTER_SANITIZE_STRING));
$state = $safari->country_state_location($countryid);
?>
<select name="city" id="city" class="drpdown" onchange="geneeratecity(this);">
<option value="">Select State</option>
<?php
for($i=0;$i<count($state);$i++)
{
$statename = $safari->get_singlestate($state[$i]['state'])
?>
<option value="<?php echo $statename[0]['statesrno'];?>"><?php echo $statename[0]['statename'];?></option>
<?php
}
?>
</select>
<?php
}
if($action=="geneeratecuty")
{
$stateid = trim(filter_var($_REQUEST['stateid'], FILTER_SANITIZE_STRING));
$locations = $safari->country_city_location($stateid);
?>
<select name="city" class="city" id="city">
<option value="" selected>--- Select ---</option>
<?php
for($l=0;$l<count($locations);$l++)
{ ?>
<option value="marker<?php echo $locations[$l]['srno'];?>"><?php echo $locations[$l]['city'];?></option>
<?php } ?>
</select>
<?php
}
?>
The change-listener is bound to the #city-element that exists when you call initialize. When you filter the lists, this element will be overwritten, the newly created select will not listen to the listener.
There may be different ways to fix it, but you already use jQuery, so I would suggest to use jQuery's on() instead of google.maps.event.addDomListener :
jQuery(document).on('change','#city',
function(){
//your code
}
);

PHP with javascript code, live clock

Hey I would to create a live clock to put it on my website. So I wrote a simple php with JavaScript code for that, here is it:
<?php
Function d1() {
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1;
}
?>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
document.getElementById('qwe').innerHTML = '<?php d1();?>';
}
</script>
<div id="qwe">test</div>
When run this code the output like "2:40:17 PM", the div refreshed every second but the problem is the time never changed.
Get the initial time you want to start your clock with from PHP:
<script>
var now = new Date(<?php echo time() * 1000 ?>);
function startInterval(){
setInterval('updateTime();', 1000);
}
startInterval();//start it right away
function updateTime(){
var nowMS = now.getTime();
nowMS += 1000;
now.setTime(nowMS);
var clock = document.getElementById('qwe');
if(clock){
clock.innerHTML = now.toTimeString();//adjust to suit
}
}
</script>
For formatting the date there's a zillion options (MDN Date API: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date)
<script type="text/javascript">
function timedMsg()
{
var t=setInterval("change_time();",1000);
}
function change_time()
{
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if(curr_hour > 12)
curr_hour = curr_hour - 12;
document.getElementById('Hour').innerHTML =curr_hour+':';
document.getElementById('Minut').innerHTML=curr_min+':';
document.getElementById('Second').innerHTML=curr_sec;
}
timedMsg();
</script>
<table>
<tr>
<td>Current time is :</td>
<td id="Hour" style="color:green;font-size:large;"></td>
<td id="Minut" style="color:green;font-size:x-large;"></td>
<td id="Second" style="color:red;font-size:xx-large;"></td>
<tr>
</table>
use this way to display time........
enjoy the above script
You can use ajax to refresh the time:
Example:
<?php
if(#$_GET["action"]=="getTime"){
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1; // time output for ajax request
die();
}
?>
<div id="qwe">test</div>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
AX = new ajaxObject("?action=getTime", showTime)
AX.update(); // start Ajax Request
}
// CallBack
function showTime( data ){
document.getElementById('qwe').innerHTML = data;
}
</script>
<script type="text/javascript">
// Ajax Object - Constructor
function ajaxObject(url, callbackFunction) {
var that=this;
this.updating = false;
this.abort = function() {
if (that.updating) {
that.updating=false;
that.AJAX.abort();
that.AJAX=null;
}
};
this.update =
function(passData,postMethod) {
if (that.updating) { return false; }
that.AJAX = null;
if (window.XMLHttpRequest) {
that.AJAX=new XMLHttpRequest();
}else{
that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (that.AJAX==null) {
return false;
}else{
that.AJAX.onreadystatechange = function() {
if (that.AJAX.readyState==4) {
that.updating=false;
that.callback( that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML, that.AJAX.getAllResponseHeaders() );
that.AJAX=null;
}
};
that.updating = new Date();
if (/post/i.test(postMethod)) {
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+'timestamp='+that.updating.getTime();
that.AJAX.open("POST", uri, true);
that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
that.AJAX.setRequestHeader("Content-Length", passData.length);
that.AJAX.send(passData);
}else{
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+passData+'&timestamp='+(that.updating.getTime());
that.AJAX.open("GET", uri, true);
that.AJAX.send(null);
}
return true;
}
};
var urlCall = url;
this.callback = callbackFunction || function (){};
}
</script>

getting multiple post id wordpress

I am making a voting system for my theme
It is working fine in single.php
But when i keep it in index.php it only considers the id of first post and rest don't work
I think its not dealing with multiple post id
Here is the full code
Setting a cookie, calling Ajax action with jQuery
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$("#vote").not(".disabled").click(function() {
var el = $(this);
el.html('<span id="loader"></span>');
var nonce = $("input#voting_nonce").val();
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: '<?php echo $post->ID; ?>',
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = "<?php echo $post->ID; ?>";
} else {
var newcookie = cookie + ",<?php echo $post->ID; ?>";
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
This is what I put in my functions.php to register actions
add_action("wp_ajax_add_votes_options", "add_votes_options");
add_action("wp_ajax_nopriv_add_votes_options", "add_votes_options");
function add_votes_options() {
if (!wp_verify_nonce($_POST['nonce'], 'voting_nonce'))
return;
$postid = $_POST['postid'];
$ip = $_POST['ip'];
$voter_ips = get_post_meta($postid, "voter_ips", true);
if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
echo "null";
die(0);
} else {
$voter_ips[] = $ip;
update_post_meta($postid, "voter_ips", $voter_ips);
}
$current_votes = get_post_meta($postid, "votes", true);
$new_votes = intval($current_votes) + 1;
update_post_meta($postid, "votes", $new_votes);
$return = $new_votes>1 ? $new_votes." votes" : $new_votes." vote";
echo $return;
die(0);
}
this is how I call my vote button and count button
<?php
// This will display "0 votes" and increase as votes are added
$votes = get_post_meta($post->ID, "votes", true);
$votes = !empty($votes) ? $votes : "0";
if($votes == 1) $plural = ""; else $plural = "s";
echo '<div id="votecounter">'.$votes.' vote'.$plural.'</div>';
?>
<?php
// This will display the vote button and disable it if a cookie has already
// been set. We also add the security nonce here.
$hasvoted = $_COOKIE['better_votes'];
$hasvoted = explode(",", $hasvoted);
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' class="disabled"';
} else {
$vtext = "VOTE";
$class = "";
}
?>
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce', 'voting_nonce'); ?>
As for a beginning, you shouldn't have the same id for your button over and over again, so change this:
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
To this:
<?php
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' disabled';
} else {
$vtext = "VOTE";
$class = "";
}
<?php echo $vtext; ?>
This will result in id attribute of each vote button in the form of "vote-{post id}". And since I guess you still want to address all of your buttons in some way, you can now use the .vote-btn selector.
The problem with your JavaScript is that you pass the ID of the post to the script directly. This is fine, when you have only one post on the page, but when you have multiple posts, you have to either print your code multiple times, or get the post ID dynamically.
I prefer the second option, here's how your JS code should change in order to get that working:
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$(".vote-btn").not(".disabled").click(function() {
var el = $(this),
nonce = $("input#voting_nonce", el.parent()).val(),
id = el.attr('id').replace(/vote-/, ''); // get the Post ID
el.html('<span id="loader"></span>');
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: id,
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = id;
} else {
var newcookie = cookie + "," + id;
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
So, in the above code, we get the ID of the post that the user is voting from, by replacing "vote-" with an empty string(so only the ID remains). Note also the following line:
nonce = $("input#voting_nonce", el.parent()).val(),
In this line, I assume that the nonce input as well as the button have the same parent(although you should be able to use the same nonce for all posts). You can also take your nonce one step further, by changing the code that generates it to:
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce-' . $post->ID, 'voting_nonce'); ?>
And change your add_votes_options function to:
$postid = $_POST['postid'];
if ( ! wp_verify_nonce( $_POST['nonce'], 'voting_nonce-' . $postid ) )
return;
This will bind each nonce to the ID of the post, that the nonce is for.
I think that's pretty much your problem. Please try my code and tell me if there are problems with it(if it's a JS error, please add message from the error console in FireBug, or WebKit's inspector).
PP: Just saw this:
Looking for an answer drawing from credible and/or official sources.
My answer was backed-up by my experience with WordPress and jQuery - and I earn my living by working mainly with WordPress(less jQuery, but I use it relatively often as well). Hope this will be enough :)

loading page through AJAX

<form>
<table>
<tr>
<td>
<input type="tex" id="arheading" name="arheading" value="Article Heading" onfocus="if (this.value == 'Article Heading') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Article Heading';}" />
</td>
<td>
<select id="plaetype" name="placetype">
<option selected="Place Type">Place Type</option>
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM places");
while($row_adm=mysql_fetch_array($result_adm))
{
echo '<option value="'.$row_adm['places'].'">'.$row_adm['places'].'</option>';
}
?>
</select>
</td>
<td>
<select id="country" name="country">
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM countries");
while($row_adm=mysql_fetch_array($result_adm))
{
echo '<option value="'.$row_adm['country'].'">'.$row_adm['country'].'</option>';
}
?>
</select>
</td>
</tr>
</table>
</form>
Above is the code that i want to load on my index page without refreshing or without navigation through AJAX.
and the ajax code i tried to is.........
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
function ajaxpage(url, containerid) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e) {
}
}
}
else
return false
page_request.onreadystatechange = function () {
loadpage(page_request, containerid)
}
page_request.open('GET', url, true)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = page_request.responseText
}
function loadobjs() {
if (!document.getElementById)
return
for (i = 0; i < arguments.length; i++) {
var file = arguments[i]
var fileref = ""
if (loadedobjects.indexOf(file) == -1) { //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js") != -1) { //If object is a js file
fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css") != -1) { //If object is a css file
fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref != "") {
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects += file + " " //Remember this object as being already added to page
}
}
}
and the code that will call for AJAX function is.....
<ul id="admin_menu">
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM adm_tools");
while ($row_adm = mysql_fetch_array($result_adm))
{
echo '<li>' . $row_adm['adm_menu'] . '</li>';
}
?>
</ul>
My ajax code have loaded the page but the php script is not retrieving data from db
It looks like you might be missing the extract($row) function.
That would look like:
while($row_adm=mysql_fetch_array($result_adm))
{
extract($row_adm);
echo '<option value="'.$row_adm['places'].'">'.$row_adm['places'].'</option>';
}

Categories