Javascript AJAX PHP if statement not working - javascript

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"){

Related

Passing values from JS to PHP and Echo back HTML

I am studying a code and need help to learn further.
The JS code below is from a Q/A html form that sends data to server.
It crosschecks answer and on server and scores the user.
I need help writing a PHP code that receives the inputs using GET method and echo "ok" back to the html.
JS:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
if(this.responseText == "ok") {
document.getElementById("messagefont").innerHTML = checkans;
document.getElementById("answer").value = "";
document.getElementById('submit-btn').value = continuebutton;
checkans.focus();
PHP:
<?php
header('Content-Type: application/json');
$errors = array ();
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' );
if (isset ($_GET['answer'])) {
$answer = $_GET["answer"];
}
else {
array_push ($errors, no);
}
$response = "";
if (sizeof ($errors) > 0) {
$response = implode (",", $errors);
}
else {
$response = ok;
}
echo json_encode($response);
?>
I seem not to be getting something right with the PHP, please i need assistance/guide to fix the PHP code rightly.

echo is adding a new line to what i output in PHP

I am sending echoing some data to be received in Javascript however when i debug it, it seems that a new line has been added.
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
require './connection.php';
$obj = json_decode($_POST["x"], false);
$usernamequery = "SELECT * FROM User WHERE username='$obj->newUser'";
$result = mysqli_query($db, $usernamequery);
$row = mysqli_fetch_assoc($result);
if($row["Username"] == null){
$updatequery = "UPDATE User SET User='$obj->newUser' WHERE username ='$obj->username'";
$result = mysqli_query($db, $updatequery);
echo "valid";
} else{
echo "invalid";
}
?>
JS
///// USERNAME
$(document).ready(function () {
$("#userSubmitForm").on("click", function(e) {
$username = document.getElementById("user").value;
$newUser = document.getElementById("newUser").value;
user = $newUser;
obj = { "username":$username, "newUser":$newUser};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "valid"){
$('#usernameModal .modal-header .modal-title').html("Result");
$('#usernameModal .modal-body').html("Your Username Has Been Changed to '$newUser'");
$("#passSubmitForm").remove();
$("#userCloseForm").remove();
window.setTimeout(redirect,3000);
} else{
$('#error').html("This Username Already Exists"); ;
}
}
};
What is happening is responseText will be receive "valid"/"Invalid" as "valid[newline]"/"invalid[newline]"
As stated at http://php.net/manual/en/function.echo.php that can't be a "problem" of the echo. There must be some newline-character after your -tags
A simple solution would be to just trim your response text like this: var validity = this.responseText.trim(); in order to strip it from unwanted space/tab/newline characters.

XMLHttpRequest doesn't work in asynchronus mode when my php code use DOMDocument::loadHTMLFile

I have a php script that return me a string after parsing a DOM from an html file.
parserFunctions.php (I just have displayed usefull functions):
<?php
function initPagesToParse($Path){
define('MESSAGES_BY_PAGE', 20);
$Docs[0] = new DOMDocument();
$Docs[0]->loadHTMLFile($Path);
$numberOfPages = getMessageNumber($Docs[0]) / MESSAGES_BY_PAGE;
if($numberOfPages > 1){
for($i = 1; $i < $numberOfPages; $i++){
$startPost = $i * MESSAGES_BY_PAGE;
$Docs[$startPost] = new DOMDocument();
$Docs[$startPost]->loadHTMLFile($Path . '&start=' . $i);
}
}
return $Docs;
}
function runParser($Path){
$Result = '';
foreach(initPagesToParse($Path) as $Doc) {
$Result = $Result . getVoteIDsFromDocument($Doc);
}
if($Result == ''){
return FALSE;
}
$FileID = uniqid('Vote_IDs_', TRUE);
if(file_put_contents ('VoteIDs_files/' . $FileID . '.txt', $Result, LOCK_EX) === FALSE){
return FALSE;
}
return $FileID;
}
?>
parserMain.php:
<?php
include 'parserFunctions.php';
error_log("Parsing \n");
if(!isset($_POST["URL"]) || $_POST["URL"] == null) {
echo 'REQ ERROR';
exit();
}
$url = $_POST["URL"];
if(($FileID = runParser($url)) === FALSE){
echo 'PARSING ERROR';
exit();
}
error_log($url);
error_log($FileID);
echo $FileID;
?>
And to get this string I have a html page with a javascript that use a XMLHttpRequest to get the result.
<script type="text/javascript">
"use strict";
function sendUrlToParser() {
var handleResponse = function (status, response) {
alert(response);
}
var handleStateChange = function () {
switch (xmlhttp.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
handleResponse(xmlhttp.status, xmlhttp.responseText);
break;
default: alert("error");
}
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = handleStateChange;
xmlhttp.open("POST", "parserMain.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("URL=" + document.getElementById("URL").value);
}
</script>
When I use this script to get the result of my php script, in asynchronus mode (true) I get a status == 0 and I get an empty response while in synchronus mode (false) I get a status == 200 and I can display my result.
After several test I have noticed that is only when I use the parser that my asynchronous request stops working. If the php script stops before the runParser (in case of non-existent variable for example) I can get an answer (REQ ERROR in this case).
Is my problem related to the use of DOMDocument::loadHTMLFile or is the problem elsewhere?
Problem solved by disabling page refresh after a request.
Adding a "return false;" in the "onsubmit" attribute.
<form method="POST" onsubmit="sendUrlToParser(); return false;">

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

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". :-)

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']);?

Categories

Resources