yii framework where method isn't saving properly - javascript

I am using Yii framework and I am creating a register page for the user. In order for a user to create an account, they need to enter in a ticket code. A widow form pops up and they fill out the ticket code, it ajax validates it properly and stores it as a session variable. The popup window closes and allows the user to fill out the rest of the form and submit it. The form should then validate the information, create the user, reasign the ticket's user_ID to the new user_ID, and load the page /ticket/mytickets.
what happens, the ticket is confirmed that it exists, saves it into the session, the user is created, the ticket reassign method gets called, the ticket is never reassigned, and the page reloads. When I echo out the page on the reload, it shows the correct information for the user_ID, and the ticket_ID.
Any hints would help for debugging this would be helpful. Thank you
//controler
public function actionRegister()
{
$model=new User;
$valid = false;
//check to see if valid
if(isset($_POST['User'])){
$valid = $model->checkValid();
}
if($valid)
{
$model->attributes=$_POST['User'];
$user_ID = $model->ID;
if($model->save()){
//save ticket to user
$reassigned = Ticket::model()->reassign_with_IDs($_SESSION['ticket_ID'],$user_ID);
if($reassigned){
unset($_SESSION['ticket_ID']);
//redirect to mytickets
$this->redirect(array('/ticket/mytickets'));
}
}
}
$this->render('register',array(
'model'=>$model,
));
}
//model
public static function reassign_with_IDs($ticket_ID,$user_ID){
$ticket = Ticket::model()->findByPK($ticket_ID);
$ticket->user_ID = $user_ID;
if($ticket->save()){
return true;
}
else{
return false;
}
}

