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

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>

Related

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

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

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

encryption in PHP and decryption in node.js

I've tried suggestions and tricks by reading various answers on stack overflow but they don't seem to be sufficient or maybe there's something basic i'm missing. Basically i'm trying to encrypt a value in php and pass it to the webpage from where it's read by JavaScript and send to node server for processing. But i'm unable to get the same value back on node server which i encrypted in php.
Below is the php code and php version is 5.5.12 running on windows 7 64 bit:-
function encrypt($string){
$key = hash("SHA256", '1d417e2ffb2a00a3', true);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $blockSize - (strlen($string) % $blockSize);
$string .= str_repeat(chr($padding), $padding);
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,$string, MCRYPT_MODE_CBC, $iv);
$result['cipher'] = base64_encode($ciphertext);
$result['iv'] = base64_encode($iv);
return $result;
}
My node.js version is 0.10.31 running on windows 7 64 bit and code is below:-
var express = require("express");
var Server = require("http").Server;
var cookie = require("cookie");
var app = express();
var server = Server(app);
var sio = require("socket.io")(server);
var crypto = require('crypto');
sio.sockets.on("connection", function(socket) {
try{
socket.on('incoming_data', function(data){
var txt = new Buffer(data.encrypted_text,'base64');
var key = new Buffer('1d417e2ffb2a00a3','utf8');
var iv = new Buffer(data.iv,'base64');
var decipher = crypto.createDecipheriv('aes-128-cbc',key,iv);
var chunks = [];
chunks.push(decipher.update(txt,'hex','binary'));
chunks.push(decipher.final('binary'));
var fuid = chunks.join('');
console.log(fuid);
});
}catch(e){
console.log("err:-"+e);
console.log(e);
}
});// on connection ends
server.listen(9267, function(){
console.log('Node server listening on *:9267');
});
process.on('uncaughtException', function(err) {
console.log("FATAL: "+new Date().getTime()+": "+err);
});
The error i get from printing fuid in nodejs console is as below:-
FATAL: 1414483246855: TypeError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
I am looking for solutions to the following in the answers:-
1) Problems with my code and what needs to be fixed to get back the same value on node server as a string.
2) Would like to concatenate the encrypted text and the iv and send them both as a single base64 encoded string to the server. So would like the code that will be needed to separate them back on node server ready to be passed to the crypto module.
3) This code seems vulnerable to oracle padding attacks. It will be great if you can suggest how can i make it secure.
Thanks
The problem might be with your encoding:
chunks.push(decipher.update(txt,'hex','binary'));
hex looks strange, since your inputs are buffers, not strings.
The following quick test works (also answers 2.):
php:
$key = 'secretsecretsecr';
$string = 'attack at dawn';
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $blockSize - (strlen($string) % $blockSize);
$string .= str_repeat(chr($padding), $padding);
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,$string, MCRYPT_MODE_CBC, $iv);
$packet = chr($iv_size) . $iv . $ciphertext;
print base64_encode($packet);
node:
var crypto = require('crypto');
var key = 'secretsecretsecr';
var data = 'paste what the php code printed';
var txt = new Buffer(data,'base64');
var iv_size = txt[0];
var iv = txt.slice(1, iv_size + 1);
var ct = txt.slice(iv_size + 1);
var decipher = crypto.createDecipheriv('aes-128-cbc',key,iv);
var chunks = [];
chunks.push(decipher.update(ct));
chunks.push(decipher.final());
console.log(chunks.join(''));
The passes the iv size along, you can also simply hardcode it on the node side.
Regarding 3), I am by no means an expert, from what I've read the workaround is to sign your encrypted packets with HMAC to make sure they're coming from your application and not from the "oracle" (http://www.ietf.org/id/draft-mcgrew-aead-aes-cbc-hmac-sha2-05.txt).

Why is db.transaction not working with indexeddb?

I am new at using inxededdb and am trying to get data out of a store. The store contains data, but for some reason the code stops after trying to set the var tx. If I am missing anything please let me know. Here is the function with which I am trying to get the book:
function getBook(){
var tx = db.transaction("book", "readonly");
var store = tx.objectStore("book");
var index = store.index("by_getid");
var request = index.get("<?php echo $_GET['book'] ?>");
request.onsuccess = function() {
var matching = request.result;
if (matching !== undefined) {
document.getElementById("text-container").innerHTML = matching.text;
} else {
alert('no match');
report(null);
}
};
}
Solved Version:
function getBook(){
var db;
var request = indexedDB.open("library", 1);
request.onsuccess = function (evt) {
db = request.result;
var transaction = db.transaction(["book"]);
var objectStore = transaction.objectStore("book");
var requesttrans = objectStore.get(<?php echo $_GET['book'] ?>);
requesttrans.onerror = function(event) {
};
requesttrans.onsuccess = function(event) {
alert(requesttrans.result.text);
};
};
}
The problem is probably your db variable. You are probably accessing a closed or null instance of a connection object.
Try instead to create the db connection right inside the function. Do NOT use a global db variable.
index.get yields primary key. You have to get record value using the resulting primary key.
I has problem with transaction, it's return error db.transaction is not a function or return undefined.
You will try like this, it's working for me:
const table = transaction.objectStore('list');
const query = table.getAll();
query.onsuccess = () => {
const list = query?.result;
console.log(list);
};

TypeError from Google Closure compiled file

I have a Javascript file compiled with the Google Closure compiler that gives me this error TypeError: f is undefined. When I look at the compiled code it's impossible to understand but a chunk of it is commented out. I'm really stumped on why I'm getting this error but I suspect it has something to do with the following script (which is the only thing I've edited since getting this error).
var response;
var request = new goog.net.XhrIo();
goog.events.listen(request, "complete", function(){
if (request.isSuccess()) {
response = request.getResponseText();
console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
} else {
console.log(
"Something went wrong in the ajax call. Error code: ", request.getLastErrorCode(),
" - message: ", request.getLastError()
);
}
});
request.send("load_vocab.php");
var rawVocab = response[rawVocab];
var optionVocab = response[optionVocab];
alert(rawVocab.length);
alert(optionVocab.length);
Here's also load_vocab.php...
try {
$conn = new PDO('mysql:host=localhost;dbname=tygrif_school', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT word, translation, example_sentence_1 FROM vocabulary_game WHERE game_type = :game_type');
$stmt->execute(array('game_type' => 'target'));
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$data['rawVocab'][] = $row;
}
$stmt = $conn->prepare('SELECT word, translation FROM vocabulary_game');
$stmt->execute(array());
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$data['optionVocab'][] = $row;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($data);
You do know that xhr requests are asynchronous?
This means that when you call send you have to wait for the response to return, what you do is try to read the response on the next line. Your quoting is a problem too, the compiler will rename rawVocab and optionVocab but the returned data will not be renamed so you need to quote these values as ne8il pointed out.
var response;
var request = new goog.net.XhrIo();
goog.events.listen(request, "complete", function(){
if (request.isSuccess()) {
window['console'].log("Now the response returned, setting response variable");
response = request.getResponseText();
console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
} else {
console.log(
"Something went wrong in the ajax call. Error code: ", request.getLastErrorCode(),
" - message: ", request.getLastError()
);
}
});
window['console'].log("Sending request");
request.send("load_vocab.php");
window['console'].log("Trying to read response");
var rawVocab = response['rawVocab'];
var optionVocab = response['optionVocab'];
The output of the above code would be:
Sending request
Trying to read response
Error
Now the response returned, setting response variable
I think the problem is here :
var rawVocab = response[rawVocab];
var optionVocab = response[optionVocab];
You are not quoting your property accessors properly. Try this :
var rawVocab = response['rawVocab'];
var optionVocab = response['optionVocab'];

Categories

Resources