AJAX Call - Does not recognize wordpress functions / classes - javascript

i have Ajax call for getting response , in response file i have used wordpress loop usng WP_Query() class...
but when i perform ajax it returns Fatal error:
Fatal error: Class 'WP_Query' not found in C:\xampp\htdocs\business-finder\wp-content\themes\businessfinder\metabox\ajax-process.php on line 20
Here is AJAX call code:
var path = 'http://localhost/business-finder/wp-content/themes/businessfinder/metabox/ajax-process.php';
$.ajax({
type: "POST",
url: path,
data: { param:folio_data }
}).done(function( msg ) {
$( '#ajax_folio' ).html( msg );
//alert( "Data Saved: " + msg );
});
Here is response file Code:
<?php
print_r( $_POST['param'] );
if( !empty( $_POST['param'] ) ):
echo spyropress_get_attached_posts1( $_POST['param'], 'ait-grid-portfolio' );
echo '<br><br>';
endif;
function spyropress_get_attached_posts1( $post_id = '', $post_type = '' ){
//if( $post_id = '' || $post_type = '' ) return;
$counter = 0;
global $wp_query ;
$query = new WP_Query( array( 'post_type' => $post_type, 'post__in' => $post_id ) );
if( $query->have_posts() ):
$out .= '<table border = "1">';
while( $query->have_posts() ):
$query->the_post();
if( $counter == 6 ):
$out .= '<tr class = "post_list">';
else:
$counter++;
endif;
$out .= '<td>'.get_the_post_thumbnail(get_the_ID(), array(100,100)).'<br>'.get_the_title().'</td>';
if( $counter == 6 ):
$out .= '</tr>';
$counter = 0;
endif;
endwhile;
$out .= '</table>';
wp_reset_postdata();
else:
$out = 'No Posts Found....';
endif;
wp_reset_query();
return $out;
}
add_action( 'init', 'spyropress_get_attached_posts' );
?>

You have written wrong ajax code. you can not use ajax like this. See below code:
jQuery(document).ready(function($) {
var dataString = {
action: 'my_ajax',
param: folio_data
};
jQuery.ajax
({
type: "POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: dataString,
cache: false,
success: function(msg)
{
$( '#ajax_folio' ).html( msg );
//alert( "Data Saved: " + msg );
}
});
});
function ajaxDataSubmit(){
global $wpdb;
$post_id = $_POST['param'];
$post_type='ait-grid-portfolio';
$counter = 0;
global $wp_query ;
$query = new WP_Query( array( 'post_type' => $post_type, 'post__in' => $post_id ) );
if( $query->have_posts() ):
$out .= '<table border = "1">';
while( $query->have_posts() ):
$query->the_post();
if( $counter == 6 ):
$out .= '<tr class = "post_list">';
else:
$counter++;
endif;
$out .= '<td>'.get_the_post_thumbnail(get_the_ID(), array(100,100)).'<br>'.get_the_title().'</td>';
if( $counter == 6 ):
$out .= '</tr>';
$counter = 0;
endif;
endwhile;
$out .= '</table>';
wp_reset_postdata();
else:
$out = 'No Posts Found....';
endif;
wp_reset_query();
die($out);
}
add_action('wp_ajax_my_ajax', 'ajaxDataSubmit');//Logged in users
add_action('wp_ajax_nopriv_my_ajax', 'ajaxDataSubmit'); // Not logged in uNOTE: mer

Related

How can I get similar count of data

