AJAX/PHP/JS readyState = 1 and Status = 0 ALWAYS. No response text - javascript

I've been trying lately to use this sample of AJAX to compare form data to an SQL database from one http://www.example.com domain. My issue is that the readyState is always 1 and my Status is always 0. It is expecting 4 and 200 respectively. It also always returns responseText="" I've looked all over StackOverflow but have unsuccessfully found anything helpful.
I've boggled my mind over what could be the issue, but I just can't seem to get it to work.
*I've also tried to set file permissions on both the JS and PHP, but it functions the same.
*I'm using a dedicated web server to host all this, and I have no problem running most scripts.
//HTML GenerateRep.html
Excuse the lack of < and > tags missing, the code won't appear without them.
form id="formgen" onsubmit="GenRep(this)"
....form stuff....
button id="submit" type="submit">Submit</button
//JAVASCRIPT GenerateRep.js
function GenRep(formgen) {
var email = formgen['repemail'];
var hash = formgen['reppass'];
var first = formgen['firstname'];
var last = formgen['lastname'];
var territory = formgen['territory'];
hash.value = CryptoJS.SHA256(hash.value);
var login = email + ";" + hash.value + ";" + first + ";" + last + ";" + territory;
Login(login);
}
function Login(login) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText == "VALID") {
window.location.href = "success.html";
} else if (xhttp.responseText == "INVALID") {
$("#login_error").text("Failed! Plese check your info.");
} else {
window.location.href = "error.php";
}
}
};
xhttp.open("GET", "Validate.php?q=" + login, true);
xhttp.send();
}
//PHP Validate.php
<?php
header('Access-Control-Allow-Origin: *');
include ("ConnectDB.php");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//THIS IS A TEST TO SEE IF reponseText FUNCTIONS. IT DOES NOT.
//echo "testecho";
$whole = $_REQUEST['q'];
$userPass = explode (";", $whole);
$sql1 = "SELECT UName FROM Reps WHERE UName = '$userPass[0]'";
$result = $conn->query($sql1);
if ($result->num_rows > 0) {
$conn->close();
echo "INVALID";
} else {
$sql = "INSERT INTO Reps (UName, Pass, FName, LName, Territory) VALUES ('$userPass[0]', '$userPass[1]', '$userPass[2]', '$userPass[3]', $userPass[4])";
if ($conn->query($sql) === FALSE) {
$conn->close();
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "VALID";
}
?>

I previously "commented" instead of creating an "Answer" because I wasn't suggesting a fix, just a debug step to make sure what you thought was happening, was actually happening.
Since my suggestion helped you figure out the problem, I created this "Answer" in case you want to give me "credit". :-)

Related

Insert user-specific data into HTML via PHP, JSON, andJavascript

