PHP class variable failing to update via XMLHttpRequest - javascript

I'm trying to get some code to work for a uni assignment, I am still learning but feel like I'm going a little crazy trying to understand why a class variable is not working.
Using a PHP class such that
class Users {
//Variables
protected $_userName;
protected $_password;
protected $_login;
protected $_firstName;
protected $_lastName;
protected $_email;
protected $_phone;
protected $_addressStreet;
protected $_addressCity;
protected $_addressState;
protected $_company;
public function __construct() {
// gets the number of parameters
$numArgs = func_num_args();
$arg_list = func_get_args();
// make decisions based on the arguments number
switch($numArgs){
case "2":return $this->ConstructorWithTwoArgs($arg_list[0], $arg_list[1]);
case "10":return $this->ConstructorWithTenArgs($arg_list[0], $arg_list[1],$arg_list[2], $arg_list[3],$arg_list[4], $arg_list[5],$arg_list[6], $arg_list[7],$arg_list[8], $arg_list[9]);
default:
//Handle exception for method not existing with that many parrams
break;
}
}
//In order to log in we require minimum of user name and password
protected function ConstructorWithTwoArgs($userName, $password){
$this->_userName = $userName;
$this->_password = $password;
$this->_login = "false";
return $this;
}
//Checks users details and updates user details if valid
public function DoLogin(){
$result = false;
// Check if userName and password exist in the db
$query = "SELECT * FROM SIT203Users WHERE USER_NAME = :userName AND PASSWORD = :password";
// Create a new connection query
$ds = new Connection();
$ds->parse($query);
$ds->setBindValue(':userName', $this->_userName);
$ds->setBindValue(':password', $this->_password);
$ds->execute();
//User exists if rows are returned there will only be one as userName is unique
if($ds->getNextRow()){
$result = true;
$this->_login = "true";
$this->_firstName = $ds->getRowValue("FIRST_NAME");
$this->_lastName = $ds->getRowValue("LAST_NAME");
$this->_email = $ds->getRowValue("EMAIL");
$this->_phone = $ds->getRowValue("PHONE");
$this->_addressStreet = $ds->getRowValue("ADDRESS_STREET");
//Ensure all street details are obtained
if($ds->getRowValue("ADDRESS_STREET2"))
$this->_addressStreet .= $ds->getRowValue("ADDRESS_STREET2");
$this->_addressCity = $ds->getRowValue("ADDRESS_CITY");
$this->_addressState = $ds->getRowValue("ADDRESS_STATE");
$this->_company = $ds->getRowValue("COMPANY");
}
$ds->freeResources();
$ds->close();
return $result;
}
}
Now this class works fine for a direct call to it from;
http://www.deakin.edu.au/~jtparker/SIT203/xyz/flower_shop2/MyAccount.php?userName=JaieP&password=jp
<?php
require_once('initialise.php');
// Need to Validate all feilds and remove unwanted text
// The feilds to be tested are the $_REQUEST values
$userName = Validation::validateString(isset($_REQUEST['userName'])?$_REQUEST['userName']:"");
$password = Validation::validateString(isset($_REQUEST['password'])?$_REQUEST['password']:"");
$remberMe = isset($_REQUEST['remberMe'])?$_REQUEST['remberMe']:"";
// Create a new user
$newUser = new Users($userName, $password);
// Try and login
$newUser->DoLogin();
if($newUser->getLogin() == "true")
{
$_SESSION['user'] = $newUser;
// Echo out the users details plus cart details for last 3 months
//test its working to here
//echo($newUser->toString());
echo("Its working!!!");
}
else
{
//echo("falseValue");
echo($userName.$password.$remberMe.$newUser->getLogin().$newUser->getUserName().$newUser->DoLogin().$newUser->toString());
}
?>
But when I try to use it via a javascript call using the below code the _login variable fails to update and for the life of me I can't work out why?
as can be seen from this link;
http://www.deakin.edu.au/~jtparker/SIT203/xyz/flower_shop2/myaccount.html
it fails every time?
Any ideas
Many thanks in advance
Jaie
function TryLogin(){
try{
// Get the userName and password supplied
var userName = document.getElementById( "userName" );
var password = document.getElementById( "password" );
// Get the remember me value
var rememberMe = document.getElementById( "rememberMe" );
// Get the error feild
var errorDisplay = document.getElementById( "submitError" );
// set to no error
errorDisplay.innerHTML = "";
var documentMyAccount = document.getElementById( "myAccount" );
// Submit details to server for verification if not empty
if(userName.value != "" && password.value != ""){
// Now check via DB if username and password are valid
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// IF Response indicates a successful login
var myResponse = xmlhttp.responseText;
if(myResponse != "falseValue"){
// set to nothing
documentMyAccount.innerHTML = "";
// add php content
documentMyAccount.innerHTML = myResponse;
}
else{
// Do not advise what details are incorrect, just that some combination is incorrect
errorDisplay.innerHTML = "Sorry those details are not correct";
}
}
}
var submitString = "MyAccount.php?";
submitString +="userName="+userName.value;
submitString +="&password="+password.value;
submitString +="&rememberMe="+rememberMe.checked?"true":"false";
xmlhttp.open("GET",submitString,true);
xmlhttp.send();
}
else{
errorDisplay.innerHTML = "Not all details have been entered!";
}
}
catch(error){
alert(error.message);
}
}

