jquery ajax not working without loading a page - javascript

`
$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; ?>

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

Unble to display json code correct on morris.js bar

I have a controller function where it gets my json data for my bar graph
The json code from controller is
{"xkey":[["0","Sun"],["1","Mon"],["2","Tue"],["3","Wed"],["4","Thu"],["5","Fri"],["6","Sat"]],"user":[[2,"1"],[3,"1"]]}
Question from the controller function how am I able to pass the
json['xkey'] and json['user'] to my script
I have looked at Morris Js and Codeigniter pass data from a controller but not work for me.
Here is what I have tried
<script type="text/javascript">
$( document ).ready(function() {
$('#range').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'get',
url: "<?php echo base_url('admin/dashboard/chart/chart_data');?>/" + $( "#range" ).val(),
dataType: 'json',
success: function(json) {
if (typeof Morris != 'undefined') {
Morris.Bar({
element: 'bar-example',
resize: true,
stacked: false,
xLabelAngle: 50,
grid: true,
gridTextSize: 10,
data: [{m: json['xkey'] a: json['user']}],
xkey: 'm',
ykeys: ['a'],
labels: ['Users']
});
}
}
});
});
});
</script>
Controller
<?php
class Chart extends MX_Controller {
public function index() {
return $this->load->view('template/dashboard/chart_view');
}
public function chart_data() {
$json = array();
$json['xkey'] = array();
$json['user'] = array();
$uri_segment = $this->uri->segment(5);
if (isset($uri_segment)) {
$range = $uri_segment;
} else {
$range = 'month';
}
switch ($range) {
case "week":
$results = $this->getUserTotalByWeek();
foreach ($results as $key => $value) {
$json['user'][] = array($key, $value['total']);
}
$date_start = strtotime('-' . date('w') . ' days');
for ($i = 0; $i < 7; $i++) {
$date = date('Y-m-d', $date_start + ($i * 86400));
$json['xkey'][] = array(date('w', strtotime($date)), date('D', strtotime($date)));
}
break;
default:
echo "Your favorite color is neither red, nor green!";
}
$this->output->set_header('Content-Type: application/json; charset=utf-8');
$this->output->set_output(json_encode($json));
}
public function getUserTotalByWeek() {
$user_data = array();
$date_start = strtotime('-' . date('w') . ' days');
for ($i = 0; $i < 7; $i++) {
$date = date('Y-m-d', $date_start + ($i * 86400));
$customer_data[date('w', strtotime($date))] = array(
'day' => date('D', strtotime($date)),
'total' => 0
);
}
$this->db->select('COUNT(*) AS total, date_reg');
$this->db->from('user');
$this->db->where('date_reg >=', date('Y-m-d', $date_start));
$this->db->group_by('DAYNAME(date_reg)');
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$user_data[date('w', strtotime($result['date_reg']))] = array(
'day' => date('D', strtotime($result['date_reg'])),
'total' => $result['total']
);
}
return $user_data;
}
}

How to pass a PHP array to another PHP page with ajax

I have been looking for this answer without success.
I have three files: index.php, actions.js and devices.php
My index.php have this code:
<?php
$file = "canvas/interactiveWorkstations/".$roomData['id'].".json";
if(file_exists($file)){
$map = "interactiveWorkstation";
$lines = file($file);
$nPolygon = $lines[count($lines) - 4];
$counterPolygon = 0;
$pos = 4;
$areas = array();
while($counterPolygon !== $nPolygon && $pos < count($lines)){
$lines[$pos] = json_decode($lines[$pos], true);
if($counterPolygon !== 0)
$lines[$pos] = array_diff_assoc($lines[$pos], $lines[$pos-9]);
$coords = "";
foreach($lines[$pos] as $line)
foreach($line as $k => $v)
if($k !== "color" && $v !== -1)
$coords .= $v . ", ";
$coords = trim($coords, ', '); //Delete last space and last comma
$lines[$pos-3] = trim($lines[$pos-3], '#');
$areas[trim($lines[$pos-3])] = $coords;
$counterPolygon++;
$pos = $pos + 9;
}
?>
<script>
var img = document.getElementsByClassName('connection')[0];
img.setAttribute('usemap', '<?php echo "#".$map; ?>');
img.insertAdjacentHTML('afterend', '<map name="<?php echo $map; ?>" id="<?php echo $map; ?>"></map>');
var points = <?php echo json_encode($areas);?>;
</script>
<?php
}
if($bookingActive) {
echo '<script type="text/javascript">reloadDevices("'.$workstationName.'","'.$randomKey.'","'.$bookingData['ical_uid'].'",points); initCountdown('.$remainingTime.');</script>';
}
At this point I have passed my $areas variable to JS using json_encode, and my functions reloadDevices() and UpdateDevices() receive it correctly because I checked before.
In my actions.js file have this code:
function updateDevices(workstation,randomKey,z,points){
var parameters = {
"workstation" : workstation,
"randomKey" : randomKey,
"z" : z,
"points" : points
};
$.ajax({
data: parameters,
url: 'workstation/devices.php',
type: 'post',
success: function (response) {
$("#devices").html(response);
}
});
}
function reloadDevices(workstation,randomKey,z,points) {
updateDevices(workstation,randomKey,z, points);
setInterval(function () { updateDevices(workstation,randomKey,z, points); }, 6000);
}
I do an ajax call to devices.php, but when I wanna get my $_POST['points'] variable is empty.
The part of code from my devices.php where I use this variable:
<?php
$areas = json_decode($_POST['points'], true);
?>
<script>
var map = document.getElementById('interactiveWorkstation');
var area = document.getElementById('<?php echo $deviceName; ?>');
if(!area)
map.insertAdjacentHTML('beforeend', '<area id="<?php echo $deviceName; ?>" shape="polygon" coords="<?php echo $areas[$deviceName]; ?>" href=\'javascript:createTerminal(<?php echo "\"".$deviceName."\""; ?>, <?php echo "\"".$deviceIp; ?>-<?php echo $randomKey."\""; ?>, <?php echo "\"".$uid."\""; ?>, <?php echo "\"".$deviceName."\""; ?>);\'/>');
</script>
Honestly, I can't see the error. If someone helps me appreciate it.
Thanks so much.
Regards.

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

AJAX Call - Does not recognize wordpress functions / classes

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

Categories

Resources