I know this site doesn't like "spot my mistake" code, but I'm desperate. I have a website that needs to access user-specific data from a database (PHP), convert the data into a JSON file, and then change a HTML header to display that specific data. The database table has the user email, password, and class name, among other things. I have a login page that establishes the session variables for the email and the password. When the user logs in, I want their class name to be entered into HTML text. I've used dozens of sources, mostly W3schools, and came up with this code:
PHP:
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
if (!$obj) {
die(mysqli_error());
}
$servername = "localhost";
$username = "id5143969_enviroquest1";
$password = "codeteam1";
$database = "id5143969_enviroquest1";
$link = mysqli_connect($servername, $username, $password, $database);
$result = $link->query("SELECT UserClassName FROM ".$obj->UserInfo1." WHERE ".$obj->UserEmail."= '". mysqli_real_escape_string($link,
$_SESSION['useremail']) . "' and ".$obj->UserPassword." = '" . mysqli_real_escape_string($link, $_SESSION['userpassword']) . "'");
if (!$result) {
die(mysqli_error());
}
$_SESSION['classname'] = $result->fetch_assoc();
if (!$_SESSION['classname']) {
die(mysqli_error());
}
echo json_encode($_SESSION['classname']);
Javascript:
function getclassname() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "UserInfo1":"UserClassName"};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("UserClassName").innerHTML = myObj;
}
};
xmlhttp.open("GET", "php2.php" + dbParam, true);
xmlhttp.send();
}
HTML:
<h1 class="text-center" id="UserClassName" name="UserClassName" onload=
"getclassname()"> </h1>
I have no idea what's going wrong, and am too new to coding to figure it out by myself.
Try this (I can't test it, but)—
PHP:
Remove the ?> at the end of the file. Pure-PHP files should always leave off the closing tag.
Change (MYSQLI_ASSOC) to just () - per this and the docs, you don't need it.
Javascript:
Remove the session_start() call
Change
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
to
txt = myObj.UserClassName
The fetch_assoc() call in PHP gives you a mapping that uses the database field names ("each key in the array represents the name of one of the result set's columns" per the docs) for a single row. Therefore, if the JSON encode/decode worked OK, you should be able to refer directly to the field.
To test this, in the developer tools, set a breakpoint at the txt = ... line and see what myObj is.
I don't think you need $obj, dbParam, or ?x=, but I would not suggest changing them unless the above doesn't help.
Good luck!

AJAX validating correct user

I'm using AJAX to delete posts from a forum.
The code does it so that the delete icon only shows if the session variable "user" equals the one in the database. This works perfectly so no need to include the code for that here i believe.
However, in theory, couldn't anyone just read the javascript code, go to the file where everything is processed and delete whatever they want?
My idea to fix this is to send over an additional variable with the username and check it once more on the processing page.
Ajax code:
$('#deletePost').click(function() {
var xhttp = new XMLHttpRequest();
var getId = <?php echo $_GET['id']?>
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var replace = confirm("Your post was successfully deleted. Click OK to return to the homepage.");
if (replace == true) {
location.replace('index');
} else {
location.reload();
}
}
}
xhttp.open('GET', 'deletepost.php?id=' + getId, true);
xhttp.send();
return false;
});
To explain my concern more deeply: Anyone can see the file where the information is processed, so they could just go to
http://www.website.com/deletepost.php
Then just apply any id they want so the url becomes something like
http://www.website.com/deletepost.php?id=22
And because there is no validation on the second page this would work.
<?php
if (!isset($_GET['id'])) {
echo 'e';
} else {
$id = intval($GET['id']);
$sql = 'DELETE FROM posts WHERE post_id=' . mysqli_real_escape_string($conn, $id);
$result = mysqli_query($conn, $sql);
if (!$result) {
echo 'Failed to delete your post. Please try again or contact administration.';
}
}
?>
So if anyone has any idea on how to validate this it would be very much appreciated. If anything is unclear please comment and I'll fill in.

Javascript AJAX PHP if statement not working

