First, please look at https://staging.upstatetoday.com/letmein
I have inherited a very old log in mechanism that has begun to not work lately - Firefox refuses to log users in, other browsers can be iffy, too. The site is wordpress, but the login is a different server (paywall).
Correct behavior is: insert username and password, click login button, page refreshes and sends user to the homepage if authentication is valid; alert drops that the username/password is incorrect if invalid.
This only seems to happen corectly in Chrome on the desktop, and sometimes in Edge. Firefox just refreshes the page. There are no js errors.
The login button is supposed to call a JS function that stores the current url (not needed in this implementation) then calls a function (in the wordpress functions.php file) that queries a separate site with the username and password and receives an XML response. That response is evaluated for a Yes and the user is allowed in or not, based on that xml response. If the user is allowed, the JS function returns the user to the page where they last were. If they are not allowed, the JS function alerts with bad user or pass msg.
Anyone can go to any post or page, but the single.php template is modified to check for authentication. If they are authenticated, they see the post. If not, they see a notice to subscribe or log in.
But, There's more going on in the code that is not needed (?) and I think there is unnecessary duplication of the process.
You can see the dialog at the link on top. Please ignore the styling (coming later).
I have moved code, tried snippets, php sessions, but nothing is working in Firefox at all, and with no error messages, I do not know how to proceed.
This is the code for the login dialog:
<?php if(!isset($_SESSION['auth']) ) { ?>
Forgot user name/password? Click Here
<form>
<div class="form-group">
<label for="pwd">User name:</label>
<input type="text" autocomplete="user-name" class="form-control" id="user-name" placeholder="Enter user name" style="width:200px; margin-bottom:5px;"/></div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" autocomplete="current-password" class="form-control" id="pwd" placeholder="Enter password" style="width: 200px;margin-bottom:5px;"/> <button type="submit" class="btn btn-primary" id="sub-sign-in" style="color:blue;font-size:1.0em">Log in to Upstate Today</button> </div>
</form>
<button class="btn btn-default">Register or Renew Subscription </button>
<?php } else { ?>
"<script type="text/javascript">
function Redirect()
{
window.location="https://staging.upstatetoday.com";
}
document.write("You will be redirected to the homepage in 5 seconds");
setTimeout('Redirect()', 5000);
</script>"
<?php } ?>
This is the js that is called by "sub-sign-in" :
jQuery(document).ready(function( $ ){
var pageURL = $(location).attr("href");
localStorage.setItem("page_url", pageURL);
console.log('ready');
$('#sub-sign-in').click(function(){
console.log('enter');
var user_name=$('#user-name').val();
var password=$('#pwd').val();
$.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: ({
action: "check_address",
name: user_name,
pass:password
}),
success: function (response){
console.log(response);
var pg_url = localStorage.getItem("page_url");
if(response == 'Yes0'){
window.location.replace(pg_url);
}
else{
alert('wrong username or password');
}
},
error: function(error){
console.log(error);
}
});
});
});
This is the code from the child theme functions.php
function register_my_session()
{
if( !session_id() )
{
session_start();
}
}
add_action('init', 'register_my_session');
/* session_write_close(); */
function check_address()
{
$name = $_POST["name"];
$password = $_POST["pass"];
/*$edition = $_POST["edition"];
$subdate = $_POST["subscriptiondate"]*/
$response = wp_remote_get( 'https://seneca.newzware.com/authentication/auth70_xml.jsp?site=seneca&login_id='.$name.'&password='.$password);
$xml = simplexml_load_string($response['body']);
$isValid = (string) $xml->authenticated;
if(!session_id()) {
session_start();
}
if($isValid == 'Yes'){
$_SESSION['auth'] = '1';
}
echo $isValid;
}
add_action( 'wp_ajax_check_address', 'check_address' );
add_action( 'wp_ajax_nopriv_check_address', 'check_address' );
add_action( 'wp_enqueue_scripts', 'hello_elementor_child_enqueue_scripts', 20 );
function wpb_widgets_init() {
register_sidebar( array(
'name' => 'Custom Header Widget Area',
'id' => 'newzware-widget',
'before_widget' => '<div class="newzware-widget">',
'after_widget' => '</div>',
'before_title' => '<h2 class="newzware-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'wpb_widgets_init' );
This is the single post content that includes whether the user can read that post or not (ie, is authenticated):
<?php
/**
* The template for displaying singular post-types: posts, pages and user-defined custom post types.
*
* #package HelloElementor
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
?>
<?php
while ( have_posts() ) :
the_post();
?>
<main id="content" <?php post_class( 'site-main' ); ?> role="main">
<?php if ( apply_filters( 'hello_elementor_page_title', true ) ) : ?>
<header class="page-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header>
<?php endif; ?>
<!-- Newzware Protection Code -->
<?php
$key = 'Free Story';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') {
$free_story = 1;
}
?>
<?php if($_SESSION['auth'] == '1' OR current_user_can( 'read_post' ) OR $free_story == '1' ) { ?>
<!-- end part 1Newzware Protection Code -->
<div class="page-content">
<?php the_content(); ?>
<!-- beginpart 2 Newzware Protection Code -->
<?php } else { ?>
<div class='ifsub-panel'> <div class='ifsubpanel-heading' style='background:#2318A4; color:#fff; text-align:center;'><b>Subscribe To The Journal</b></div><div class='ifsubpanel-body'> <p style='text-align:center'>
If you are already registered with UpstateToday.com, please click the LOGIN button in the upper left corner of this window to log in and continue reading.<br><br>
If you'd like to subscribe,<br>
Please click here for options. We'd love for you to join our family.</b></p>
</div></div>
<?php } ?>
<!-- End Newzware Protection Code -->
<div class="post-tags">
<?php the_tags( '<span class="tag-links">' . __( 'Tagged ', 'hello-elementor' ), null, '</span>' ); ?>
</div>
<?php wp_link_pages(); ?>
</div>
<?php comments_template(); ?>
</main>
<?php
endwhile;
I want to make this work reliably in desktop and mobile browsers. I'd love to have a user tap a login button, go to a page with the dialog, log in, then return to the home page.
Thanks for your time and pointers.
Related
I have custom post types with JS filtering (based on category). There are simple html boxes + php code with ACF fields what display after select category.
Problem is it take 1 second or more to load all this html boxes so its not so smooth.
This is my JS (file filters.js):
(function($){
$(document).ready(function(){
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url:wp_ajax.ajax_url,
data: { action: 'filter', category: category },
type: 'post',
success: function(result) {
$('.js-filter').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);
This is html of box what is loaded (file content_pozice_box.php)
<a href="<?php echo get_permalink();?>"><div class="vypis_pozice">
<div class="projekt-wrapper">
<?php
$projekt = get_field('projekt');
if( get_field('projekt') == 'XXX' ) {
?>
<div class="logo-wrapper">
<img src="https://YYY.png" class="logo-wrapper-img">
</div><?php
}
if( get_field('projekt') == 'YYY' ) {
?>
<div class="logo-wrapper">
<img src="https://XXX.png" class="logo-wrapper-img">
</div>
<?php
}
?>
<div class="field_projekt"><h3><?php the_field('projekt');?></h3><div class="field_AAA">AAA:
<?php if ( get_field( 'AAA' ) ): ?>
<?php the_field('AAA');?>
<?php else: // field_name returned false ?>
dohodou
<?php endif; // end of if field_name logic ?>
</div></div>
</div>
<?php the_title('<h3>', '</h3>'); ?>
<div class="location-wrapper">
<div class="BBB"><img src="https://BBB.png"><?php the_field('BBB');?></div>
<div class="CCC"><img src="https://CCC.png"><?php the_field('CCC');?></div>
</div>
<div class="DDD"><?php $cat = get_the_category(); echo $cat[0]->cat_name; ?></div><div class="job-button">Otevřít</div>
</div></a>
PHP (loading JS, Ajax, function)
function load_scripts() {
wp_enqueue_script('ajax', get_stylesheet_directory_uri() . '/' . 'template-parts/' .'filters.js', array('jquery'), NULL, true);
wp_localize_script('ajax' , 'wp_ajax',
array('ajax_url' => admin_url('admin-ajax.php'))
);
}
add_action( 'wp_enqueue_scripts', 'load_scripts');
add_action( 'wp_ajax_nopriv_filter', 'filter_ajax' );
add_action( 'wp_ajax_filter', 'filter_ajax' );
function filter_ajax() {
$category = $_POST['category'];
$args = array(
'post_type' => 'pozice',
'posts_per_page' => -1
);
if(isset($category)) {
$args['category__in'] = array($category);
}
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
include("content_pozice_box.php");
endwhile;
endif;
wp_reset_postdata();
die();
}
This won't solve all your problems but the first thing you should do is reduce your database calls. get_field('projekt') is called 4 times, which runs for every iteration of your loop. Oddly, you've already set it to a variable:
$projekt = get_field('projekt');
But you're not using the variable anywhere. So try replacing that first, so that it only runs once per iteration:
if ( $projekt ) {...}
While you're at it you should always escape output for security's sake. I.E. Instead of <h3><?php the_field('projekt');?></h3> replace with <h3><?php echo esc_html( $projekt ); ?></h3>.
To find other sources of inefficiencies you might try the Query Monitor plugin, as well as your browser's dev tools. I'm not sure about your JS. It looks fine to me but perhaps someone else here will notice something.
I am creating my custom form-edit-account.php template. This contains a form that allows users to change their name, surname, password and other info. Originally the form does not perform ajax requests, you click the save changes button, the data is saved and the page is reloaded. The required fields and their validity are managed by the file https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.218
What I did was create ajax request for the form in order to save the fields without the page refresh. The fields are edited and updated correctly, so it works. However, handling validation not working.
Somehow I need field handling validation but I don't know how to proceed I'm stuck at this point. I have two ideas I could work on:
Try somehow to make the original handling validation work.
Create a custom handling validation with js or php separately from the original file, but I don't know if this is correct.
How could I handle field validation? I hope someone can help me understand how I could do this, I appreciate any help and thank you for any replies.
Example of My-Form
<form name="Form" class="mts-edit-account" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
<!-- Save Settings -->
<p style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</p>
</div>
</form>
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) { //form onsubmit ecent
e.preventDefault(); // the preventDefault function stop default form action
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success: function(data) {
alert('Form Inviato');
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
add_action('woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
// A default response holder, which will have data for sending back to our js file
$response = array(
'error' => false,
);
// Example for creating an response with error information (This not working)
if (trim($_POST['account_first_name']) == '') {
$response['error'] = true;
$response['error_message'] = 'Name is required';
if (trim($_POST['account_first_name']) == '') {
$response['status'] = false;
$response['message'] = 'Name is required';
}else{
$response['status'] = true;
$response['message'] = 'success';
}
// Exit here, for not processing further because of the error
echo json_encode($response);
exit();
}
exit(json_encode($response));
}
Thanks to the intervention of Martin Mirchev in the comments I was able to solve the problem.Here is the solution for anyone who is in the same conditions.
(The form remained the same)
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
//jQuery('.woocommerce-notices-wrapper').append(response);
jQuery('.woocommerce-notices-wrapper').prepend(response);
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$response = wc_print_notices();
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}
I trying to make opening WP posts in popup.
Firts part of code its form in posts loop where I get query of posts what should be opened
<form id="postForm" method="POST">
<input id="postQuery" style="display: none" name="postQuery" value="<?php echo get_the_ID() ?>">
<input id="sendQueryBtn" data-toggle="modal" data-target="#exampleModalLong" type="submit" value="<?php the_title(); ?>">
</form>
Next is my JS, where I do query check by alert
$(document).ready(function () {
$("form").submit(function () {
let xuinya = $(this).serialize();
$.ajax({
type: "POST",
url: '.../footer.php',
data: xuinya,
success: function (data) {
alert(xuinya)
},
error: function (jqXHR, text, error) {
$('#modalBody').html(error);
}
});
return false;
});});
And I final, here is part of HTML with modal, where I try to use POST
<div id="modalBody" class="modal-body">
<?php
echo $_POST["postQuery"];
echo apply_filters( 'the_content', get_post( $_POST["postQuery"] )->post_content );
?>
</div>
My problem is because when I check query in JS - qet alert message with correct value, but in php I always qet simple "1".
I don't get why you posting to footer.php, I think its should be admin-ajax.php
just simply add to youfooter.php
<script>
var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
</script>
Change url value in js to ajax_url, make sure hat with data you posting variable action and then create function in functions.php, something like this(if you sending action value as 'get_pop_posts')
add_action( 'wp_ajax_get_pop_posts', 'get_pop_posts_init' );
add_action( 'wp_ajax_nopriv_get_pop_posts', 'get_pop_posts_init' );
function get_pop_posts_init() {
$data = $_POST;
print_r($data);
die();
}
i'm trying to make a very basic website that includes reCAPTCHA. i've obtained my site key and secret key and followed 2 tutorials so far with no luck
the sites goal is to use a form to obtain a number from the user as input and display a string once the reCAPTCHA is successful and the submit button is pressed
here is my code so far
<!DOCTYPE HTML>
<html> <!-- template-->
<head>
<title>template</title>
<script src="lib/jquery-2.1.4.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form action="/verify.php" method="get">
Number:<br>
<input type="text" name="firstname"><br>
<div class="g-recaptcha" data-sitekey="6LcKeGwUAAAAAOdDqu2CzJxZdgYUXEUEPQKZBOtn"></div>
<input type="submit" value="Submit" />
</form>
</body>
</html>
and here is my php
<html>
<body>
The number is <?php echo $_GET["number"]; ?><br>
<?php
if ($_GET["number"] == 42)
echo "42 is the right answer!";
?>
</body>
</html>
as of now the site works fine... except i don't know how to add the reCAPTCHA code and googles documentation confused me because i know very little about php.
any code samples or links to simple documentation is greatly appreciated. this is my first post on stackoverflow... i hope i followed to rules well enough
this would be your verify.php
$post_data = http_build_query(
array(
'secret' => CAPTCHA_SECRET, //as provided from google
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
if ($result->success) {
//success,
echo $_GET["firstname"]; //your input field name was 'firstname' not 'number'
}else{
echo 'we think you are a bot';
//fail
}
I would suggest changing your HTML code to this:
<form method="post" action="verify.php">
Number:<br>
<input type="text" name="number"><br>
<?php
require_once('recaptchalib.php');
$publickey = "your_public_key"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<input type="submit" />
</form>
<!-- more of your HTML content -->
</body>
and in verify.php add this:
<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
if (isset($_POST['number']) && $_POST['number'] == '42') {
echo "42 is the right answer!";
}
}
?>
I am trying to make an search box which to display the "Address" from MYSQL/PHP
I have used ajax to refresh page without leaving page, but when I run in browser, it always give me an error. when I used console, the return result of echo $_POST['name'] = ( html code of header.php + "What I need" + html code of footer.php )
<?php
include 'header.php';
include 'Connect.php';
if( isset($_POST['ajax']) && isset($_POST['name']) ){
echo $_POST['name'];
exit;
}
?>
<form method="POST">
<label>Username</label>
<input type="text" name="name" required="required" id='name'>
<div id='response'></div>
</form>
<script>
$(document).ready(function(){
$('#name').keyup(function(){
var name = $('#name').val();
$.ajax({
type: 'post',
url: index.php,
data: {ajax: 1,name: name},
success: function(response){
$('#response').text(response);
}
});
});
});
</script>
<?php
if(isset($_POST['name'])){
$username = $_POST['name'];
$stmt = $con->prepare("SELECT Username, FullName, Adresse, Email, Phone FROM dbo.users WHERE Username= ?");
$stmt->execute(array($username));
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$Username = $row["Username"];
$FullName = $row["FullName"];
$Adresse = $row["Adresse"];
$Email = $row["Email"];
$Phone = $row["Phone"];
echo "<tr>
<div>
<td>".$Username."</td>
<td>".$FullName."</td>
<td>".$sEID."</td>
<td>".$Email."</td>
<td>".$Phone."</td>
</div>
</tr>";
}
echo "</table>
</div>";
} else echo '<div class="alert alert-danger"> This Name <strong>is not exit</strong></div>';
include $tpl.'footer.php';
}
?>
Your question isn't very clear... if i understand correctly... this is broken by design, you're calling the page itself and update #name with the content of the entire page, thats why you see html + "what you need" (the response): the response is the whole page.
The right way to do this would be to move the second part of PHP code (where you perform the query ecc.) on a separate script and then call that new script by putting its name as the url parameter in the ajax call.
thank you for your respanse, i want to use the value returned by ajax to use with MYSQL/PHP to echo $row['Address'];
if i move the second part of PHP code the result is
echo $_POST['name'] = ( "What I need" + html code of footer.php )