I'm having trouble understanding with my code on how the php is actually communicate the server and pull information from the files. Because I don't really see where the full url is coming from. I'm very new to php so I'm at a loss. The code is displaying information from http://webster.cs.washington.edu/cse154/services/flashcards
but I don't really see where it goes about, specifically accessing those pathways, I don't see how to get information to create the new json and xmls. Like if I wanted to pull a txt file, let's say a made up website: http://jackson.hubert.com/coolstuff and coolstuff has the txt file how is this code getting that info? Sorry if this is a really stupid question
<?php
# Solution to CSE 154 Flashcard lab.
# generates a JSON list of categories if passed a parameter mode
# with the value of categories. Otherwise outputs a random question
# from the passed in category in XML.
$mode = $_GET["mode"];
$category = $_GET["category"];
$url = "../../cse154/services/flashcards/";
if($mode == "categories") {
outputJson($url);
} else {
outputXml($url, $category);
}
# outputs the list of available categories in JSON
function outputJson($url) {
$files = glob($url . "*");
$json = array("categories" => array());
foreach($files as $file) {
$count = count(glob($file."/*"));
$json["categories"][basename($file)] = $count;
}
header("Content-type: application/json");
print(json_encode($json));
}
# outputs a random question about the provided category in XML
function outputXml($url, $category) {
$files = glob($url . "$category/*");
$index = array_rand($files);
// this is a great place to use list!!
list($ques, $ans) = file($files[$index]);
$dom = new DOMDocument();
$card = $dom->createElement("card");
$dom->appendChild($card);
$question = $dom->createElement("question");
$question->appendChild($dom->createTextNode($ques));
$card->appendChild($question);
$answer = $dom->createElement("answer");
$answer->appendChild($dom->createTextNode($ans));
$card->appendChild($answer);
header("Content-type: text/xml");
print($dom->saveXML());
}
?>
/* javascript */
(function() {
var category = "computerscience";
var xml = null;
// sets up onclick handlers
window.onload = function() {
document.getElementById("viewAll").onclick = viewAll;
document.getElementById("next").onclick = next;
};
// sends an ajax request to the passed in address.
// calls the passed in function when the request returns.
function ajax($adress, $function) {
var request = new XMLHttpRequest();
request.onload = $function;
request.open("GET", $adress, true);
request.send();
}
// makes a request for all of the categories.
function viewAll() {
ajax("flashcards.php?mode=categories", displayAll);
}
// displays all categories in a list on the page.
function displayAll() {
$json = JSON.parse(this.responseText);
for($cat in $json.categories) {
var li = document.createElement("li");
li.innerHTML = $cat;
li.onclick = choose;
document.getElementById("categories").appendChild(li);
}
}
// sets a new category as the category all questions should come from.
function choose() {
category = this.innerHTML;
}
// displays the next question if it was last displaying an answer or nothing.
// displays the answer to the previous question otherwise.
function next() {
if(!xml) {
ajax("flashcards.php?category=" + category, displayNext);
} else {
document.getElementById("card").innerHTML = xml.querySelector("answer").textContent;
xml = null;
}
}
// displays the question that it recieved from the server.
function displayNext() {
xml = this.responseXML;
document.getElementById("card").innerHTML = xml.querySelector("question").textContent;
}
})();
Related
In my SQL query PHP I have:
<?php
$mstr_ID = $_GET['MF_ID'];
$sql = "select hospital, patient_id from masterfileaccess where masterfile_id = " . $mstr_ID . "FOR JSON PATH";
$patLookup = sqlsrv_query($conn,$sql);
$row = sqlsrv_fetch_array($patLookup, SQLSRV_FETCH_ASSOC);
echo json_encode($row);
sqlsrv_free_stmt($patLookup);
sqlsrv_close($conn);
?>
In my JavaScript function I have:
function chooseThisPatient(id,name){
const mstrID = name.substring(2);
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const res = JSON.parse(xhttp.responseText);
alert(res)
// what do I do here to access the JSON file?
}
let phpfile = "cardiac/phps/cardiacGetPatientData.php?MF_ID=" + mstrID;
xhttp.open("GET", phpfile);
xhttp.send();
}
When I run the select on SQL Management Studio, I get:
[{"hospital":"Good Hospital","patient_id":"12345678"}]
When I run chooseThisPatient() withOUT the JSON.parse, alert(res) gives me:
{"JSON_F52E2B61-18A1-11d1-B105-008-5F49916B":"[{\"hospital\":\"Good Hospital\",\"patient_id\":\"12345678\"}]"}
When I run chooseThisPatient() WITH the JSON.parse, alert(res) gives me: Object object
I have tried xhttp.responseXML, res[x] (where x is 0-10) - this gives me single characters '[','{','', etc. Have tried res.hospital (undefined), res['hospital'] (undefined), res.key, res.key(), res.key[0], res.keys, Object.keys(res), Object.keys(res[0], all without being able to see what the JSON is holding.
What I would LIKE to happen is to be able to put the object in a loop and update HTML elements, something like:
for( x in res){
const key = x.key;
const value = x[key];
document.getElementById(key).innerHTML = value;
}
This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 1 year ago.
I am trying to make a simple JavaScript game, and as a user, I will get a score.
I want to send this score to a PHP server, but in my case, I can't get this data in the PHP file.
Here my JavaScript code:
var obj = {
"note": 0,
};
obj.note = score;
console.log(obj.note)
var data, xml, txt = "", mydata;
data = JSON.stringify(obj.note);
xml = new XMLHttpRequest();
xml.onreadystatechange = function() {
if (this.readystate == 4 && this.status == 200) {
mydata = JSON.parse(this.responseText);
for (x in mydata) {
txt += mydata[x];
}
// document.getElementsByClassName("pEl").innerHTML = txt;
}
};
xml.open("POST", "getnote.php", true);
console.log("true");
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.send("x=" + data);
Here my PHP code:
<?php
// Takes raw data from the request
$json = file_get_contents('application/x-www-form-urlencoded');
// Converts it into a PHP object
$data = json_decode($json);
echo $data
?>
Many people tried to help you, you used a valid sample which you linked, anyway still using the wrong code, which you modified with no reason and all you had to do was to follow suggestions from GeeksForGeeks page you linked.
Short
You can not use anything you want when you trying to access php://input stream (you used application/x-www-form-urlencoded, which is wrong, and I have no even idea why?)
Working, minified sample
test.html
<script>
let obj = {
"note": 123,
"foo": "bar"
};
let data, xml;
data = JSON.stringify(obj);
xml = new XMLHttpRequest();
xml.open("POST", "getnote.php", true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.send(data);
</script>
getnote.php
<?php
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
// print whole array decoded from JSON object
print_r($data);
// print single node of the array
echo "The sent note is: {$data['note']}";
echo "The sent foo is: {$data['foo']}";
// etc.
Please, read once again the article you linked, also read carefully the question linked by El Vanja to recognize what mistake you did.
Note: that should be just a comment, and probably will be flagged to delete, anyway I have no idea what else we can do if you don't want to read the simple comments that solve your problem and give you a detailed description.
I need to send JSON data to a MySQL database, but when I am trying to do this, my code only sends "{"0":"A" to the MySQL database.
Here is my code:
JavaScript
<span id="start_button_container">Send and start</span>
const allCards = {
'0':'A ♦','1':'A ♥','2':'A ♣','3':'A ♠',
'4':'10 ♦','5':'10 ♥','6':'10 ♣','7':'10 ♠',
'8':'K ♦','9':'K ♥','10':'K ♣','11':'K ♠',
'12':'Q ♦','13':'Q ♥','14':'Q ♣','15':'Q ♠',
'16':'J ♦','17':'J ♥','18':'J ♣','19':'J ♠'
};
let userInTable = localStorage.getItem( 'saved_user' );
if (userInTable) { // Save user and find table onclick START
saveUser.style.display = 'none';
hello.textContent = "Hi " + userInTable;
start.onclick = () => {
if (userInTable) {
let x = new XMLHttpRequest();
let url = "php/findtable.php";
let data = JSON.stringify(allCards);
let params = "cards="+data+"&user="+userInTable;
x.open("POST", url);
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.send(params);
x.onreadystatechange = () => {
if (x.readyState == 4 && x.status == 200) {
console.log(x.responseText);
}
}
}
}
}
Here is my PHP code:
if (isset($_POST["cards"],$_POST["user"])) {
$cards = $_POST["cards"];
$user = $_POST["user"];
$query = "INSERT INTO tables (u_1,all_cards) VALUES (?,?)";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("ss", $user, $cards);
if ($stmt->execute()) {
print_r($cards);
}
}
}
What am I doing wrong?
The encodeURIComponent() function helped me a lot:
let data = JSON.stringify(encodeURIComponent(allCards));
If you/somebody still want to know why this happens, every ampersand (&) is a new input in a querystring. Meaning var1=value&var2=value&var3=value. Your JSON contains ampersands, so the parser thinks you are starting a new variable.
var1=value&var2={"a":"&2934;"}
^ This one starts a new variable
var2 contains {"a":"1 and processes 2934;"} as a new variable name.
encodeURIComponent escapes the ampersands, so the query string parser does not use it for division of variables.
Basically, what I'm trying to do is send a request to a separate .php file which queries my database. The problem occurs when trying to return an array as a variable type array. I need this, because I want to send it to another PHP when it is send to the HTML. In the second PHP file, I want to use a for-each-loop-statement in order to create some code, but this only takes arrays and not strings. I've tried a couple of things including the use of JSON in an attempt to fix this, but on return the array keeps turning into a string. Any help would be appreciated. Most relevant code is included below:
javascript:
function getEvents(){ //gets the events from the database
var req = new XMLHttpRequest();
var att = 1; //Just a filler because somehow this seems needed
var link = "IekjeConnector.php";
dataType:"json";
req.onreadystatechange = function() {
if(req.readyState === 4 && req.status === 200)
{
addEvents(JSON.parse(this.responseText)); //This should be a normal array
}
}
req.open("GET", link + "?att=" + att, true);
req.send();
}
function addEvents(events = ""){
var req = new XMLHttpRequest();
var link = "IekjeHome.php"; //sends to the next php
req.onreadystatechange = function() {
if(req.readyState === 4 && req.status === 200)
{ document.getElementById("event").innerHTML = this.responseText; }
}
req.open("GET", link + "?events=" + events, true); //events has the right value
req.send();
}
php:
if (filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING)) {
$events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
$length = count($events);
print_r(gettype($events));
foreach($events as $event)
{ echo $events[$count] . $events[$count+2]; }
}
The foreach returns an error that $events is a string as does the gettype().
I tried changing the way addEvents and the php-code receive the array, but i'm probably doing something wrong trying.
I think you need to change the string to array, for example using explode.
$events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
$events = explode(",",$events);
Instead of the ",", just put your event's separator.
I believe what you're looking for is JSON.parse(this.responseText).
The following code should check if either a # or # symbol has been found in a string. The regex should find each and every # or # (kind of like Twitter does)and should either place each instance it found into the messages table (if it was an # symbol), or if it was a # symbol it should insert the instance into the hashtags table or update an existing record if the hashtag is already in the table.
Currently, the script itself works fine, but when using the code with javascript through AJAX, the console responds by saying the requested entity (this script) is too large (or something of that caliber). I'd assume its getting stuck in an endless loop, but so far I haven't found a (working) better way to do this. So, what would be a better way of coding this?
if (preg_match_all("/[#]+[A-Za-z0-9-_]+/i", $post, $matches)) {
for ($i = 0;$i <= $matches;$i++) {
$match = str_replace("#", "", $matches[$i]);
foreach($match as $key=>$mVal) {
$uMSQL = "INSERT INTO `messages` (`to`, `from`, `message`, `sent`) VALUES (:to, :from, '<p>tagged you in a post</p>', NOW())";
$uMQ = $con->prepare($uMSQL);
$uMQ->bindParam(':from', $author, PDO::PARAM_STR);
$uMQ->bindParam(':to', $mVal, PDO::PARAM_STR);
$uMQ->execute();
}
}
}
if (preg_match_all("/[#]+[A-Za-z0-9-_]+/i", $post, $hashtags)) {
for ($h = 0; $h <= $hashtags; $h++) {
$htMatched = $hashtags[$h];
foreach($htMatched as $key=>$htVal) {
$htCheck = "SELECT COUNT(hashtag) FROM `hashtags` WHERE `hashtag` = '$htVal'";
$htQ = $con->query($htCheck);
$htExistence = $htQ->fetchColumn();
if ($htExistence >= 1) {
$addTU = "UPDATE `hashtags` SET `used` = used+1 WHERE `hashtag` = '$htVal'";
$updateHT = $con->exec($addTU);
} else {
$htMSQL = "INSERT INTO `hashtags` (`hashtag`) VALUES (:hashtag)";
$htMQ = $con->prepare($htMSQL);
$htMQ->bindParam(':hashtag', $htVal, PDO::PARAM_STR);
$htMQ->execute();
}
}
}
}
AJAX
function sendData() {
var hr = new XMLHttpRequest();
var url = "http://localhost/NextIt/ajax/sendPost.php";
var txtField = window.frames['richTextField'].document.body.innerHTML;
var access = document.getElementById('postTo').selectedIndex;
var acc = document.getElementById('postTo').options;
var accss = acc[access].text;
var vars = "post="+txtField+"&access="+accss;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState === 4 && hr.status === 200) {
var return_data = hr.responseText;
$('status').innerHTML = return_data;
window.frames['richTextField'].document.body.innerHTML = '';
}
}
hr.send(vars);
$('status').innerHTML = "Posting...";
}
The post_max_size is 8M.