$model->ID is only set after $model is saved. Therefore your code should read:
if($valid)
{
$model->attributes=$_POST['User'];
if($model->save()){
//save ticket to user
$user_ID = $model->ID;
$reassigned = Ticket::model()->reassign_with_IDs($_SESSION['ticket_ID'], $user_ID);
You can however get rid of the reassign_with_IDs function and the unnecessary variable user_ID and just explicitly set the ticket using:
$reassigned = Ticket::model()->updateByPk($_SESSION['ticket_ID'], ['user_ID'=>$model->ID]);

Related

How do I resend data from previous url after reCAPTCHA passed in the same page?

Data sent from this
www.example.com/modules/liaise/index.php?form_id=xxx
In normal condition, after submit, the page redirects to
www.example.com/modules/liaise/index.php
and sends mail.
Wantedly, I placed the reCAPTCHA in the same file (index.php).
Google captcha :
require_once "recaptchalib.php";
// your secret key
$secret = "secret key";
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
//send mail
} else {
echo '
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div id="html_element"></div>
<script>
var onloadCallback = function() {
grecaptcha.render("html_element", {
"sitekey" : "sitekey",
"callback" : correctCaptcha
});
};
var correctCaptcha = function(response) {
location.reload();
};
</script>';
}
Whenever I pass reCAPTCHA and page reloads, reCAPTCHA shows again.
I know data from previous page www.example.com/modules/liaise/index.php?form_id=xxx is still there by using
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
Is there any way by which I can resend data from previous url after reCAPTCHA is passed in the same page?
I am newbie in coding. Please be specific.
Thank you so much!
If your talking about re-sending your data as mail you can use something like this:
if (isset($_POST['form-input'])) {
// Send mail
}
and every time you reload the page and the Post data is not null or blank, it will run that code.
If you are wanting the reCAPTCHA to reload as success, I would say that's defeats the security of reCAPTCHA
Also I see that you have a typo esle should be else.

Alerting users on website through ajax

I'm attempting to make a notification system that notifies users when they are assigned to a ticket, or when a new ticket is added to the database.
The system itself, that I already have, works except that it only sends the notification to the first user who receives the ajax request. Is there any way to make it so that everyone who is suppose to receive the notification, actually receives the notification?
My code:
javascript:
function checkUpdates()
{
$.ajax({
type: "POST",
url: 'ajax/checkDB.php', // a webservice or other URL that queries the database
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log('Connected and executed PHP page... '+data);
if (data.hasChanged == "true") {
playSound('img/notif2');
notifyAdmin();
console.log('Updated Tickets Page...');
$("#contents").load("dynamic/tickets.php");
$("#contents").fadeTo("fast", 1);
}
if (data.newAssigned == "true") {
playSound('img/notif2');
notifyUser();
console.log('Updated Tickets Page...');
$("#contents").load("dynamic/tickets.php");
$("#contents").fadeTo("fast", 1);
}
}
});
}
$(document).ready(function() {
setInterval("checkUpdates()", 3000); // Calls the function every 3 seconds
});
My php script (checkDB.php):
<?php
include("../static/config.php");
session_start();
header("Content-Type: text/json");
$result = mysqli_query($con,"SELECT notify FROM tickets WHERE notify='0'");
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0) {
$hasChanged = 'true';
mysqli_query($con,"UPDATE tickets SET notify='1' WHERE notify='0'");
} else {
$hasChanged = 'false';
}
$result2 = mysqli_query($con,"SELECT notify,Assigned FROM tickets WHERE Completeness='1' AND notify='1'");
$row_cnt2 = mysqli_num_rows($result2);
if($row_cnt2 > 0) {
while($row2 = mysqli_fetch_array($result2))
{
if(strcmp($_SESSION['Name'],$row2['Assigned']) == 0) {
$newAssigned = 'true';
} else {
$newAssigned = 'false';
}
}
mysqli_query($con,"UPDATE tickets SET notify='2' WHERE Completeness='1' AND notify='1'");
} else {
$newAssigned = 'false';
}
echo json_encode(array('newAssigned' => $newAssigned, 'hasChanged' => $hasChanged));
?>
Here is a rundown of my exact intentions:
User logs into system, and is given administrative rights if granted.
User loads the tickets page, which lists all the tickets along with this javascript that I gave you
the javascript loads checkDB.php every 3 seconds, basically running a check against the database for a 'notify' value of 0, and if at least 1 exists, is updated in the database to '1' and is returned as true to the ajax call - which sends out notifications.
Again this works for the 1st user who is loaded into the page, but after that, obviously there are no more 'notify=0' in the database as they have already been updated, so they are not shown the notification.
It was requested that I share my database structures.
tickets:
UniqueID - Unique ID per ticket (always unique)
Requester - Whoever submitted the ticket.
Problem - Description of the given issue.
Assigned - User who is assigned to the ticket.
Completeness - The level of completeness (0-4)
Times - Times listed for ticket start, assigned, etc
notified - Used in old ticket system (I plan to get rid of it)
Urgency - Selected by requester, how urgent the ticket is
Location - Location in our warehouse assistance is needed.
FollowUp - currently not in use, will be used to submit follow ups.
isProject - (0-1) is project or not
additionalTechs - Lists additional users on a ticket (Not important for question)
notify - (0-2) at 0, ticket is new and notif should be sent to admins which should set this to 1, when it is 1 it should send a notif to users that are attached to the ticket.
Techs Database:
UniqueID
Username
Password
Name
Level
Disabled
LastTimeSeen
needsNotify (Used in old system, plan to remove)
I'm really stuck here.
You can make it with websockets, or socket.io.
Then the js of multiple clients will connect with that socket will notify all connected people about they ticket
You can change your update statement to something like:
UPDATE tickets SET notify='1' WHERE notify='0' and Assigned = ''//some user id passed

How to check if USERNAME already exists in PHP/MYSQL?

