How to use object generated from SQL Server to populate HTML elements? - javascript

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;
}

Related

Can't send data from JavaScript to PHP [duplicate]

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.

Send JSON data to MySQL database?

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.

Data not being sent via XMLHttpRequest

I have a weird issue with a script I am using to send some info to my PHP. I say weird because this code is a direct copy of some already working code on the same application, with new variable names. I need to upload a small amount of data to my server, and while the value is there and the code runs all the way through, the POST data is not being sent or something. I have checked, and it says it has been submitted to my PHP with the value but nothing happens. I am using Vue.js if there are questions about some of my formatting
I have tried looking at other examples online, but my thing is that this was a block of code that copied from a working part of my application. It works until the data transfer from JS -- PHP
JS
editDisplayName: function() {
var self = this;
var newName = prompt("10 Characters Max, 3 Min", "Enter Display Name");
if(newName.length <= 10 && newName.length >= 3 ) {
var sendData = new XMLHttpRequest();
sendData.open("POST", "primary.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(newName);
self.username = window.localStorage.getItem('username');
window.localStorage.clear();
}
}
PHP
function changeUsername() {
// Connect to Server
$link = // Commented Out For Security;
if (mysqli_connect_error()) {
die ("DB Connection Error");
}
$newName = $_POST['newName'];
$newName = mysqli_real_escape_string($link, $newName);
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET username = '$newName' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
mysqli_close($link);
echo("
<script>
var username = $newName;
window.localStorage.setItem('username', username);
</script>
");
}
if(isset($_POST['newName'])) {
changeUsername();
}
I'm expecting on my DOM that I would have the new username set, instead it is blank. The spot where stuff stops working is somewhere with the POST data being sent, since my PHP isn't picking anything up, but I can't figure out what is wrong.
Instead of just sending the value, you should send the parameter name as well.
So, instead of using sendData.send(newName);, try using:
sendData.send("newName=" + newName);
(as your Content-type is application/x-www-form-urlencoded)
Or if you want to use JSON:
Change your Content-type to application/json, then send the data as a JSON string, like so:
sendData.send(JSON.stringify({'newName': newName}));

how to access an array within a json php to javascript/jquery

I have this function in php
$everything= array($ary);
$response = (json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$everything)));
how can i access this using javascript/jquery.I have this at the moment.
javascript
websocket.onmessage = function(ev) {
received = JSON.parse(ev.data);
var everything = received.everything;
};
I am able to get all data except for the varible $everything how can I pass it from php and retrive it over in javascript.
try this :
$response = json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$ary));
It will work perfectly for you.
You need to use the index ex. received[0]
websocket.onmessage = function(ev) {
received = JSON.parse(ev.data);
var everything = received[0].everything;
document.write(everything);
};
a better way to do this is to use the implode function in php
to convert the arrays in to strings and then pass it
$everything= array($ary);
ConvertEverything = implode(' ',$everything);
$response = (json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$ConvertEverything )));
JavaScript
websocket.onmessage = function(ev) {
received = JSON.parse(ev.data);
var everything = received.everything;
};
<?php
header('Content-Type: application/json');
$everything= array($ary);
$response = (json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$everything)));
?>
<script>
websocket.onmessage = function(ev) {
var code = ev.data;
var id= ev.id;
var usr = ev.usr;
};
</script>

How do php contact and pull information from a server

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;
}
})();

Categories

Resources