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']);?
Related
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;">
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.
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"){
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". :-)
What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];