I'm currently configuring my "User Registration" form in PHP.
Trying to create a simple function to check if the username already exists in the database
After doing my research, I have found that there are several ways this can be done.
(a) the best way is probably to use a PHP/AJAX combination, to check right away if the username already exists (in other words, the check is done BEFORE the user clicks the "Submit" button;
(b) the other way is to do a simple SQL-query, which will return an error message, if that particular username already exists in the database. (The only drawback with this method is that : the check is done only AFTER the user clicks the "Submit" button.
I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.
So, I went with Option B instead.
And, I got it working.
Here is the simply query I used :
if(isset($_POST['submit1'])||isset($_POST['submit1'])) {
$login = $_POST['login'];
$query_login = "SELECT login FROM registration WHERE login='$login';";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "Sorry, that Username is already taken. Please choose another.";
return false; }
else { //proceed with registration
It worked fine. The error was displayed.
The only problem is : the registration form itself disappeared.
I would have liked to display the error on the same page as the registration form, without having to RESET or somehow GO BACK.
I know that the reason for this is something very minor (and kinda stupid on my part :D :D)
Probably something to do with that "return false" thingy at the end of the query.
But, I am not sure.
(a) How can I get the error message displayed on the form-page itself?
(b) Or, better yet, is there a JavaScript Function I can use for this, so that I can simply call the function in the "Submit" button................like so : onSubmit = return function() ??
Thanks
UPDATE: Here is my form code.
form action="myform.php" method="post">
<br>
Choose a username : <input type="text" name="login" value="<?=$login?>"
required>
UPDATE
I was able to find the following jQuery code :
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is
Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not
Available');
}
});
}
I assume that, for my particular example :
(a) the jQuery file cannot be inserted into the actual PHP file (my php file is named : registration.php, which includes both the html and php);
(b) this particular jQuery file includes a "button", which needs to be clicked to check if the username already exists. This is not a bad idea; but, I would rather that this was done automatically, without the need to click on a button (let's face it : there are some users out there who are indeed too clueless to perform this simple check manually). My aim is free the user as much as possible from the need to do such trivial tasks :D
Anyway, my point is : so as to eliminate the need for a button, I would like to include an auto-function which checks once the user types in the username.
According to Google, the following function is what I need :
Replace $(‘#check_username_availability’).click(function(){ … with $(‘#username’).keyup(function(){ …
(c) Isn't there any way to actually insert that JQUERY into "registration.php" ?? Or, should it be a separate file entirely?
The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. Don't forget to check the username after form submission at before form submission.
Below your input box create a
<span class= "error">Username is already present. </span>
<span class= "success">Username can be assigned. </span>
and just display the message accordingly.
You may use the script as
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {"username",$("input.username").val()},
success : function (data)
{
if(data == "success")
{$(".success").show();$(".error").hide();}
else
{$(".error").show();$(".success").hide();}
},
});
You php code would be something like this :
$query = "SELECT username FROM tab_users WHERE username = '".$_POST['username']."'";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "fail";
return false;
}
else
{
echo "success";
return false;
}
You can disable the submit button and add a span message near the input field.
Check this code:
function checkUsername()
{
var username = document.getElementById('username');
var message = document.getElementById('confirmUsername');
/*This is just to see how it works, remove this lines*/
message.innerHTML = username.value;
document.getElementById("send").disabled = true;
/*********************************************/
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {username: username},
success: function (response) {
if (response==0)
{
message.innerHTML = "Valid Username";
document.getElementById("send").disabled = false;
}
if (response==1)
{
message.innerHTML = "Already Used";
document.getElementById("send").disabled = true;
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="uername">Username:</label>
<input type="text" class="form-control" name="username" id="username" onkeyup="checkUsername(); return false;" required/>
<span id="confirmUsername" class="confirmUsername"></span>
<button type="submit" id="send" name="action" value="Send">Send</button>
put this
include([your validating php file]);
and in your form action link to your login form file.
note : your login file have to be php file.

jQuery open page in a new tab while passing POST data

I have a javascript variable called "list". I need to send it as a POST data to another page and open that page in a new tab (with the POST data present).
This code:
jQuery.post('datadestination.php', list);
sends the data all right, but ofcourse it opens the page in the same tab.
I saw some solutions to similar problems using invisible form and things like that, but I could not get them to work. Is there any simple solution?
You can send a form using the target="_blank" attribute.
<form action="datadestination.php" method="POST" target="_blank" id="myform">
<input type="hidden" name="list" id="list-data"/>
<input type="submit" value="Submit">
</form>
Then in JS:
jQuery('#list-data').val(list);
jQuery('#myform').submit();
This is an implementation of Sergey's solution.
<?php // this is save.php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
// So even if someone passed _POST[isAdmin]=true, all that he would do
// is populate _SESSION[data][isAuthenticated], which nobody reads,
// not the all-important _SESSION[isAuthenticated] key.
if (array_key_exists('data', $_POST)) {
$_SESSION['data'] = $_POST['data'];
$_SESSION['data.timestamp'] = time();
// Let us let the client know what happened
$msg = 'OK';
} else {
$msg = 'No data was supplied';
}
Header('Content-Type: application/json; charset=utf8');
die(json_encode(array('status' => $msg)));
?>
In the first page:
$.post('save.php', { data: list }, function(response){
if (!response.status) {
alert("Error calling save");
return;
}
if (response.status !== 'OK') {
alert(response.status);
return;
}
// We had a response and it was "OK". We're good.
window.open('datadestination.php');
});
And in datadestination.php add the fix:
if (!array_key_exists('data', $_SESSION)) {
die("Problems? Did you perchance attempt to reload the page and resubmit?");
// For if he did, then yes, $_SESSION would have been cleared.
// Same if he is operating on more than one window or browser tab.
}
// Do something to validate data. For example we can use data.timestamp
// to assure data isn't stale.
$age = time();
if (array_key_exists($ts = 'data.timestamp', $_SESSION)) {
$age -= $_SESSION[$ts];
}
if ($age > 3600) {
die("Data is more than one hour old. Did someone change server time?!?");
// I actually had ${PFY} do that to me using NTP + --hctosys, once.
// My own time zone is (most of the year) exactly one hour past GMT.
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data'], $_SESSION['data.timestamp']);
// keep things clean.
// From here on, the script behaves "as if" it got a _POST.
Update
You can actually merge save.php and datadestination.php and use a "saving stub" savepost.php that you can recycle in other pages:
<?php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
if (array_key_exists('data', $_POST)) {
// Timestamp sent by AJAX
if (array_key_exists('ts', $_POST)) {
// TODO: verify ts, but beware of time zones!
$_SESSION['data'] = $_POST['data'];
Header("Content-Type: application/json;charset=UTF-8");
die(json_encode(array('status' => 'OK')));
}
die("Error");
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data']); // keep things clean.
?>
Now your call becomes
$.post('datadestination.php', { data: list, ts: Date.now() }, function(){
window.open('datadestination.php');
});
and in your datadestination.php (or anywhere else) you add
require 'savepost.php';
I suggest:
Pass that list with the jquery.post() function and save it in the SESSION array.
Open a new tab with the same file/address/URL with the window.open() function.
Retrieve saved data from the SESSION array.
This seems straightforward and clean to me.

Load disparate views based on user name using PHP

I have created a student and teacher feedback system using PHP and MySQL. Students and lecturers should be shown a separate view once they login. A students username takes the form of B******** and a lecturers' username takes the form of E********. I'm thinking is there a way to take the user inputed username and to truncate it and match the B or E and then serve up the relevant PHP view for the given user or is there a better way to achieve what I'm after. I'm relatively new to PHP so any help would be much appreciated.
Below would be my approach:
In the database, make a "userType" column that indicates whether a username belongs to a student or a teacher.
User submits their login details. You find a match, check the "userType" column and display a view accordingly.
Here's a very basic example with code
$sql = $this->db->query("
SELECT userType
FROM userTable
WHERE userName = //Username typed in by the user
AND password = //Password typed in by the user
");
$result = $sql->fetchAll();
if($result[0][0] == "student") include_once "student.php";
if($result[0][0] == "teacher") include_once "teacher.php";
else echo "User does not exist";
You can easily get the first character of a string with array access syntax [], string access syntax {}, and a variety of other methods.
if ("B" == $name[0]) {
// show student page
}
else {
// show instructor page
}
if ( $username[0] == 'E' )
{
// It's a teacher
} else if ( $username[0] == 'B' )
{
// It's a student
} else {
// Username is invalid
}

Categories