I'm hacking away at some code in order to have it register a click on an invisible div element, which expands an article to reveal it's excerpt while adding a +1 to the number of time's it's been clicked by anyone. Afterwards it updates an element with ajax with the number of clicks it's received.
At least, that's the goal.
The following code ends up breaking Wordpress and gives me the white screen of doom. This is taken from a simple click counter with an Ajax callback to update the number.
Where my problem lies is hacking away at this for it to register clicks on a different element.
Without wasting too much of anyones time, here's my question:
Wouldn't I just need to rename all post_like to post_reader? Someone's been telling my in person that it should work so check your server but that is ridiculous... it seems.
Note, below where you see post_reader, it had said post_like previously.
// post click to expand button
$timebeforerevote = 1;
add_action('wp_ajax_nopriv_post-like', 'post_reader');
add_action('wp_ajax_post-like', 'post_reader');
wp_localize_script('like_post', 'ajax_var', array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce')
));
function post_like()
{
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Busted!');
if(isset($_POST['post_reader']))
{
$ip = $_SERVER['REMOTE_ADDR'];
$post_id = $_POST['post_id'];
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$meta_count = get_post_meta($post_id, "votes_count", true);
if(!hasAlreadyVoted($post_id))
{
$voted_IP[$ip] = time();
update_post_meta($post_id, "voted_IP", $voted_IP);
update_post_meta($post_id, "votes_count", ++$meta_count);
echo $meta_count;
}
else
echo "already";
}
exit;
}
function hasAlreadyVoted($post_id)
{
global $timebeforerevote;
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$ip = $_SERVER['REMOTE_ADDR'];
if(in_array($ip, array_keys($voted_IP)))
{
$time = $voted_IP[$ip];
$now = time();
if(round(($now - $time) / 60) > $timebeforerevote)
return false;
return true;
}
return false;
}
function getPostReadLink($post_id)
{
$themename = "toolbox";
$vote_count = get_post_meta($post_id, "votes_count", true);
$output = '<div class="post-read">';
if(hasAlreadyVoted($post_id))
$output .= ' <span title="'.__('I like this article', $themename).'" class="qtip like alreadyvoted"></span>';
else
$output .= '<a href="#" data-post_id="'.$post_id.'">
<span title="'.__('I like this article', $themename).'"class="qtip like"></span>
</a>';
$output .= '<span class="count">'.$vote_count.'</span></div>';
return $output;
}
The function called when clicked:
jQuery(".expand").click(function(e){
e.preventDefault();
readers = jQuery(this);
// Retrieve post ID from data attribute
post_id = readers.data("post_id");
// Ajax call
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-reader&nonce="+ajax_var.nonce+"&post_reader=&post_id="+post_id,
success: function(count){
// If vote successful
if(count != "already")
{
heart.addClass("readered");
heart.siblings(".count").text(count);
}
}
});
return false;
})
Invoking it within the appropriate div.
<?php echo getPostReadLink(get_the_ID());?>
Related
I have created a search using ajax and php, however when I click the search button nothing happens. There are no errors, however when I look at the network in the console it doesn't seem to be reaching searching.php as this file doesn't show up in the network. I want to be able to put the returned data from the search into seperate divs, although at the minute it isn't returning any data at all and I have no idea why.
This is my php
require_once('config1.php');
$output = '';
if(isset($_POST['search']) === true && empty($_POST['search']) === false){
$query = "SELECT a.attraction_name, a.lat, a.long, a.cost, a.image FROM zz_attractions a INNER JOIN zz_city c ON a.city_id = c.city_id WHERE c.city_name = '" . mysqli_real_escape_string(trim($_POST['search'])) . "' ";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count == 0) {
$output = 'there was no search results';
} else {
while ($row = mysqli_fetch_array($result)) {
$attraction_name = $row['attraction_name'];
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$image = "<img src='{$row['image']}' height='100' width='100'>";
$output .= '<div>'.$attraction_name.' '.$lat.' '.$long.' '.$cost.' '.$image.'</div>';
}
}
}
This is my ajax
$('#submit').on('click', function() {
var search = $('#search').val();
if ($.trim(search) != '') { //if search is not equal to nothing - using trim allows users to type in blank space and it won't return anything
$.post('searching.php', {search: search}, function(data) {
$('#return').text(data);
});
}
});
Within the html the div id is #return. If someone could help me find out why no data is returning that would be great.
I have currently implemented a live search (search as you type) function on text fields. The flow is something like this.
Call a .js file inside the page.
Set the id of the text field to "client-search".
Inside the .js file it is currently listening for on key up events of the "client-search" text field.
If the on key up event is fired, the .js file calls a PHP file that searches the database and returns the output as a list item in an unordered list underneath the "client-search" text field.
This setup currently works but how do implement it in multiple fields inside a single page, since it works using "id" and obviously I can't have multiple IDs in a single page.
HTML:
<div class="input-group">
<input type="text" id="client-search" class="form-control" placeholder="Search for manager...">
<ul class="livesearch" id="client-result" onclick="clickResult()"></ul>
</div>
JS
/* JS File */
// Start Ready
$j(document).ready(function() {
// Icon Click Focus
$j('div.icon').click(function(){
$j('input#client-search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#client-search').val();
$j('b#search-string').text(query_value);
if(query_value !== ''){
$j.ajax({
type: "POST",
url: "clientsearch.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#client-result").html(html);
}
});
}return false;
}
$j("input#client-search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$j("ul#client-result").fadeOut();
}else{
$j("ul#client-result").fadeIn();
$j(this).data('timer', setTimeout(search, 100));
};
});
});
PHP:
<?php
$serverName = "(local)";
$connectionInfo = array( "Database"=>"CMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
} else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$html = '';
$html .= '<li value="myLi" class="myLi">';
$html .= '<small>nameString</small>';
$html .= '<small></small>';
$html .= '</li>';
$search_string = $_POST['query'];
//$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$sql = "SELECT TOP 10 ClientName FROM Client WHERE ClientName LIKE '%" . $search_string . "%'";
$params = array($search_string);
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results_array[] = $row;
}
if (isset($results_array)) {
foreach ($results_array as $result) {
$display_function = $result['ClientName'];
$display_name = $result['ClientName'];
$output = str_replace('nameString', $display_name, $html);
//$output = str_replace('functionString', $display_function, $output);
echo($output);
}
}else{
$output = str_replace('nameString', '<b>No Results Found.</b>', $html);
$output = str_replace('functionString', 'Sorry :(', $output);
echo($output);
}
}
?>
I have : Html + jQuery + ajax post and a PHP file to process the form values and returning a error(true or false) and a message with html markups.
My javascript code:
$(document).ready(function() {
var form = $('#form'); // contact form
var submit = $('#submit'); // submit button
var alert = $('.alert'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'contact.php', // form action url
type: 'post', // form submit method get/post
dataType: 'json', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(result) {
if(result.error){
/* On error stuff */
alert(result.html).fadeIn();
}else{
/* On success stuff */
alert(result.html).fadeIn();
}
}
});
});
});
and at last my php:
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$result = array("error" => false, "html" => null);
$vars = array('name', 'email','telefoonnummer', 'message');
$verified = TRUE;
foreach($vars as $v) {
if(!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if(!$verified) {
$result["error"] = true;
$result["html"] = "<b>Error11</b>";
echo json_encode($result);
exit;
}
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$tel= filter_var($_POST['telefoonnummer'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$to = '';
$sent = email($to, $email, $name, $tel, $message);
if ($sent) {
$result["error"] = false;
$result["html"] = "<b>Success</b>";
echo json_encode($result);
} else {
$result["error"] = true;
$result["html"] = "<b>Error</b>";
echo json_encode($result);
}
return;
}
/**
* Email send with headers
*
* #return bool | void
**/
function email($to, $name, $email, $tel, $message){
$header = array();
$header[] = "MIME-Version: 1.0";
$header[] = "From: <".$name."> <".$email.">";
/* Set message content type HTML*/
$header[] = "Content-type:text/html; charset=iso-8859-1";
$header[] = "Content-Transfer-Encoding: 7bit";
if( mail($to, $tel, $message, implode("\r\n", $header)) ) return true;
}
Ok.. now that's clear I know something goes wrong with the error returning, it does show up and then goes away again n my html so I don't know what exactly happens there..
I don't want "fixes" just so i can copy paste the code but an explanation of what happened and what goes wrong and how to solve it (at least then I learn a little)
You are using alert in two different ways... One time as an object, one time as a function. The latter is probably what causes the undesired effect. Look closely at the brackets after alert;
alert() is a function
alert. signafies it's an object
We cannot use jquery chaining method in alert function.
I want to show a message displaying the result of each iteration of a for loop in php.
I have tried several methods using jquery, ajax etc but they doesn't seem to fit my needs or either i am not getting to work around with them.
What my script does?
It scans a website, grab some links, then visits each link one by one and grab an image from each page and finally send it to my wordpress including its title and image.
What's the problem?
The problem is that as there can be several links (more than 200), so even though my scripts displays message regarding the success but it shows the messages after the whole loop is finished executing.
What I want to do?
Now, what i want to do that during each iteration the message should be shown on the browser rather than waiting for the loop to complete i.e. during 1st iteration (Posted Successfully) then during 2nd (Not Posted) and so on...
Here is the code:
<?php
$category = array();
for ($i = 0; $i < count($result); $i++)
{
set_time_limit(30);
// Check if post already exists
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts .
' WHERE post_name = %s',sanitize_title_with_dashes($result[$i]->title));
$cID = $wpdb->get_var($query);
if (!empty($cID))
{
echo $result[$i]->title .
" <font style='color:#FF0000; font-weight:bold;'>Already Exists.</font><br />";
} else
{
$inner_html = file_get_html($result[$i]->href);
$inner_result_image = $inner_html->find('meta[property=og:image]',1);
$inner_result_cats = $inner_html->find('a[rel=category tag]');
$title = $result[$i]->title;
$body = "<a href='$inner_result_image->content'><img src='$inner_result_image->content' /></a>";
// Automatically Create new Category if it doesn't exist.
foreach ($inner_result_cats as $cats)
{
if (!($cats->innertext == "Jobs"))
{
array_push($category,$cats->innertext);
$count = 0;
// For Cities
if (search_city($cats->innertext))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '14')); // Jobs by City
} else
{
$count += 1;
}
// For Qualification
if (search_qualification($cats->innertext))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '51')); // Jobs by Qualification
} else
{
$count += 1;
}
// International Jobs
if (check_international(parse_url($cats->href,PHP_URL_PATH)))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '52')); // International Jobs
} else
{
$count += 1;
}
if ($count == 3)
{
wp_insert_term($cats->innertext,'category',array('description' => '','slug' =>
''));
}
} // End if NewsPaper Check
} // End if Auto Category
echo "<br />";
$postdate = new IXR_Date(strtotime($date));
$title = htmlentities($title,ENT_NOQUOTES,"UTF-8");
$content = array(
'title' => $title,
'description' => $body,
'mt_allow_comments' => 1, // 1 to allow comments
'mt_allow_pings' => 1, // 1 to allow trackbacks
'post_type' => 'post',
'date_created_gmt' => $postdate,
'categories' => $category,
);
// Create the client object
$client = new IXR_Client('http://localhost/FDJ/xmlrpc.php');
$username = "Admin";
$password = "Password";
$params = array(0,
$username,
$password,
$content,
true); // Last parameter is 'true' which means post immediately, to save as draft set it as 'false'
// Run a query for PHP
if (!$client->query('metaWeblog.newPost',$params))
{
die('Something went wrong - ' . $client->getErrorCode() . ' : ' . $client->
getErrorMessage());
echo $title . " <font style='color:#FF0000; font-weight:bold;'>Not Posted.</font><br />";
} else
echo $title . " <font style='color:#00FF00; font-weight:bold;'>Posted Successfully.</font><br />";
}
} // End if Main
?>
I have a piece of code which is giving me trouble.
I am trying to get order values from a php class function :
public function generalSettings(){
$totalprijs = 0;
foreach($_SESSION['items'] as $key => $value){
$products->setProduct($key);
$totalprijs = $totalprijs + ($products->prijs_exBTW * $value);
}
$inclbtw = ($totalprijs * ('1.'.$this->BTWPercnt));
if($totalprijs > $this->franco_vanaf){
$verzendkosten = 0;
}else{
$verzendkosten = $this->verzendkosten;
}
$btw = ($totalprijs + $verzendkosten) * ('0.'.$this->BTWPercnt);
if($totalprijs > $this->franco_vanaf){
$totaalInc = ($totalprijs + $btw);
}else{
$totaalInc = ($totalprijs + $btw + $this->verzendkosten);
}
$return = array(
"subtotaal" => $totalprijs,
"btw" => $btw,
"inclbtw" => $inclbtw,
"verzendkosten" => $verzendkosten,
"totaalInc" => $totaalInc
);
return($return);
}
When I access this function from within the class it works.
And when I call other function that uses this function in my checkout it works.
But when I try to access it in my AJAX-handling file it says:
Warning: Invalid argument supplied for foreach()
The code,when I call the function in the ajax file is as below:
if($isValid == true){
unset($notneeded);
$notneeded = array("ww1","ww2","huisnr","vhuis","companyvat","companyname","tel","firstname","lastname");
foreach($_POST['gegevens'] as $key => $value){
if(in_array($key,$verplichtArray) && (!in_array($key,$notneeded))){
$fields .= "`".$key."`,";
$values .= "'".$value."',";
}
}
$shoppingcar = new Winkelwagen;
$order = $shoppingcar->generalSettings();
$fields .= '`timestamp`,`klant`,`totaal`,`totaalInc`,`verzendkosten`,`status`,`betaalmethode`';
$values .= "now(),'".$acc->id."','".$order['subtotaal']."','".$order['totaalInc']."','".$order['verzendkosten']."','3','".mysql_real_escape_string($_POST['betaalwijze'])."'";
if(isset($_POST['gegevens']['V'])){
$fields .= ',`V`';
$values .= ",'X'";
}
$message = "INSERT INTO order (".$fields.") VALUES (".$values.")";
}
It seems like when I call the function from the ajax file the session's empty
but when I call the function from the file where I call to the ajax file it works just fine.
Could anyone explain what I'm doing wrong???
EDIT
The piece of jquery i use to call the ajax file as requested:
$('#afrekenen').click(function(){
clearInterval(myInterval);
var fields = $('.addressform :input');
$.each(fields, function(field,val){
$(val).removeClass('errorInput');
})
var gegevens = {};
var adresform = $('.addressform').serializeArray();
$.each(adresform, function(index, val){
gegevens[this.name] = this.value;
});
if(!$('input[name=payment]:checked').val()){
var betaalwijze = 0;
}else{
var betaalwijze = $('.betaalwijze').val();
}
var voorwaarden = $('input[name=voorwaarden]:checked').val();
$.ajax({
type: 'post',
url: '/inc/afrekenen.php',
data: {"gegevens":gegevens ,"betaalwijze":betaalwijze,"voorwaarden":voorwaarden},
success: function(data) {
response = jQuery.parseJSON(data)
if(response.isValid == false){
$('#errormsg').html('<div class="alert alert-danger">'+
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
+response.message+'</div>');
$.each(response.fouteVelden, function(index, object){
$('#'+object+'').addClass('errorInput');
});
}else{
$('#errormsg').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
+response.message+'</div>');
}
}
});
});
if have the
ob_start(); tag and the session_start(); tag
also only the sessions that are somehow linked to my class are returning 1 when i try to print_r them the rest of my sessions still remain
the foreach through the $_SESSION['item'] in the first part of my code isn't working
all the other parts of code work
EDIT
A good nights sleep seems to have solved the conflict...
don't know what the error was and don't know how i fixed it but it works!
Thank you for the suggestions :)
if /inc/afrekenen.php is in the same domain as your class then session is shared
and phpsid cookie is passed along your ajax request.
In this case, the only problem would your session not being started in /inc/afrekenen.php.
Verify that session is started in /inc/afrekenen.php.
// print $_POST['gegevens'] if it is returning you a json string so
// do this
$postDataGegevens = json_decode($_POST['gegevens']);
// if $postDataGegevens in current format
// then pass in foreach
foreach($postDataGegevens as $key => $value){
// your code here ...
}
I noticed that my sessions where saved in
session_save_path('../tmp');
added this to the top of my ajax file and it worked it's magic
Thank you for the suggestions