I want to get set if statement of no. of count of array from database. I already have a if statement checking the count but I am unable to use it in my file.
Help me replicate the count if statement here. I want to wrap pro_type and is_pro in if statement of no. of counts similar in reaferandearn page .
My function where I need if count statement :
users.php file
public function update_valid_refer_point($id){
global $db;
$user_balance = $db->where('id',$id)
->getOne('users',array('balance'));
$_POST['pro_type'] =4;
$_POST['is_pro'] =1;
$bal =$user_balance['balance']+500;
$updated = $db->where('id', $id)
->update('users', array('pro_type' => 4,'is_pro' => 1,'balance' => $bal));
return TRUE;
}
The file where I have similar if count statement but I have no idea how to use it above :
referandearn.php
if(count($data['refferal_data']['data']) > 0){
for($u=0; $u<count($data['refferal_data']['data']);$u++){
$userFirstName = $data['refferal_data']['data'][$u]->first_name;
$userLastName = $data['refferal_data']['data'][$u]->last_name;
$userName = $userFirstName.' '.$userLastName;
$userProfilePhoto = $data['refferal_data']['data'][$u]->avater;
$refferalDate = date('d - M - Y',strtotime($data['refferal_data']['data'][$u]->refferalDate));
$userRefferalCode = $data['refferal_data']['data'][$u]->refferalCode;
?>
<li>
<img src="<?php echo $userProfilePhoto;?>" width="75" height="75" viewBox="0 0 24 24" style="margin-right: 15px; border-radius: 50%;"/>
<?php echo $userName."<br>".$refferalDate;?>
</li>
<?php
}
}else{
?>
<li>
<?php echo 'No reffered user yet';?>
</li>
<?php
}
?>
referandearn controller :
Class Referearn extends Theme {
public static function LoadreffralUsers() {
global $_AJAX, $_CONTROLLERS;
$data = '';
$ajax_class = realpath($_CONTROLLERS . 'aj.php');
$ajax_class_file = realpath($_AJAX . 'loadmore.php');
if (file_exists($ajax_class_file)) {
require_once $ajax_class;
require_once $ajax_class_file;
$_POST['page'] = 1;
$loadmore = new Loadmore();
$refferal_users = $loadmore->refferal_users();
parent::$data['refferal_data'] = $refferal_users;
/*if (isset($refferal_users['html'])) {
$data = $refferal_users['html'];
}*/
}
return $data;
}
}
And loadmore referusers function :
function refferal_users() {
global $db, $_BASEPATH, $_DS,$_excludes;
if (self::ActiveUser() == NULL) {
return array(
'status' => 403,
'message' => __('Forbidden')
);
}
$error = '';
$page = 0;
$perpage = 7;
$html = '';
$html_imgs = '';
$template = '';
if (isset($_POST) && !empty($_POST)) {
if (isset($_POST[ 'page' ]) && (!is_numeric($_POST[ 'page' ]) || empty($_POST[ 'page' ]))) {
$error = '<p>• ' . __('no page number found.') . '</p>';
} else {
$page = (int) Secure($_POST[ 'page' ]) - 1;
}
}
if ($error == '') {
$limit = $perpage;
$offset = $page * $perpage;
//$query = GetRefferalUserQuery(self::ActiveUser()->id, $limit, $offset);
//exit;
//$refferal_users = $db->rawQuery($query);
$sql = 'SELECT U.id,U.online,U.lastseen,U.username,U.avater,U.country,U.first_name,U.last_name,U.location,U.birthday,U.language,U.relationship,U.height,U.body,U.smoke,U.ethnicity,U.pets,U.gender, RU.refferalDate, RU.refferalCode FROM users U INNER JOIN refferalusers RU ON RU.refferalBy = U.id ';
$sql .= ' WHERE RU.refferalTo = '.self::ActiveUser()->id.' AND ( ';
$sql .= ' U.verified = "1" AND U.privacy_show_profile_random_users = "1" ';
// to exclude blocked users
$notin = ' AND U.id NOT IN (SELECT block_userid FROM blocks WHERE user_id = '.self::ActiveUser()->id.') ';
// to exclude liked and disliked users users
$notin .= ' AND U.id NOT IN (SELECT like_userid FROM likes WHERE ( user_id = '.self::ActiveUser()->id.' OR like_userid = '.self::ActiveUser()->id.' ) ) ';
$sql .= ' ) ';
$sql .= ' ORDER BY U.id DESC LIMIT '.$limit.' OFFSET '.$offset.';';
$random_users = $db->objectBuilder()->rawQuery($sql);
$theme_path = $_BASEPATH . 'themes' . $_DS . self::Config()->theme . $_DS;
//$template = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'random_users.php';
//$template1 = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'matches_imgs.php';
if (file_exists($template)) {
foreach ($random_users as $random_user) {
if($random_user->id!=(int)auth()->id){
ob_start();
require($template);
$html .= ob_get_contents();
ob_end_clean();
}
}
}
return array(
'status' => 200,
'page' => $page + 2,
'html' => $html,
'data' => $random_users
);
} else {
return array(
'status' => 400,
'message' => $error
);
}
}

jquery ajax not working without loading a page

