Send JSON data to MySQL database? - javascript

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.

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

Return multiple values from stored procedure

The idea is that each subject has multiple topics, and when I call the function getTopicsForSubject() in order to get this data to a website page, it returns only 1 of the records from the table. I'm testing this using console.log(response) in the JavaScript file to see what is being passed in from the stored procedure/api connection. I'm thinking I need to read what's being passed by the stored procedure as if it were an array, although I'm not too sure how this is done.
Stored Procedure:
USE [Capstone]
GO
/****** Object: StoredProcedure [dbo].[getTopicsForSubject] Script Date: 2/21/2021 11:30:03 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getTopicsForSubject]
#SubjectID int
AS
BEGIN
select *
from Topic
where SubjectID = #SubjectID
return;
END
API Code
private static string ExecuteSPGetSubjectsForTopic(string queryString, string subjectID)
{
string json = "";
string connectionString = ConfigurationManager.AppSettings["dbconn"].ToString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand(queryString, conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#SubjectID", subjectID));
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// iterate through results, printing each to console
while (rdr.Read())
{
json = (string)rdr[0].ToString() + "|" + (string)rdr[1].ToString()+ "|" + (string)rdr[2].ToString() + "|" + (string)rdr[3].ToString();
}
}
}
return json;
}
JavaScript Code
function getTopicsForSubject()
{
var postObj = {
subjectID: localStorage.getItem('myFutureCurrentSubject')
};
console.log(postObj);
var req = new XMLHttpRequest();
req.open('POST', 'https://localhost:44303/api/JSON/getTopicsForSubject', true);
req.setRequestHeader('Content-Type', 'application/json');
req.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log(req.response);
}
}
req.send(JSON.stringify(postObj));
return false;
}
You're reinitializing your JSON variable each time when reading a row. Try this:
json += (string)rdr[0].ToString() + "|" + (string)rdr[1].ToString()+ "|" + (string)rdr[2].ToString() + "|" + (string)rdr[3].ToString();
This is not the right way to return data. In JS you will still get this as a string and then parse it like this to get the actual values:
var array = req.response.split('|');
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
I would suggest you use a proper way to handle this data by return an HTTP response from API instead of a string. E.g. create a list and then populate it while reading from the reader and return it. Try this:
List<object[]> topics = new List<object[]>();
while (rdr.Read())
{
object[] row = new object[rdr.FieldCount];
for (int i = 0; i < rdr.FieldCount; i++)
{
row[i] = rdr[i];
}
topics.Add(row);
}
return Ok(new { Data = topics });

Javascript using PHP to return an array

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

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

"Request page too large", Best way to refactor?

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.

Categories

Resources