I had to redirect the visitor to another page if something went wrong. Header location couldn't work because there is already some things displayed so I only have the choice to use javascript. Here is a piece of my PHP code :
add_action('frm_field_input_html', 'getDoctypes');
function getDoctypes($field, $echo = true){
$url = 'http://ff/interface/iface.php';
$html = '';
if ($field['id'] == get_id_from_key_frm('doctype')){
$data = array('action' => 'getDoctypes');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'timeout' => 30,
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$return = file_get_contents($url, false, $context);
$doctypes = json_decode($return);
if ($return === FALSE || isset($doctypes -> code)){
$wpBaseUrl = site_url();
echo "<script>window.location = '$wpBaseUrl/error-connection-interface/' </script>";
}else{
$html = ">";
foreach ($doctypes as $code => $name){
$html .= "<option value=\"$code\">$name</option>";
}
}
}
if ($echo)
echo $html;
return $html;
}
The problem is when $return === FALSE, instead of executing the script, it just display "window.location = 'http://my_ip/error-connection-interface/'" into the HTML
Any ideas ?
Thanks in advance
Related
Hellow.
I'm not only a php beginner and but a wordpress beginner.
I try to integrate 3rd-party PHP file and Javascript (For Age Verification using Phone. i.e: SMS Certification) into my wordpress site.
this 3rd-party reference
Using 'add_shortcode', i managed to add 'request function' to my wordpress site. (Reference Url's STEP 1)
if (! function_exists ( 'register_mycustom_agecert_page' ) ) {
function register_mycustom_agecert_page () {
$mid ='**********'; // Given MID(Merchant ID)
$apiKey ='********************************'; // apikey to MID
$mTxId ='***********';
$reqSvcCd ='01';
// Check if registered merchant or not.
$plainText1 = hash("sha256",(string)$mid.(string)$mTxId.(string)$apiKey);
$authHash = $plainText1;
$userName = 'Anonymous'; // User name
$userPhone = '01011112222'; // user Phone
$userBirth ='19830000'; // user Birth
$flgFixedUser = 'N'; // When fixing specific user, use below 'Y' setting.
if($flgFixedUser=="Y")
{
$plainText2 = hash("sha256",(string)$userName.(string)$mid.(string)$userPhone.(string)$mTxId.(string)$userBirth.(string)$reqSvcCd);
$userHash = $plainText2;
}
$foo = '';
$foo .= '<div align="center" class="age-gate-wrapper">';
$foo .= '<form name="saForm">';
$foo .= '<input type="hidden" name="mid" value="' . $mid . '">';
$foo .= '<input type="hidden" name="reqSvcCd" value="' . $reqSvcCd . '">';
$foo .= '<input type="hidden" name="mTxId" value="' . $mTxId . '">';
$foo .= '<input type="hidden" name="authHash" value="' . $authHash .'">';
$foo .= '<input type="hidden" name="flgFixedUser" value="' . $flgFixedUser . '">';
$foo .= 'input type="hidden" id="userName" name="userName"';
$foo .= '<input type="hidden" id="userPhone" name="userPhone">';
$foo .= '<input type="hidden" id="userBirth" name="userBirth">';
$foo .= '<input type="hidden" name="userHash" value="' . $userHash . '">';
$foo .= '<input type="hidden" name="directAgency" value="">';
$foo .= '<input type="hidden" name="successUrl" value="' . esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '<input type="hidden" name="failUrl" value="'. esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '</form>';
$foo .= '<button onclick="callSa()">Proceed to "Age Verification"</button>';
$foo .= '</div>';
echo $foo;
}
add_shortcode( 'register_mycustom_agecert_page', 'register_mycustom_agecert_page');
}
callSa() script.
function callSa()
{
let window = popupCenter();
if(window != undefined && window != null)
{
document.saForm.setAttribute("target", "sa_popup");
document.saForm.setAttribute("post", "post");
document.saForm.setAttribute("action", "https://sa.inicis.com/auth");
document.saForm.submit();
}
}
function popupCenter() {
let _width = 400;
let _height = 620;
var xPos = (document.body.offsetWidth/2) - (_width/2); // Align center
xPos += window.screenLeft; // For dual monitor
return window.open("", "sa_popup", "width="+_width+", height="+_height+", left="+xPos+", menubar=yes, status=yes, titlebar=yes, resizable=yes");
}
And then, i put success.php file in "childtheme-folder/kg/".
(Reference's Step 2, 3)
success.php file.
<?php
// -------------------- recieving --------------------------------------
extract($_POST);
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
echo 'authRequestUrl : '.$_REQUEST["authRequestUrl"]."<br/>";
echo 'txId : '.$_REQUEST["txId"]."<br/><br/><br/>";
$mid ='********'; // Test MID. You need to replace Test MID with Merchant MID.
if ($_REQUEST["resultCode"] === "0000") {
$data = array(
'mid' => $mid,
'txId' => $txId
);
$post_data = json_encode($data);
// Start 'curl'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_REQUEST["authRequestUrl"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
// -------------------- Recieve result -------------------------------------------
echo $response;
// Check If user age is under 20 years old or not.
$pre_age_cert_result = json_decode( $response, true );
if ( isset ($pre_age_cert_result) && ! empty ( $pre_age_cert_result['userBirthday'] ) ) {
$pre_user_input_date = date ( 'Ymd', strtotime ($pre_age_cert_result['userBirthday']) );
$user_input_date = new DateTime( $pre_user_input_date );
$current_date = new DateTime();
$user_input_date->add( new DateInterval( 'P20Y' ) );
if ( $current_date > $user_input_date ) {
$age_cert_check = true;
$age_checking_msg = 'Age Verification: Success';
} else {
$age_cert_check = false;
$age_checking_msg = 'Age Verification: Failed';
}
} else {
$age_cert_check = false;
$age_checking_msg = 'Some Problem.';
}
echo $age_checking_msg;
// Add result of age cert into usermeta.
if ( $age_cert_check === true ) {
echo 'Success - Process 01';
echo '<br>';
if ( is_user_logged_in() ) {
echo 'Success - Process 02';
echo '<br>';
$temp_current_user_id = get_current_user_id();
echo $temp_current_user_id;
if ( $temp_current_user_id !== 0 && $temp_current_user_id !== NULL ) {
echo 'Success - Process 03';
echo '<br>';
$result_cur_time = date( 'Ymd', strtotime("now") );
echo $result_cur_time;
update_user_meta( $temp_current_user_id, 'ageCert', true );
update_user_meta( $temp_current_user_id, 'ageCertDate', $result_cur_time );
} else {
echo 'Failure - Process 03';
echo '<br>';
return;
}
} else {
echo 'Failure - Process 02';
echo '<br>';
$button_link_03 = esc_url( wp_login_url() );
$button_text_03 = esc_html( __( 'You Need to Login.', 'woocommerce' ) );
echo ''.$button_text_03.'';
return;
}
} else {
echo 'Failure - Process 01';
echo '<br>';
return;
}
}else { // if resultCode===0000 is not, display below code.
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
}
?>
Finally i could get "echo 'Success - Process 01". But i can't display neither 'success -Process 02' nor 'Failure -Process 02'.
I think the cause of this is that success.php is not wordpress page. So success.php doesn't have access to wordpress function.
How can i achive my goal?
If it's not possible to fetch usermeta in custom page (like success.php), below can be option ?
Using wordpress Rest-API, send value of $user_input_date. And hook somewhere, like wp_remote_get() ?
Using alternative function which can get usermeta from wordpress.
Grating access to wordpress to success.php page
I would appreciate any reference page or example Code.
Thank you for reading this long article.
Finally i achive my goal - thanks to IT goldman and Json.
i added below 2 lines into success.php
$custom_path = '/wp-load.php file path';
require_once( $custom_path . '/wp-load.php' );
It works !
You can just include "wp-config.php"; as the first line of your php script then you get all wordpress functions, including get_user_meta.
you use use wp_load.php on success.php file
if your folder structure is like this (/wp-content/themes/child-theme/kg/success.php)
in the success.php file add this line
<?php
include_once("../../../../wp-load.php");
echo "test:: " . get_site_url();
wp-load.php which loads all the functions and code for wordpress(bootstraps).
I'am trying to display same data using datatables server side processing at Codeigniter.I should use 'where' clause and i'am using Emran ul hadi script class.(Visit https://emranulhadi.wordpress.com/2014/06/05/join-and-extra-condition-support-at-datatables-library-ssp-class/#comment-196).
My controller script :
$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'kreatx',
'host' => 'localhost'
);
$index = $this->uri->segment(3);
$table = 'user';
$columns = array(
array('db' => 'Name', 'dt' => 0),
array('db' => 'Lastname', 'dt' => 1),
array('db' => 'Email', 'dt' => 2),
array('db' => 'Username', 'dt' => 3),
array('db' => 'Password', 'dt' => 4)
);
$primaryKey = 'ID';
$this->load->model('employees_model');
$department = $this->employees_model->get_department($index);
require( 'SSP.php' );
$where = 'Department = '.$index.'';
echo json_encode(
SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns,
null ,$where )
);
My view script :
$('#employees').DataTable({
"responsive":true,
"processing":true,
"serverSide":true,
"searching":true,
"ordering":true,
"order":[],
"ajax":{
url:"<?php echo base_url() .
'employees/get_employees/'.$index.''; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[4],
"orderable":false,
},
],
});
Table is displaying correctly,with no errors.But search and order does'nt work.
If i try to search it just say prrocessing and show the same table.
Same problem with ordering.
Any sugesstion please ?
Thanks !
On your script you set "serverside" parameter to "true"
That means all the filtering and sorting needs to be in your php script. Every time you change the order or try to apply a filter, the dataTables javascript will send an ajax call to the php page you have listed under the ajax parameter. The ajax call will include everything you need inside of get or post variables that you can parse.
You need to write the code in php to parse the URL parameters and dynamically create a sql query that filters your database results.
I haven't done this in Codeignitor before but this is a quick example of what I would try in Laravel (note, you need to hard code your own database columns or if you're advanced then you can loop the code into an array of your database column names)
public function MyExampleJson(Request $request)
{
$len = $_GET['length'];
$start = $_GET['start'];
$select = "SELECT *,1,2 ";
$presql = " FROM entities a ";
$whereused = false;
if($_GET['search']['value']) {
$presql .= " WHERE (id LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column01 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column02 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column03 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column04 LIKE '%". $_GET['search']['value']."%' ";
$presql .= ") ";
$whereused = true;
}
$orderby = "";
$columns = array('column01','column02','column03','column04');
$order = $columns[$request->input('order.0.column')];
$dir = $request->input('order.0.dir');
$columnsearcharray = $request->columns;
foreach ($columnsearcharray as $key => $value)
{
if ($value['search']['value']) {
if ($whereused) {
$presql .= " AND ";
} else {
$presql .= " WHERE ";
$whereused = true;
}
$presql .= $columns[$key] . " LIKE '%" . $value['search']['value'] . "%' ";
}
}
$orderby = "Order By " . $order . " " . $dir;
$sql = $select.$presql.$orderby." LIMIT ".$start.",".$len;
$qcount = DB::select("SELECT COUNT(a.id) c".$presql);
$count = $qcount[0]->c;
$results = DB::select($sql);
$ret = [];
foreach ($results as $row) {
$r = [];
foreach ($row as $value) {
$r[] = $value;
}
$ret[] = $r;
}
$ret['data'] = $ret;
$ret['recordsTotal'] = $count;
$ret['iTotalDisplayRecords'] = $count;
$ret['recordsFiltered'] = count($ret);
$ret['draw'] = $_GET['draw'];
echo json_encode($ret);
}
i need help with decode json
if($loop->have_posts()) :
$json = '{';
$json .= '
"api_status":1,
"api_message":"success",
"data": [';
while ( $loop->have_posts() ) : $loop->the_post();
$json .= '{
"id":'.get_the_ID().',
"post_name":"'.get_the_title().'"
},
';
endwhile;
$json = substr($json,0,-1);
$json .= ']}';
echo $json;
endif;
break;
}
my error is
in the last } i have still , so i need to remove it.
but i dont know how ?
someone help me ?
As mentioned in the comments, json_encode is the way to go.
$toEncode = array(
"api_status" => 1,
"api_message" => "success",
"data" => array()
);
while ($loop->have_posts()) {
$loop->the_post();
array_push($toEncode["data"], array(
"id" => get_the_ID(),
"post_name" => get_the_title()
));
}
echo json_encode($toEncode);
However, I do not quite understand how your system for posts work. Are you using some type of iterator?
You can use php function json_decode / encode:
JSON_DECODE
JSON_ENCODE
f.ex.
json_decode($variable, true);
json_encode($variable, true);
use rtrim($json, ","); to remove last comma from json output
if($loop->have_posts()) :
$json = '{';
$json .= '
"api_status":1,
"api_message":"success",
"data": [';
while ( $loop->have_posts() ) : $loop->the_post();
$json .= '{
"id":'.get_the_ID().',
"post_name":"'.get_the_title().'"
},';
endwhile;
$json = rtrim($json, ",");
$json .= ']}';
echo $json;
endif;
break;
}
another way
$json = new array();
if($loop->have_posts()) :
$json["api_status"] = 1,
$json["api_message"] = "success",
$json["data"] = new array();
while ( $loop->have_posts() ) : $loop->the_post();
$json["data"]["id"] = get_the_ID();
$json["data"]["post_name"] = get_the_title();
endwhile;
echo json_encode($json);
endif;
break;
}
I'm really struggling to find a way to create pagination with ajax for my Wordpress posts. The solutions that I have found do not work.
To be more informative about this here is a link that has bullets at the bottom for pagination. Once these are clicked I want the effect of the site to load the new posts without triggering a page refresh.
http://maxlynn.co.uk/natural-interaction/category/all/
My question is, is there any good tutorials out there that you may have had success with for this type of effect.
Let me know if you need more information.
****** UPDATE ******
function kriesi_pagination($pages = '', $range = 2) {
$showitems = ($range * 2)+1;
global $paged;
if (empty($paged)) $paged = 1;
if ($pages == '') {
global $wp_query;
$pages = $wp_query->max_num_pages;
if (!$pages) {
$pages = 1;
}
}
if (1 != $pages) {
echo "<div class='pagination'><div class='pagination-container'>";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>«</a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";
for ($i=1; $i <= $pages; $i++) {
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
}
}
if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>»</a>";
echo "</div>\n</div>\n";
}
}
This is my PHP that I'm using, how would I use this php to create an ajax request so that the page doesn't reload?
What you need to do is to prevent default on the pagination links, and send an AJAX request to get the posts. Wordpress works in this way for AJAX: you send all your requests to wp-admin/admin-ajax.php with an action parameter that will identify the request in order to catch it in functions.php using wp_ajax_nopriv_my_action and wp_ajax_my_action hooks.
So basically you will do this in your template file:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.pagination a').click(function(e) {
e.preventDefault(); // don't trigger page reload
if($(this).hasClass('active')) {
return; // don't do anything if click on current page
}
$.post(
'<?php echo admin_url('admin-ajax.php'); ?>', // get admin-ajax.php url
{
action: 'ajax_pagination',
page: parseInt($(this).attr('data-page')), // get page number for "data-page" attribute
posts_per_page: <?php echo get_option('posts_per_page'); ?>
},
function(data) {
$('#content-posts').html(data); // replace posts with new one
}
});
});
});
</script>
You'll have to change classes names / attributes etc depending of your template.
And on the functions.php side:
function my_ajax_navigation() {
$requested_page = intval($_POST['page']);
$posts_per_page = intval($_POST['posts_per_page']) - 1;
$posts = get_posts(array(
'posts_per_page' => $posts_per_page,
'offset' => $page * $posts_per_page
));
foreach ($posts as $post) {
setup_postdata( $post );
// DISPLAY POST HERE
// good thing to do would be to include your post template
}
exit;
}
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );
The thing is to query the posts of the page requested (so we calculate the offset from the page number and the posts per page option), and display them with the template you use for single posts.
You may want to manipulate the browser history too, for that you should check on the History API.
filter.js file
$('#post-category').change(function(){
category = $(this).find('.selected').text();
postType = $('#search-form-type').val();
post_filter();
});
function post_filter(paged){
$.ajax(
{
url:ajaxUrl,
type:"POST",
data: {action:"get_post_category","category":category,'search':search, 'postType':postType, 'paged': paged},
success: function(response) {
$('#blog-post-cover').html(response);
}
});
}
$('#blog-wrapper').on('click','#pagination a',function(e){
e.preventDefault();
if ($(this).hasClass('prev')||$(this).hasClass('next')) {
paginateNum = $(this).find('.prev-next').data('attr');
post_filter(paginateNum);
}
else{
paginateNum = $(this).text();
post_filter(paginateNum);
}
$("html, body").animate({ scrollTop: 0 }, "slow");
});
postType = $('#search-form-type').val();
post_filter(1);
function.php file
add_action( 'wp_ajax_nopriv_get_post_category', 'post_category' );
add_action( 'wp_ajax_get_post_category', 'post_category' );
function post_category() {
$post_type = $_POST['postType'];
$category = $_POST['category'];
$search = $_POST['search'];
$paged = ($_POST['paged'])? $_POST['paged'] : 1;
if($post_type==="resource-center"):
$taxonomy ="resource-center-taxonomy";
else:
$taxonomy ="category";
endif;
if($category):
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $category,
),
),
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
else:
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
endif;
$posts = new WP_Query($args);?>
<?php if ( $posts->have_posts() ) :?>
<?php while ($posts->have_posts()) : $posts->the_post(); ?>
<?php echo $post->post_title; ?>
<?php endwhile;?>
<?php
$nextpage = $paged+1;
$prevouspage = $paged-1;
$total = $posts->max_num_pages;
$pagination_args = array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => $total,
'current' => $paged,
'show_all' => false,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('<span class="prev-next" data-attr="'.$prevouspage.'">«</span>'),
'next_text' => __('<span class="prev-next" data-attr="'.$nextpage.'">»</span>'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<div id='pagination' class='pagination'>";
echo $paginate_links;
echo "</div>";
}?>
<?php wp_reset_query(); ?>
<?php else:?>
<div class="no-post-cover">
<div class="container">
<h1 class="has-no-post-list">Posts Not Found</h1>
</div>
</div>
<?php endif;?>
<?php die(1);
}
I am using the below php code to export from my mysql database:
<?php
require_once('connect.php');
$group = 1;//$_GET['group'];
$export = mysql_query ("SELECT * FROM relationship WHERE group_id = $group");
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
mysql_close($my_connection);
?>
I can download the file from my browser (chrome) if I simply run this php file.
However, the download does not show if I use a click button on another page and call below javascript to run this php file:
<script>
function export_data()
{alert(1);
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "export.php",
data: {group: localStorage.group_id},
dataType: "html",
success: function(response){
alert(response);
}
});alert(2);
}
</script>
Javascript will alert all the xls contents, but block the download.
How can I solve this?
Thanks in advance!
Why don't you just use window.location instead of AJAX ?
<script>
function export_data()
{
window.location='export.php';
}
</script>
You can remove JavaScript click even and direct create a link
Download
This will download file without referencing page on browser.