`
$previous_year = $year = 0;
$previous_month = $month = 0;
$ul_open = false;
$myposts = get_posts(array(
'numberposts' => $numposts,
'orderby' => 'post_date',
'order' => 'DESC'
));
foreach ($myposts as $post) : ?>
$year = mysql2date('Y', $post->post_date);
$month = mysql2date('n', $post->post_date);
$day = mysql2date('j', $post->post_date);
?>
http://localhost/klientasnew/archives/?=01">
jQuery(document).ready( function(){
jQuery('#df').on('click', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'href' );
jQuery.ajax({
url : '/archives?=',
type : 'post',
data : {
post_id : rml_post_id
},
success : function( response ) {
//jQuery('#dd').html(response);
alert(response);
}
});
jQuery(this).hide();
});
});
`
<?php $numposts = -1; <br>
$previous_year = $year = 0;
$previous_month = $month = 0;
$ul_open = false;
$myposts = get_posts(array(
'numberposts' => $numposts,
'orderby' => 'post_date',
'order' => 'DESC'
));?>
$year = mysql2date('Y', $post->post_date);
$month = mysql2date('n', $post->post_date);
$day = mysql2date('j', $post->post_date);?>
" >
$(document).ready(function(){
$(".get_project").click(function(){
var id = $(this).attr("data_id");
var data = '?='+ encodeURIComponent(id); // this where i add multiple data using ' & '
//alert(data);
$.ajax({
type:"GET",
url: "/archives" + data,
success: function(html){
$(".blg-bck").html(html);
}
});
});
});
Try this code
<?php
$numposts = -1;
$previous_year = $year = 0;
$previous_month = $month = 0;
$ul_open = false;
$myposts = get_posts(
array(
'numberposts' => $numposts,
'orderby' => 'post_date',
'order' => 'DESC',
)
);
?>
<?php foreach ( $myposts as $post ) : ?>
<?php
setup_postdata( $post );
$year = mysql2date( 'Y', $post->post_date );
$month = mysql2date( 'n', $post->post_date );
$day = mysql2date( 'j', $post->post_date );
?>
<?php if ( $year != $previous_year || $month != $previous_month ) : ?>
<?php if ( $ul_open == true ) : ?>
<?php endif; ?>
<li><a id="df" rel="<?php echo get_the_date( 'm' ); ?>" href="
<?php
echo site_url();
?>
/archives?=<?php echo get_the_date( 'm' ); ?>" onclick="return loadmore();">
<span><?php the_time( 'F Y' ); ?></span></a>
</li>
<?php $ul_open = true; ?>
<?php endif; ?>
<?php
$previous_year = $year;
$previous_month = $month;
?>
<script type="text/javascript">
function loadmore(){
e.preventDefault();
var rml_post_id = jQuery(this).data( 'href' );
jQuery.ajax({
url : rml_post_id,
type: 'post',
data: {
post_id: rml_post_id
},
success : function( response ) {
//jQuery('#dd').html(response);
alert(response);
return false;
}
});
jQuery(this).hide();
}
</script>
<?php endforeach; ?>

Modify DOM and replace mail addresses