I've been struggling with this problem for over two hours now and can find any reasonable solution. If i will get rid of if statement marked by ---> this arrow. alert() on its on will work. It will will be triggered when i just put if(true) but it don't work with following condition. I'm not really good with this languages. Just have to finish that for school project. I'm sure it is something small but cat figure it out on my own.
Java Script Function
function checkLogin(str) {
if (str.length == 0) {
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var ret = xmlhttp.responseText;
----> if (ret == "match"){
alert("Login name already exists !");
}
}
}
xmlhttp.open("GET", "loginCheck.php?q=" + str, true);
xmlhttp.send();
}
}
PHP Code
/*
<?php
include 'db.inc.php';
date_default_timezone_set("UTC");
$login = $_REQUEST["q"];
$sql = "SELECT * FROM staffMembers";
if (!($result = mysqli_query($con,$sql))){
die ('An Error ->' . mysqli_error() );
}
while ($row = mysqli_fetch_array($result)){
$firstName = $row['nameLogin'];
$ret="true";
if($firstName == $login){
$ret = "match";
break;
}
}
mysqli_close($con);
echo $ret;
?>
*/
Your PHP code has possibly output whitespace around match. Try this
if (ret.trim() == "match"){

Passing variable to php MySQL script with Javascript

I borrowed this code from another source.
Now, I am attempting to modify it.
I need to pass the contents of $q to my php page and use this as a where clause in my SQL statement.
My Javascript:
<script>
function subject(str) {
if (str == "") {
document.getElementById("subject").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("subject").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","form_get.php?q="+str,true);
xmlhttp.send();
}
}
</script>
Inside the html select code I am using:
onchange="subject(this.value)"
My PHP
$q = intval($_GET['subject']);
//if (!empty($_GET['q'])){
//$q = $_GET['q'];
//}
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";
As you can see, I am passing the $q into my SQL statement.
I understand that intval returns a number, but when I try other types, such as strval, it breaks the script. It als breaks the script when I tried the commented out section above.
When I change the php to: $q=$_GET["q"]; I get the error: form_get.php?q=Reading 500 (Internal Server Error).
This tells me that $q is indeed pulling from the options list, but something else is going on...
the problem is with your php you suppose to get the q and not subject
$q = intval($_GET['q']);
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";
$q = intval($_GET['subject']);
This looks wrong - should that not be $q = intval($_GET['q']);?

php script restarts randomly with same POST data

I have a php script that receives parsed data from a javascript application via xmlhttp.
I'm finding that the php script will sometimes stop while it's processing a chunk of data and restart with the same POST data that was sent to it. I thought that maybe the javascript's xmlhttp might be double firing somehow, but I've ruled that out with an inProgress flag as shown below.
function SendPHP(str, callback){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
xmlhttp.open("POST","sendmail.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
inProgress=false;
if(xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if (inProgress==false){
inProgress=true;
xmlhttp.send(str);
}
else{
writeDisplayConsole("ERROR: xmlhttp fired twice!");
}
}
If the xmlhttp tries to send twice then that error is shown and no further packets will be sent. But that's never the case so the php script must be restarting on it's own.
Bear in mind that it happens at random intervals, not at the same time every time with the same data. What could be causing this to happen?
The php script frequently writes to big text file logs, could that be something to do with it?
Here's the php (but since the error happens at random intervals with the same data, I'm not sure how it could be a problem with the php code):
<?php
writelog("\n*** Sendmail script started ***");
$q = $_POST['q'];
//Split auth code and verify
$pieces = explode("(<!asplit!>)", $q);
$authc=$pieces[0];
$q=$pieces[1];
if ($authc<>"****"){
echo "!Authentification denied.";
writelog ("Authentification denied");
die;
}
writelog ("Authentification accepted");
//Split off packet details
$pieces=explode("(<!psplit!>)", $q);
$tpack=$pieces[0];
$q=$pieces[1];
$pieces=explode("-", $tpack);
$tpacket=$pieces[0];
$ofpacket=$pieces[1];
$totalcontacts=$pieces[2];
//Split contact data from email message
$pieces = explode("(<!dsplit!>)", $q);
$split=$pieces[0];
$q=$pieces[1];
//Assign contacts to array
$contacts = explode ("<!", $split);
$tcount=count($contacts);
$tcount=$tcount-1;
echo "(PACKET ";
echo $tpacket;
echo " OF ";
echo $ofpacket;
echo ")- ";
writelog("(PACKET " . $tpacket . " of " . $ofpacket . ")");
//Killswitch check incase double run
checkKillSwitch("!Startup aborted as Power set to off.",0);
checkKillSwitch("!Aborted, Killswitch set to Kill",1);
file_put_contents('log/killswitch.txt', "on");
echo $tcount;
echo " contacts processing...";
foreach ($contacts as &$value) {
//check killswitch
checkKillSwitch("Killswitch aborted during runtime",1);
$split=explode ("^!", $value);
//Get the contact's details
$firstname= $split[0];
$lastname= $split[1];
$temail = $split[2];
if ($firstname<>""){
$mainmessage=str_replace("[firstname]",$firstname,$q);
$mainmessage=str_replace("[lastname]",$lastname,$mainmessage);
//Split off subject
$pieces = explode("(/subject)", $mainmessage);
$tsubject=$pieces[0];
$mainmessage=$pieces[1];
testLogMail($temail, $tsubject, $mainmessage);
//log progress
$adder=$adder+1;
//For the log, show progress of total (based on 10 per packet change if different)
$tadder = (($tpacket-1)*10)+$adder;
echo ($tadder . ".");
writelog($tadder . " of " . $totalcontacts . " processed >> " . $temail);
sleep(rand(2,20));
}
}
function testLogMail($xaddress, $xsubject, $xmessage){
$tdate=date('d/m/Y H:i:s');
$file = 'log/testmaillog.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Enter email
$towrite="To: ".$xaddress."\n";
$towrite.="Subject: ".$xsubject."\n";
$towrite.="Date: ".$tdate."\n";
$towrite.="...\n";
$towrite.=$xmessage."\n";
$towrite.="___________________________________\n\n";
$current .= $towrite;
// Write the contents back to the file
file_put_contents($file, $current);
}
function writelog($towrite)
{
$tdate=date('d/m/Y H:i:s');
$file = 'log/testlog.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $towrite." --- ".$tdate."\n";
// Write the contents back to the file
file_put_contents($file, $current);
}
function checkKillSwitch($towrite, $killtype){
if ($killtype==0){
$killswitch = file_get_contents('log/killswitch.txt');
if ($killswitch=="on") {
echo $towrite;
writelog($towrite);
die;
}
}
if ($killtype==1){
$killswitch = file_get_contents('log/killswitch.txt');
if ($killswitch=="kill") {
echo $towrite;
writelog($towrite);
die;
}
}
}
writelog("*** Sendmail script ended ***");
?>

Categories

Resources