Trouble finding the actual log-in action Yii - javascript

I was thrown some code and I'm trying to edit the log-in functionality but I'm having trouble locating where the actual login is going. The login url at the address bar states that it's in site/index.php but when I check that page, the codes there are completely irrelevant so I found the "login.php" page that points towards the _login.php as a view.
Here is the code for login.php:
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'secret',
'secret' => 'secret',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<?php
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<div style="float:left;"><?php echo $msg ?></div>
<div style="clear:both;"></div>
<div id="form_login" class="form">
<h1>Login</h1>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<div class="row">
<?php //echo $form->labelEx($model,'username'); ?>
<?php //echo $form->textField($model,'username'); ?>
<?php //echo $form->error($model,'username'); ?>
<?php echo $form->labelEx($model,'first_name'); ?>
<?php echo $form->textField($model,'first_name'); ?>
<?php echo $form->error($model,'first_name'); ?>
<?php echo $form->labelEx($model,'last_name'); ?>
<?php echo $form->textField($model,'last_name'); ?>
<?php echo $form->error($model,'last_name'); ?>
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
<?php echo $form->error($model,'rememberMe'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login',array('id'=>'submit_button'));
?>
<a href="<?php echo Yii::app()->getBaseUrl(); ?>/index.php/persons/create">
<?php echo CHtml::button('Sign Up',array('id'=>'submit_button')); ?>
</a>
</div>
<?php $this->endWidget(); ?>
</div>
<!-- form -->
Then I went on to check the _login.php and this is what I found and I think this is where the actual login happens:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'login-form'.$box,
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<?php
if($model->hasErrors()){
//$nameErrMsg = $model->getError('first_name').'\n';
$nameErrMsg = $model->getError('email').'\n';
$unameErrMsg = $model->getError('username').'\n';
$passErrMsg = $model->getError('password');
//$err = $nameErrMsg.$unameErrMsg.$passErrMsg;
$err = $nameErrMsg.$passErrMsg;
?>
<script>alert("<?=$err?>");</script>
<?php } ?>
<?php //echo $form->textField($model,'first_name',
//array('id'=>'fname'.$box, 'class'=>'login_typebox','placeholder'=>'FIRST NAME','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'first_name')))))); ?>
<?php echo $form->textField($model,'email',
array('id'=>'email'.$box, 'class'=>'login_typebox','placeholder'=>'EMAIL','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'email')))))); ?>
<?php //echo $form->textField($model,'last_name',
//array('id'=>'lname'.$box, 'class'=>'login_typebox','placeholder'=>'LAST NAME','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'last_name')))))); ?>
<?php echo $form->passwordField($model,'password',
array('id'=>'pword'.$box, 'class'=>'login_typebox','placeholder'=>'PASSWORD','title'=>ucfirst(strtolower(strip_tags($form->error($model, 'password')))))); ?>
<input type="hidden" name="box" value="<?php echo $box ?>">
<input type="submit" class="login_submitbtn" style="font-family: 'AsapRegular', Helvetica, sans-serif;color: #FFF;font-size: 14px;padding: 5px 0;border-radius: 5px;border: 1px solid #d0e7ef;background-color: #67b3cf;" name="LOG IN" value="LOG IN"/>
<?php $this->endWidget(); ?>
<div class="login_note_box">
<p><a target="_blank" href="<?php echo Yii::app()->createUrl('register')?>">Not yet a member?</a></p>
<p><a target="_blank" href="<?php echo Yii::app()->createUrl('user/forgot')?>">Forgot password?</a></p>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('input').placeholder();
$('#login-form<?php echo $box?> input.login_typebox').each(function(i,e){
$(this).keydown(function(){
$(this).removeClass('error').attr('title', '');
});
});
$('#login-form<?php echo $box?>').submit(function(){
var email = $("#email<?php echo $box?>").val();
// var fname = $("#fname<?php echo $box?>").val();
// var lname = $("#lname<?php echo $box?>").val();
var pword = $("#pword<?php echo $box?>").val();
//if(fname == '' && lname == "" && pword == "") {
if(email == "" && pword == "") {
alert('Please input your Email and Password');
//alert('Please input your First Name, Last Name, and Password');
$('#login-form<?php echo $box?> input.login_typebox').each(function(i,e){
//$(this).keydown(function(){
//$(this).addClass('error').attr('title', 'Please input your First Name, Last Name, and Password');
$(this).addClass('error').attr('title', 'Please input your Email and Password');
//})
});
return false;
}
var $data = $(this).serialize();
$.ajax({
url : $(this).attr('action'),
data : $data,
type : 'POST',
beforeSend : function(){
$("#login-form<?php echo $box?> .login_submitbtn").addClass("loading");
},
success : function($return){
try{
$arr = $.parseJSON($return);
if($arr.status == 'success'){
location = $arr.url;
}
}catch(e){
$('.loginform').html($return);
}
},
complete : function(){
//$(".login_submitbtn").removeClass("loading");
}
});
return false;
});
$('#login-form<?php echo $box?> input.error').each(function(i,e){
$(this).keydown(function(){
$(this).removeClass('error').attr('title','');
})
});
});

LoginForm.php in the models folder is used along with UserIdentity.php which is in the components folder are the basis of the login process. That is the basis of a Yii login, how a facebook specific login works in conjunction with these is a different matter.

Related

Ajax call within WordPress returning entire HTML page in response

The most frustrating thing is that this code was working then suddenly it startet returning an entire page of HTML rather than just the HTML code from the template below.
I'm calling an ajax function and passing it an object that looks like this (result of console.log(data)):
Here is my ajax function:
function mapResults (data) {
//console.log(data);
$.ajax({
type: 'post',
url: wp_ajax.wp_url,
data: {action: 'marker_in_viewport', resultsArray: data},
success: function(result) {
$('#map-results').html(result);
},
error: function(result) {
console.warn(result);
}
});
}
Here is the PHP code that handles the request:
<?php
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
function marker_in_viewport() {
$locationResults = $_POST['resultsArray'];
$posts = get_posts(array(
'post_type' => 'accommodation',
'post__in' => $locationResults,
));
?>
<?php
//require result template
//require_once ('map-results.php');
if( $posts ) { ?>
<?php foreach( $posts as $post ) {
$id = $post->ID;
$title = get_the_title($id);
$location = get_field('location', $id);
$permalink = get_permalink( $id );
$rooms_available_from = get_field('rooms_available_from', $id);
$gallery = get_field('gallery', $id);
?>
<div class="col-md-4 accom-results-cont pb-3">
<?php if ($gallery) : ?>
<a href="<?= $permalink; ?>" title="Learn more about <?= $title; ?>">
<div class="accom-results-img-cont">
<img class="img-fluid" src="<?= $gallery['url']; ?>" alt="An image of <?= $title; ?>" >
</div>
<?php endif; ?>
<div class="accom-results-data-cont pr-3 pt-3">
<?php if ( $title ) : ?>
<p class="results-title"><b><?= $title ?></b></p>
<?php endif; ?>
</div>
</a>
</div>
<?php } ?>
<?php } ?>
<?php wp_die(); ?>
<?php } ?>
And in my page template I have the following div where I want the results to be populated:
<div id="map-results"class="row py-5"></div>
Any ideas what I have done wrong?
I revised your code. try the below code.
function mapResults (data) {
$.ajax({
type: 'post',
dataType : "json",
url: wp_ajax.wp_url,
data: {action: 'marker_in_viewport', resultsArray: data},
success: function(result) {
$('#map-results').html(result.data.html);
},error: function(result) {
console.warn(result);
}
});
}
You can use ob_start() and ob_get_clean().
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
function marker_in_viewport() {
$locationResults = $_POST['resultsArray'];
$posts = get_posts(array(
'post_type' => 'accommodation',
'post__in' => $locationResults
));
ob_start();
if( $posts ) { foreach( $posts as $post ) {
$id = $post->ID;
$title = get_the_title($id);
$location = get_field('location', $id);
$permalink = get_permalink( $id );
$gallery = get_field('gallery', $id);
$rooms_available_from = get_field('rooms_available_from', $id);
?>
<div class="col-md-4 accom-results-cont pb-3">
<a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
<?php if ( $gallery ) : ?>
<div class="accom-results-img-cont">
<img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
</div>
<?php endif; ?>
<div class="accom-results-data-cont pr-3 pt-3">
<?php if ( $title ) : ?>
<p class="results-title"><b><?php echo $title; ?></b></p>
<?php endif; ?>
</div>
</a>
</div>
<?php } }
$html = ob_get_clean();
wp_send_json_success(array(
'html' => $html
));
}
USEFUL LINKS
ob_start()
ob_get_clean()
wp_send_json_success()
Finally got this working after about a week of trying!!
Here is my AJAX Function inside js/script.js
$.ajax({
type: 'post',
//dataType: 'json',
url: map_ajax_obj.ajaxurl,
data: {action: 'marker_in_viewport', resultsArray: data, nonce: map_ajax_obj.nonce},
success: function(result) {
//console.log(result);
$('#map-results').html(result);
},
error: function(result) {
console.warn(result);
}
});
Inside my functions.php file I have enqueued and localised my wp-admin.php like this
function load_req_scripts()
{
wp_register_script( 'custom-js-script', get_template_directory_uri() . '/js/script.js', array( 'jquery'), '', true);
wp_enqueue_script( 'custom-js-script' );
wp_localize_script(
'custom-js-script', //I think this is a dependancy on the above script though not entirely sure
'map_ajax_obj',
array (
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax_nonce')
)
);
}
add_action( 'wp_enqueue_scripts', 'load_req_scripts' );
require_once('ajax/accommodation-ajax.php'); //where to handle and return the data to the ajax call
here is the function in my accommodation-ajax.php file
<?php
function marker_in_viewport() {
$locationResults = $_POST['resultsArray'];
if (!empty($locationResults)) {
$posts = get_posts(array(
'post_type' => 'accommodation',
'post__in' => $locationResults
));
if( $posts ) {
foreach( $posts as $post ) {
$id = $post->ID;
$title = get_the_title($id);
$location = get_field('location', $id);
$permalink = get_permalink( $id );
$gallery = get_field('gallery', $id);
$rooms_available_from = get_field('rooms_available_from', $id);
?>
<div class="col-md-4 accom-results-cont pb-3">
<a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
<?php if ( $gallery ) : ?>
<div class="accom-results-img-cont">
<img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
</div>
<?php endif; ?>
<div class="accom-results-data-cont pr-3 pt-3">
<?php if ( $title ) : ?>
<p class="results-title"><b><?php echo $title; ?></b></p>
<?php endif; ?>
</div>
</a>
</div>
<?php } //end for each
} //end if posts
} //end if not empty
else {
echo "No results found please search again!";
}
wp_die();
}
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
As to why this now works compared to what I posted above I have no idea!! Could it be the NONCE? though I'm not using it to authenticate in the PHP function. Anyway hope this helps someone or my future self next time I'm banging my head against the wall with wordpress ajax calls.
UPDATE So this stopped working for me again then I realised that it was working when logged in as admin and not workign for logged out and all other users. Because this is a membership site I wanted to block anyone that wasn't an admin form the admin area. Didn't realise that this function was also blocking access to the admin-ajax.php file too. This was redirecting to the Homepage hence why the AJAX call was returning the entire page HTML.
SO I needed to update my function to include:
&& ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX )
to the following:
//block users from admin if not admin
function blockusers_wps_init() {
if ( is_admin() && ! current_user_can( 'administrator' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}
add_action( 'init', 'blockusers_wps_init' );
Don’t use wp_die() it’s returning html, use just die()

AJAX Post request working only on Web Console (Preview)

I have a really simple ajax request to "send" the ID of an element the user clicks on the webSite. The script is working only on the Web Console (in the Network -> Preview section). This happens in every browser.
here's the code:
AJAX REQUEST
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {
var itemid = event.target.id;
$.ajax({
type: 'post',
//url: "index.php",
data: {'itemid' : itemid},
cache : false,
async : true,
dataType: 'html',
success: function(data) {
alert('success');
},
failure: function(data) {
alert('failure');
}
});
});
</script>
PHP Function
<?php
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo "success";
$itemid = (int)$itemid;
echo $itemid;
} else{
echo "failure";}
?>
Can you help me with this?
Just adding the image to let you understand better.
UPDATED: Here's the full code, hope it's not too confusionary (still a beginner):
I'm getting the response correct but echo json_encode($d); is not printing.
Btw thank you very much for your support :)
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include '../includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n";
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "</script>";
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo "<script type='text/javascript'>\r\n";
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>
Here is what can work for you. If it does not work then please share your entire code and the response from PHP too.
// jQuery AJAX call should be something like this
$.ajax({
url: 'index.php',
data: {
"itemid": itemid
},
type: "post",
dataType: "json",
success: function(json) {
if(json.success) {
alert("Item ID is " + json.itemid);
} else {
alert("Item ID is " + json.itemid);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error :: " + textStatus + " :: " + errorThrown);
}
});
// PHP code can be like this
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo json_encode(['success' => true, 'itemid' => $itemid]);
} else {
echo json_encode(['success' => false, 'itemid' => 'Not available']);
}
Consider the following.
JavaScript
$("[class*='point']").click(function(e) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
PHP
<?php
$d = array();
if(isset($_POST['itemid'])){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
?>
In a lot of cases, it's better to pass JSON data back. It's easier for JavaScript to handle it. So we build an array of data that we want to pass back to AJAX request and encode it as JSON.
When we make the AJAX Post, PHP will result in a Successful response. You're welcome to catch an error, this would happen with 400 or 500 Status result from the PHP call. You can also see this in your Web Console.
We're going to get a JSON Object back from PHP, either:
{
result: "success",
itemid: 2
}
Or:
{
result: "error",
error: "'itemid' was not set."
}
In JavaScript, we can use dot notation to access the elements of the object. You can also access it like this:
if(data['result'] == "success")
Dot notation is advised.
Update 1
In your PHP File, you will want a different structure. You're going to have to perform some actions before the HTML is presented to the Browser.
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$itemid = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
$d;
// Connect to SQL
// Query DB for Table Data ...WHERE itemId = '$itemid'
// Store resultset to $d
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once "../grid.asp";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include 'includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n"
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>
Hope this helps.

How to include php function in javascript(Alertify.js) that had been echo in php

I am using alertify.js library to prompt a cormfirmation to user. Ex if user press ok , it will run certain php funtion. The alert are echo using php. but it return an error.
<?php
include('header.php');
if( isset($_GET['id']) && $_GET['action'] == 'delete'){
$id = $_GET['id'];
echo '<script type="text/javascript">
alertify.confirm("Confirm Title", "Confirm Message", function(){ alertify.success("Ok")'.
if($user->deleteAccount($id)){
$_SESSION['current_url'] = $_SERVER['PHP_SELF'];
/* echo "<script type='text/javascript'>
window.location.replace('clear_Post.php');
</script>";*/
}
.' }
, function(){ alertify.error("Cancel")});
</script>';
}
?>

How to display username on home page only after login?

//header.php
<?php
session_start();
if(isset($_SESSION['loggedin']))
$_SESSION['displayname']="notset";
else
$_SESSION['loggedin']=0;
?>
//index.php
<?php
require "header.php";
if($_SESSION['loggedin']==1) //ignores the if statement
{
echo "Welcome".$_SESSION['displayname']."!";
echo "<button id='logout_button'>
<a href='logout.php'>Logout</a>
}
else
{
echo '<a id="display_name" href="login.html">Login/ Signup</a>';
}
?>
//verify.php
<?php
session_start();
include "connect.php";
$uname=$_POST['uname'];
$pass=$_POST['pass'];
$check=mysqli_query($conn,"SELECT * FROM member_list WHERE username='$uname'");
$numrows=mysqli_num_rows($check);
if ($numrows == 1)
{
$row = mysqli_fetch_array($check);
$dbusername = $row['username'];
$dbpassword = $row['password'];
if( $uname == $dbusername && $pass == $dbpassword )
{
$_SESSION['loggedin']=1;
$_SESSION['displayname'] = $uname;
header("location:index.php");
}
else
{
$msg="Invalid Password !!";
echo "<script type='text/javascript'>alert('$msg');
window.location.replace('loggedin.html')</script>";
}
}
else
{
$msg="Invalid Username !!";
echo "<script type='text/javascript'>alert('$msg');
window.location.replace('index.html')</script>";
}
?>
This is my code. There is no error. But when I login it does not display the username. It ignores the if statement on index.php and goes straight to the else statement.
try this to debug your apps
index.php
<?php
//start header.php
ob_start();
session_start();
$_SESSION['loggedin'] = (isset($_SESSION['loggedin'])) ? $_SESSION['loggedin'] : 0;
if($_SESSION['loggedin']==1)
$_SESSION['displayname']="admin";
else
$_SESSION['displayname']="guest";
//end header.php
if($_SESSION['loggedin']==1)
{
echo $_SESSION['displayname'];
echo "<a href='logout.php'>Logout</a>";
}
else
{
echo $_SESSION['displayname'];
echo "<a href='login.php'>Login</a>";
}
?>
login.php
<?php
ob_start();
session_start();
$_SESSION['loggedin']=1;
echo "try login....";
sleep(1);
header( 'Location: index.php' ) ;
?>
logout.php
<?php
ob_start();
session_start();
$_SESSION=NULL;
session_destroy();
echo "try logout....";
sleep(1);
header( 'Location: index.php' ) ;
?>
let me know this script work or not

Posting variables with AJAX to a php function on a different file and calling the function

I am attempting to post variables via AJAX and using these variables to run a script that creates a list of checkbox options. My code is as follows:
*index.php*
require_once ("session_start.php");
require_once ("ajax.php");
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$link = mysqli_connect ( 'localhost', 'root', '' );
if (! $link) {
die ( "Connection failed" . mysqli_errno ( $link ) );
}
function getDBlist() {
global $link;
$qry = ("SHOW DATABASES");
$res = mysqli_query ( $link, $qry );
while ( $row = mysqli_fetch_assoc ( $res ) ) {
echo '<input type="checkbox" name="db" value="' . $row ['Database'] . '" class="checkbox" />';
echo $row ['Database'];
}
}
getDBlist ();
The Script
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {"db=" + db},
success: function (html) {
$("#qryDisplay").show();
}
});
});
ajax.php
function showTables() {
if (isset ( $_POST ['db'] )) {
$db = $_POST ['db'];
$link = mysqli_connect ( '192.168.2.113', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
?>
<ul>
<?php
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
?>
<input type="checkbox" name="tbl[]" class="tbl_list"
value="<?php echo $row [0]; ?>" />
<?php echo $row [0]; ?>
<br>
<?php
}
}
}
showTables ();
?>
</ul>
<?php
function tblProperties() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
$db = $_POST ['db'];
$link = mysqli_connect ( '192.168.2.113', 'root', '', $db );
$qry = "DESCRIBE $tbl";
$result = mysqli_query ( $link, $qry );
?>
<div class="Table">
<div class="Heading">
<div class="Cell2">
<p> <?php echo $tbl; ?> </p>
</div>
</div>
<div class="Row">
<div id="topRow">
<input type="checkbox" name="tbl" id="tblall" value="All" />
<p>ALL</p>
</div>
<?php
while ( $row = mysqli_fetch_array ( $result ) ) {
?>
<div class="draggable-cell ui-widget-content">
<input type="checkbox" name="tbl" class="tblst"
value="<?php echo $row[0];?>" />
<p><?php echo $row[0]; ?> </p>
</div>
<?php }?>
</div>
</div>
<?php } } tblProperties();
(Clicking the checkbox should post a variable db to my ajax.php page)
At this point I believe i'm doing everything right, however when I call the ajax.php functions like showtables() in my index.php file I get no results. Could it be that the variables aren't being posted? If so why would the success condition be fulfilled? Have I missed something crucial?
Replace below:
data: {"db=" + db},
With below and try:
data: {db: db},
You need to echo your result set in ajax.php. you did not echo any thing or did not return anything.

Categories