I would like to make use of Simple HTML DOM parser to search for mail-adresses in the content of a html-site and replace them.
The replacement contains a span element and a little bit JS (this should obfuscate the addresses.
At the moment this works as follows:
$pattern =
"/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/";
preg_match_all( $pattern, $content, $matches );
foreach ( $matches[ 0 ] as $email ) {
$content = $this->searchDOM(
$content,
$email,
$this->hide_email($email)
);
}
This is the searchDOM-method:
private function searchDOM( $content, $search, $replace, $excludedParents = [] )
{
$dom = HtmlDomParser::str_get_html(
$content,
true,
true,
DEFAULT_TARGET_CHARSET,
false,
DEFAULT_BR_TEXT,
DEFAULT_SPAN_TEXT
);
foreach ( $dom->find( 'text' ) as $element ) {
if ( !in_array( $element->parent()->tag, $excludedParents ) ) {
$element->innertext = preg_replace(
'/(?<!\w)' . preg_quote( $search, "/" ) . '(?!\w)/i',
$replace,
$element->innertext
);
}
}
return $dom->save();
}
and this is the hide_email-method:
function hide_email( $email )
{
$character_set = '+-.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
$key = str_shuffle( $character_set );
$cipher_text = '';
$id = 'e' . rand( 1, 999999999 );
for ( $i = 0; $i < strlen( $email ); $i += 1 )
$cipher_text .= $key[ strpos( $character_set, $email[ $i ] ) ];
$script = 'var a="' . $key . '";var b=a.split("").sort().join("");var c="' . $cipher_text . '";var d="";';
$script .= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
$script .= 'document.getElementById("' . $id . '").innerHTML=""+d+""';
$script = "eval(\"" . str_replace( [ "\\", '"' ], [ "\\\\", '\"' ], $script ) . "\")";
$script = '<script type="text/javascript">/*<![CDATA[*/' . $script . '/*]]>*/</script>';
return '<span id="' . $id . '">[javascript protected email address]</span>' . $script;
}
Well - this is not working as expected, because the rendered page shows only "[javascript protected email address]". If I have a look at the source, the a-tag is missing.

Unable to insert Ajax return into HTML

I'm trying to use a PHP file to process serialized info from an Ajax request. I want to send back the value of each form field to be further manipulated by javascript (inserted into a div). The result is not being inserted into the HTML. When I alert the result I get {"return":["<p>form value for name<\/p>","<p>form value for description<\/p>"]} Any suggestions?
EDIT: Updated question with relevant HTML and revised PHP code.
HTML:
<div class="col-md-4">
<h5>Heading</h5>
<div id="formBasicResults"></div>
</div>
Javascript:
.on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('formValidation');
$.post($form.attr('action'), $form.serialize())
.done(function (result) {
$('#formBasicResults').html(result.responseText);
alert(result);
},'json');
});
PHP:
if (!isset($_SESSION)) {
session_start();
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
} else {
$token = $_SESSION['token'];
}
}
foreach($_POST as $key = > $value) {
$temp = is_array($value) ? $value : trim($value);
$_SESSION[$key] = $temp;
}
$expected = array(
'name' = > 'string',
'description' = > 'string',
);
foreach($expected AS $key) {
if (!empty($_POST[$key])) {
$ {$key} = $_POST[$key];
} else {${$key} = NULL;
}
}
foreach($expected AS $key = > $type) {
if (empty($_POST[$key])) {
$ {$key} = NULL;
continue;
}
if (!isset($ {
$key})) {
$ {$key} = NULL;
}
}
function safe( $value ) {
htmlentities( $value, ENT_QUOTES, 'utf-8' );
return ($value);
}
$name = $_POST['name'];
$description = $_POST['description'];
$return['result']=array();
if(!empty($name)){$return['result'][]= '<p>' . safe($name) . '</p>';}
if(!empty($description)){$return['result'][]= '<p>' . safe($description) . '</p>';}
echo json_encode($return);
try something like this:
$('#formBasicResults').html(result['return'][0]);
or
$('#formBasicResults').html(result['return'][1]);
Instead of this:
if ($_POST['token'] == $_SESSION['token'])
{$return['return']=array();
if(!empty($_POST['name'])){$return['return'][] = '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){$return['return'][] = '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
echo json_encode($return); }}
do this:
$return['responseText']='';
if ($_POST['token'] == $_SESSION['token'])
{
if(!empty($_POST['name'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
}
}
echo json_encode($return);

Cannot retrieve json string from php using ajax

I can't retrieve json string data from my php script using ajax call.
Here is my ajax script :
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(data){
$("#app_panel").append(data.html);
$('.inv_date').hide();
}
});
and this is my php script:
<?php
//wall ===================================================
session_start();
include("../../dbinfo.inc.php");
$from = $_POST['from'];
$to = $_POST['to'];
$sel = $_POST['sel'];
// connect to the database
$client_id = $_SESSION['clientid'];
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
$results = array(
'html' => $html
);
$html = " ";
if($sel == "all"){
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
}else{
$query=" select * from tele_panel_call where (client='$client_id' AND date_time BETWEEN '$from' AND '$to') ORDER BY date_time DESC";
$result = $mysqli->query($query);
}
if ($result->num_rows > 0){
while ($row = $result->fetch_object())
{
$from = $row->from;
$to = $row->to;
$html .= '<div style="width:590px;height:15px;background: url(img/clientimg/wrap-white.png)repeat;padding: 5px 5px 5px 5px;margin-bottom:5px;">';
$query_from=" select * from tele_agent_dialer where (client='$client_id' AND (dialer='$from' OR dialer='$to'))";
$result_from = $mysqli->query($query_from);
$row_from = $result_from->fetch_assoc();
$dialer = $row_from['dialer'];
if($dialer == $from){
$image = 'outgoing';
$out = $out+1;
}
if($dialer == $to){
$image = 'incoming';
$in = $in+1;
}
if($dialer != $to & $dialer != $from){
$image = 'extension';
$ext = $ext+1;
}
$html .= '<img src="img/clientimg/'; $html .= $image; $html .= '.png" style="float:left;margin-right:10px;height:15px">';
$html .= '<div style="float:left;margin-right:5px;width:135px;height:30px;overflow:hidden;"><b>From: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $from, $matches ) )
{
$from = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $from;
$html .= '</div>
<div style="float:left;margin-right:5px;width:125px;height:30px;overflow:hidden;">
<b>To: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $to, $matches ) )
{
$to = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $to;
$html .= '</div>
<div style="float:left;width:160px;margin-right:5px;height:30px;overflow:hidden;">
<b>Date/Time: </b>'; $html .= $row->date_time;
$html .= '</div>
<div style="float:left;width:100px;margin-right:5px;height:30px;overflow:hidden;">
<b>Duration: </b>';
$duration = $row->duration;
preg_match("#(\d+):(\d+)#", $duration, $matches );
$min = $min + $matches[1];
$sec = $sec + $matches[2];
$html .= $duration;
$html .= '</div>';
$html .= '</div>';
}
}else{
echo "No results to display!";
}
$jsonString = json_encode($results);
echo $jsonString;
$mysqli->close();
?>
Can someone please tell me what I'm doing wrong here? My php script doesn't have any errors when I check the page itself.
Also it's good to add proper header for json data output (at the begining of the script for example).
header("Content-Type: application/json");
As for query results, you should debug it. Try to print the query and run it in Phpmyadmin (or other database administration tool)

Categories

Resources