You simply have to debug what's the final URL that is being called by your AJAX and confirm if everything is being sent as you expect and that will solve it.
Try
console.log(submitString)
before your AJAX call and you'll know if everything is being sent correctly.

Related

PHP not able to read JSON but writes extra lines in SQL

I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits

Check if form has been submitted via ajax in php

I have a login form which is validated using javascript and then sent to php file for further processing. Form is submitted via ajax.
Currently, i have an if statement in php file that checks whether form has been submitted, problem is this if statement never evaluates to true. Hence my php code inside my if statement never runs. When request is sent via ajax, .onload event gets invoked without if statement inside php file evaluating to true.
Question
Once the form is submitted to php file via ajax, how can i detect in php file that form has been submitted via javascript.
Here's my php code
<?php
require 'DbConnection.php';
// if form is submitted
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
echo '<script>alert(\'form submitted\')</script>';
verifyLoginCredentials($username, $password);
} else {
echo '<script>alert(\'form not submitted\')</script>';
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
}
else { // if username/password combination is incorrect
echo 'Incorrect Username/Password Combination';
}
} else { // if username doesn't exists in the database
echo 'Entered username isn\'t registered';
}
} else {
echo 'Error while preparing sql query';
}
}
?>
and here's relevant javascript code
let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');
// submit login form to server using ajax
function ajaxFormSubmit() {
'use strict';
let ajaxRequest = new XMLHttpRequest();
let url = 'admin login.php';
// login form submitted on server successfully
ajaxRequest.onload = function () {
if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'success');
}
};
// error while login form submission on server
ajaxRequest.onerror = function () {
if (ajaxRequest.status !== 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'error');
}
};
ajaxRequest.open('POST', url, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(new FormData(loginForm));
}
function validateForm(e) {
'use strict';
// prevent form submission
e.preventDefault();
if (anyEmptyField()) {
displayInfoMessage('Please fill all the empty fields', 'error');
highLightEmptyFields();
//return false;
return;
}
// check if username is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
displayInfoMessage('Username not valid', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if username is atleast 3 characters long
if (usernameField.value.length < 3) {
displayInfoMessage('Username should contain atleast 3 characters', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if password is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
displayInfoMessage('Password not valid', 'error');
highLightTextField(passwordField);
//return false;
return;
}
// check if password is atleast 6 characters long
if (passwordField.value.length < 6) {
displayInfoMessage('Password should contain atleast 6 characters', 'error');
highLightTextField(passwordField);
//return false;
return;
}
//return true;
// submit form information to server via ajax
ajaxFormSubmit();
}
// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);
There is no guaranteed way to know that the form was submitted via ajax.
Normally this is done via headers, in our case HTTP_X_REQUESTED_WITH which can be retrieved via the global $_SERVER variable.
Do note that headers can easily be spoofed.
You can check like so:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// code here
}
Here's a few links to look at:
https://paulund.co.uk/use-php-to-detect-an-ajax-request
How to check if the request is an AJAX request with PHP

Duplicate JavaScript and php problems

I recently notice that I have a duplicate line on the table, when the device is spinning or calling someone on this davay at the time of pressing the 'save' button. On the lines of UserRealTime I see that the interval is a duplicate of 5-6 milliseconds.
How to avoid duplicates using javascript or jQuery. For example, check the connection of the device to the Internet?
ajax.php
<?php
if (isset($_GET['d1']) && isset($_GET['d2']))
{
$conn=connSQL();
$query = "insert into doorname(d1, d2, UserRealTime) values ('".$_GET['d1']."','".$_GET['d2']."', getdate())";
$rs=$conn->execute($query);
$rs->Close();
$conn->Close();
}
?>
JavaScript
<script>
var httpObject = null;
function getHTTPObject()
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
return null;
}
}
function Inter()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
var d1=document.getElementById('d1').value;
var d2=document.getElementById('d2').value;
if (d1=="" || d2=="")
{
alert("sorry!!!");
}
else
{
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2, true);
httpObject.send(null);
httpObject.onreadystatechange = InterSet;
}
}
}
function InterSet()
{
if(httpObject.readyState == 4)
{
var data=httpObject.responseText;
alert("Good!!!");
}
}
</script>
This way of approach it is not a suggested practice. However, just to work around the problem here is one way of handling general duplicate DB entries.
Generate one random Token on the client side for every successful server side insert. Discard the Token on client side once the server confirms the successful insert. Following is an example:
1) Generate a random Token on the client side, like so
Generate random string/characters in JavaScript
var tokenOnClientSide = makeid();
2) Attach the generated Token to Ajax Params:
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2+"&token="+token, true);
3) Server side: Look if the Token already exists
<?php
if (isset($_GET['d1']) && isset($_GET['d2']) && isset($_GET['token']))
{
$query = sprintf("SELECT * FROM token_table WHERE token = '%s'", $_GET['token']);
$rs=$conn->execute($query);
if (mysql_num_rows($res) == 0) {
// carry on with insert and return success message
.....
// now store the token permanently
$query = "insert into token_table(token, time_of_exec) values ('".$_GET['token']."', getdate())";
$rs=$conn->execute($query);
}
4) Finally, unset the global token on client side
tokenOnClientSide = "";
Hope that one gets a basic idea of handling duplicates.

All users been blocked after login

I am creating a login form which if the user tries 3 input login it will automatically block. but the problem is after 1 login only it already block. and All the users have been blocked. I want only after 3 times the username that i input will be blocked. Can someone help me?Thank you.
here is my code...
<!DOCTYPE html>
<?php
function p(){
$xmldoc=new DOMDocument();
$xmldoc->load('person.xml');
$root=$xmldoc->documentElement;
$data=$root->getElementsByTagName('user');
$status="Blocked";
if($data){
$domelemupdate=[];
foreach ($data as $domElement) {
$domElement->childNodes->item(5)->textContent=$status;
}
}
foreach ($domelemupdate as $domElement) {
# code...
$domElement->parentNode->replaceChild($domElement);
}
$xmldoc->save('person.xml');
}
?>
<html>
<head>
<body>
</body>
</head>
</html>
var ctr=0;
window.login = function(e)
{
if (document.frmlogin.login_username.value == "")
{
alert("User name is not blank");
return;
}
else if(document.frmlogin.login_pass.value == "")
{
alert("Password is not blank");
return;
}
else
{
var xmlDoc;
var x;
var txt = "";
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.overrideMimeType('text/xml');
xhttp.open("GET", "person.xml", false);
xhttp.send(null);
xmlDoc = xhttp.responseXML;
var ktra=false;
var xml=xmlDoc.childNodes[0];
var name = xml.childNodes["username"];
var pass=xml.childNodes["password"];
var status=xml.childNodes["status"];
for(var i=0;i<xml.childNodes.length;i++){
if(xml.childNodes[i].nodeName=="user"){
name = xml.childNodes[i].childNodes[3];
pass = xml.childNodes[i].childNodes[5];
status = xml.childNodes[i].childNodes[7];
position = xml.childNodes[i].childNodes[9];
if(name.textContent==frmlogin.login_username.value && pass.textContent==frmlogin.login_pass.value && status.textContent== "Active")
{
alert("Login Success!");
}
}
if(ktra==false)
{
ctr+=1
alert("Login Failed !!!" +ctr);
if(ctr==3){
//alert("You are now Blocked!!!" );
x=p()
alert(x);
}
}
}
}
</script>
Whenever i call the function in my ctr==3 .If i run the program,if for example i try first login wrong username . after i click login the text easily update to block,.i want my counter 3 times before it will be block and i want the user that i input will be blocked only not all the users
You should be keeping track of the failed count either in a database, or write to the XML file an incremental count each time they fail to login with valid credentials..

AJAX email form will not submit

I have an email sign-up form on my site that I recently added validation to.
Now, the form will not send or provide an error message. When I check the inspector I see the following error:
TypeError: null is not an object (evaluating 'document.getElementById(update[0]).innerHTML = update[1]')
This is my contact.php file
<?php
$to = "hello#interzonestudio.com";
$subject_prefix = "";
if(!isset($_GET['action']))
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to,$subject,$message,"From: ".$email."");
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>';
else {
echo("$email is not a valid email address");
}
?>
This is my form in HTML
<div id="contactarea">
<span style="font-family: 'Old Standard TT', serif;">Newsletter</span>
<form id="contactform" name="contactform" >
<input class ="email" type="text" name="email" id="inputbox" value="E-Mail"
onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
<input type="submit" value="Submit" name="send" onclick="sendemail(); return false; " class="signup" >
</form>
</div>
and this is my javascript
<script language="javascript">
function createRequestObject() {
var ro;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} else {
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sendemail() {
var email = document.contactform.email.value;
document.contactform.send.disabled = true;
http.open('get', 'contact.php?email=' + email + '&action=send');
http.onreadystatechange = handleResponse;
http.send(null);
setTimeout(function() {
jQuery(document).find("#thanks").fadeOut();
}, 3000);
}
function handleResponse() {
if (http.readyState == 4) {
var response = http.responseText;
var update = new Array();
if (response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById(update[0]).innerHTML = update[1];
}
}
}
</script>
Any insight would be greatly appreciated.
I think this is what you are looking for:
document.contactform.send.disabled=false;
add another div in html page with id = "msg"
replace
document.getElementById(update[0]).innerHTML = update[1];
with
you can add conditions here
depending on what you want to display upload[0] or upload[1]
document.getElementById('msg').innerHTML = update[0]+update[1];
and in contact.php
there is '}' missing before else.
Multiple errors, client and server-side.
Changes to javascript. Your form data wasn't being sent in the php call.
I have made changes to your call type get/post and used new FormData(). If you want to add more to your call formdata.append("ParamName", Value/Variable); and use $something=$_POST['ParamName']; to get the post in PHP.
var formdata = new FormData();
formdata.append("email", email);
formdata.append("action", "send");
http.open('POST', 'contact.php');
http.onreadystatechange = handleResponse;
http.send(formdata);
Changes to PHP. You missed the opening/closing of the if statements.
The way you have your javascript setup, you split the php reply (|) if the email posted wasn't valid you would cause a JS error because you didn't have the divID and bar(|) in your echo.
$to = "hello#interzonestudio.com";
$subject_prefix = "";
if(isset($_POST['action'])){ // ***** Missing ({)
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_POST['email']); //The senders subject
$email = trim($_POST['email']); //The senders email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)===false) {
mail($to,$subject,$message,"From: ".$email."");
// **** Div ID Missing with Bar (contactarea|)
echo 'contactarea|<div id="thanks">Thank you. We promise you won\'t regret it.</div>';
// **** Else missing (})
}else {
echo("contactarea|$email is not a valid email address");
}
}// **** Close if issset (})
I hope I have covered all your problems in this answer.
If you don't understand anything please leave a comment below, i will update the answer to help you understand anything within this answer. I would rather you take this source code understand it, not just a copy paste. You won't learn from copy/paste.
Tip: Clean your php string before putting them into mail().
I hope this helps. Happy coding!

Categories

Resources