I was wondering why my variable from my php page isn't saving to my .txt. I have posted the code below. All the variables match.
Everytime the new page refreshes, the message disappears and I've checked my txt file, the variables are not saved in an array as it should be.
function updateData() {
$.getJSON("#host/information.txt",
function(data) {
var senator = data[0];
var cmicrophone = data[1];
var microphone = data[2];
var words = data[3];
$("#java").text(senator + cmicrophone + microphone + words);}
);
}
<?php
session_start();
if(isset($_POST["senator"]) && isset($_POST["cmicrophone"]) && isset($_POST["microphone"]) && isset($_POST["words"])) { // If the page receives POST data, it needs to be stored
$senator = $_POST["senator"];
$cmicrophone = $_POST["cmicrophone"];
$microphone = $_POST["microphone"];
$words = $_POST["words"];
$data = json_encode(Array($senator, $cmicrophone, $microphone, $words)); // Put values into an array and encode it for storage
file_put_contents('information.txt', $data); // Put the JSON-encoded array into a text file. This function replaces the contents of the text file, which is exactly what is needed in this application. To append instead of replacing the contents, you need a FILE_APPEND flag.
} else { // If there's no POST data, the values are retrieved from the storage
$data = json_decode(file_get_contents('information.txt')); // Retrieve the contents of the text file and decode them back into an array
$senator = $data[0];
$cmicrophone = $data[1];
$microphone = $data[2];
$words = $data[3];
}
echo "". $senator. "" .$cmicrophone. "" .$microphone. "";
$wordformat = wordwrap($words, 32, "\n", false);
echo "".$words. "";
?>
If the code is correct, would it just be the
$.getJSON()
location isn't correct? The variables are all correct.
Related
pick a line depending on variable "number"
then save each of the words on that line into each javascript variable1 and javascript variable2.
if variable number equals 2, pick line 2, set Variables1 to potato ,and set Variables2 to tomato.
//Text file on server
Apple, Oranges
Potato, Tomato
Cake, Muffin
Cheese, Milk
//Java script code in browser.
var number = Math.floor((Math.random() * 4) + 1);
var xhr = new XMLHttpRequest();
xhr.open("GET","http://..........data.txt",false);
xhr.send(null);
What should I do next?
Any help is appreciated
Thanks in advance
You better off chosing random string via your backend server rather than js because servers meant to do that. You could create a page to which you will reffer to and pass path to your file as parameter and set it to return random line from that file. After you parsed that string you can use split() onto your parsed string to get an array of those words. Also you should consider using fetch 'cause it's a replacement for a XHR.
So my js code looks something like this:
function getTextFile(path){
var line = Math.floor(Math.random() * 4);
params = {
path: path,
line: line
}
var data = new FormData();
data.append("json", JSON.stringify(params));
var promise = fetch("http://mysite/myscript.php", {method: 'POST', body: data})
.then((response) => {
return response.text();
}).then((text) => {
if(text != 'error'){
text = text.replace(/(\r\n|\n|\r)/gm, "");
var result = text.split(" ");
//Result will be an array of those values and will look something like that:
//["Cheese", "Milk", "Yogurt"]
}
else{
alert('error');
}
});
}
And then on a backend it looks like that:
$json = (array) json_decode($_POST['json']);
if( validatePath($json['path']) ){
$file = file($json['path']);
$my_string = $file[$json['line']];
echo $my_string;
}
else{
echo 'error';
}
function validatePath($path){
//You should definitely use some other validations
$allowedExtensions = ['txt', 'json'];
$pathinfo = pathinfo($path);
//Right now it's only checking for right extension and
//that's this file ain't located in admin subdir
if(strstr($pathino['dirname'], '/admin') || !in_array($pathinfo['extension'], $allowedExtensions)){
return false;
}
else{
//Check if file exists
if( file_exists($path) ){
return true;
}
else{
return false;
}
}
}
Although not every browser supports fetch and if you want to support more browsers you'll need polyfill.
I'm trying to write a php and javascript code that's going to behave similarly to the code I have below (I didn't write the code) but I'm a little confused on what's going on in the php and how the two are communicating. I've tried to watch videos and read about php but I'm still pretty confused by it.
Then the javascript makes requests to the php when its buttons are clicked and the php sends information back.
The general function of the php file is it displays the contents of a random file in the http://webster.cs.washington.edu/cse154/services/flashcards/pokemon directory. It can take in a parameter called mode. When the user passes in a mode value of categories it outputs a list of all of the folder names in http://webster.cs.washington.edu/cse154/services/flashcards. Otherwise, it just displays the contents of a random file as before.
I get it on a broad overview but I'm still kind of confused on how the php code is working. Like I said I'm trying to write a code that's going to be quite similar to this so I just am trying to get a better understanding of how php works but all the information i've read hasn't been that helpful.
<?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;
}
})();
I am having problems passing my javascript array to a php file. i know that the JS array has the correct users input data because I have tested this by using toString() and printing the array on my web page. My plan was to use send the JS array to my php script using AJAX's but I am new to using AJAX's so there is a good chance I am doing something wrong. I have look through a good lot of different posts of people having this same problem but everything i have tried has not worked so far. All I know at this point is the JS has data in the array fine but when I try to pass it to the php file via AJAX's the php script dose not receive it. i know this because I keep getting undefined variable errors. To be fully honest I'm not to sure if the problem in how I'm trying to pass the array to the php script or if it how I'm trying to request and assign the array values to variables on the php side. At the moment my code is as follows:
My Javascript:
function createAsset(str, str, str, str, str, str, str, str, str)
{
var aID = assetID.value;
var aName = assetName.value;
var pPrice = purchasedPrice.value;
var pDate = purchasedDate.value;
var supp = supplier.value;
var cValue = currentValue.value;
var aOwner = actualOwner.value;
var wEdate = warrantyExpiryDate.value;
var dDate = destroyedDate.value;
//document.write(aID);
//var dataObject = new Array()
//dataObject[0] = aID;
//dataObject[1] = aName;
//dataObject[2] = pPrice;
//dataObject[3] = pDate;
//dataObject[4] = supp;
//dataObject[5] = cValue;
//dataObject[6] = aOwner;
//dataObject[7] = wEdate;
//dataObject[8] = dDate;
//dataObject.toString();
//document.getElementById("demo").innerHTML = dataObject;
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
$.ajax
({
type: "POST",
url: "create_asset_v1.0.php",
data: dataObject,
cache: false,
success: function()
{
alert("OK");
location.reload(true);
//window.location = 'create_asset_v1.0.php';
}
});
}
My PHP:
<?php
// Get Create form values and assign them to local variables.
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
// Connect to the SQL server.
$server='PC028\ZIRCONASSETS'; //serverName\instanceName
$connectinfo=array("Database"=>"zirconAssetsDB");
$conn=sqlsrv_connect($server,$connectinfo);
if($conn)
{
echo "Connection established.<br/><br/>";
}
else
{
echo "Connection couldn't be established.<br/><br/>";
die(print_r( sqlsrv_errors(), true));
}
// Query the database to INSERT record.
$sql = "INSERT INTO dbo.inHouseAssets
(Asset_ID, Asset_Name, Perchased_Price, Date_Perchased, Supplier, Current_Value, Actual_Owner,Worranty_Expiry_Date, Destroyed_Date)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = array($assetID, $assetName, $purchasedPrice, $purchasedDate, $supplier, $currentValue, $actualOwner, $warrantyExpiryDate, $destroyedDate);
// Do not send query database if one or more field have no value.
if($assetID && $assetName && $purchasedPrice && $purchasedDate && $supplier && $currentValue && $actualOwner && $warrantyExpiryDate && $destroyedDate != '')
{
$result = sqlsrv_query( $conn, $sql, $params);
// Check if query was executed with no errors.
if( $result === false )
{
// If errors occurred print out SQL console data.
if( ($errors = sqlsrv_errors() ) != null)
{
foreach( $errors as $error )
{
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br/>";
echo "code: ".$error[ 'code']."<br/>";
echo "message: ".$error[ 'message']."<br/>";
}
}
}
else
{
echo "Record Created!<br/>";
}
}
// Close server connection
sqlsrv_close( $conn );
if($conn)
{
echo "<br/>Connection still established.";
}
else
{
echo "<br/>Connection closed.";
}?>
Just as extra info if its not obvious from my code I am trying to send user data from a html form to a php script that process it and uses it to query a MSSQL database. This function that I am working on now is the create database entry function.
You need to match the keys you send through AJAX:
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
with the POST array keys:
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
Your code should look like this:
$assetID = $_POST['assitID'];
$assetName = $_POST['assitName'];
$purchasedPrice = $_POST['purchasedPrice'];
...
You are reading the wrong keys.
$assetID = $_POST['aID'];
Must be:
$assetID = $_POST['assitID'];
As per your sent object.
I have a variable stored username and I wish to pass this through a link to the next page. So I have:
Go!
When you land on register-form.php there is an onload event for the script:
<body onload="inputUsername()">
function inputUsername(){
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
}
However I get an undefined variable error for username.
It seems to me that the URL is not passing the variable correctly. Should I be seeing my actual variable in the address line? Should I be seeing username=myusernameisthis ?
In essence, all I'm after is passing the variable username from page 1 to page 2. That's all.
Parameters passed in a url query string don't get magically loaded into the javascript global scope.
As #Archios says you can parse the query string with javascript with something like:
var username = getUrlVars()["username"];
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
but personally I prefer:
function inputUsername(){
var username= "<?php echo isset($_GET[username])?$_GET[username]:''; ?>";
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
}
what would be even easier, is if you changed:
<input id="inputUsername" type="text" name="username">
to
<input id="inputUsername" type="text" name="username" value="<?php echo $_GET[username]">
and remove the onload event.
the href on the previous page should look something like:
Go!
assuming $username holds the current username
where your script says
username = wordOne + wordTwo + wordThree;
add the line
$('.userNameButton a').attr('href','register-form.php?username='+username);
I think You are trying to get query string variable to javascript not to php. Try something like:
Get query string parameter to js
You are getting an undefined variable error because you have not set the js variable 'username' anywhere. Setting this in the URL is NOT the same as defining a variable.
If you are setting the URL correctly you shouls see something like 'register-form.php?username=Francesca'
You can do this with a mix of PHP and javascript.
In your register-form.php:
register-form.php:
if(isset($_GET["username"])) {
$username = $_GET["username"];
} else {
$username = "not set";
}
in your js (this is better than calling <body onload="inputUsername()">):
window.onload=function(){
var username = <?php echo $username ?>
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
};
Better yet would be to not use js at all and do this all in PHP:
<?php
if(isset($_GET["username"])) {
$username = $_GET["username"];
} else {
$username = "not set";
}
?>
<input name="username" id="username" type="text" value="<?php echo $username ?>">
Here ya go. I commented the code so it makes more sense hopefully. Basically, we get the url from the address bar and parse out the pieces one by one to get what we want.
window.ParseQueryString = function () {
//Get the current location in the address bar
var url = window.location.href,
parameterSet = [],
//Get everything to the right of the '?'
parameterString = url.split('?')[1];
//Do we have anything to work with?
if (parameterString) {
//Lets get all individual parameter in the parameter string
var parameterParts = parameterString.split('&');
for (var i = 0, e; e = parameterParts[i++];) {
//Get the parameter key and the value
var parameter = e.split('=');
//Push it into the array
parameterSet.push({
'key': parameter[0],
'value': parameter[1]
});
}
}
//Give me my prettyfied query string array plz!
return parameterSet;
}
console.log(ParseQueryString());
Using this code with a window location of http://www.home.com?s=search&f=images will yield:
[{ key: 's', value: 'search'}, {key: 'f', value: 'images'}]
With this, in your onload callback, you can call the ParseQueryString and look through it to find the username value and populate it to textbox.
Edit
I am added a function that instead of returning an array of key/value pairs, it will return an object with the query string keys as the fields on the object.
window.ParseQueryString = function () {
//Get the current location in the address bar
var url = window.location.href,
parameterSet = {},
//Get everything to the right of the '?'
parameterString = url.split('?')[1];
//Do we have anything to work with?
if (parameterString) {
//Lets get all individual parameter in the parameter string
var parameterParts = parameterString.split('&');
for (var i = 0, e; e = parameterParts[i++];) {
//Get the parameter key and the value
var parameter = e.split('=');
//Add a new field to the object
parameterSet[parameter[0]] = parameter[1];
}
}
//Give me my prettyfied query string array plz!
return parameterSet;
}
Here is a fiddler demonstrating your specific use case. Please note that the fiddler is appending a query string to the url as fiddler wouldn't allow it otherwise. This occurs on line 3
I want to send an array with image strings to my php action. This is what I do so far:
$('#savepdf').click(function() {
var imagesarray = new Array();
var count = 4;
var quizid = <?php echo json_encode($quizid); ?>;
for (var i=0; i<count; i++)
{
var chart = Highcharts.charts[i];
var canvasname;
if(i == 0){
canvasname = "canvas";
}
else{
canvasname = "canvas" + i;
}
// get highcharts
canvg(document.getElementById(canvasname), chart.getSVG())
var canvas = document.getElementById(canvasname);
var img = canvas.toDataURL("image/png");
imagesarray[i] = img;
}
imagesarray = JSON.stringify(imagesarray);
// AJAX CALL TO ACTION
$.download('/results/savepdf','quizid=' + quizid + '&image=' + imagesarray);
});
The array that I send looks like this:
["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…197b1kPfJ5y3guHO4WLEyAAAECBAgcEFjz7y+zZJ6ttf8GC0YA4ro/bucAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…9v2cl0YeqeBTqMAAIIIIAAAgMINO3aT3a+sfNxGIa7fwBwOTGmIk2OYgAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…xdLNBhIkAEiAARIAJEIA8I7FRlf1T/XlD/hhcoUOCv/we6Hn4A9659wwAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…BdGOlYwAkjASSABJAAEkACBgm8UI89qf6sUX9GRIkS5cr/AFfL9D3Dad7CAAAAAElFTkSuQmCC"]
In my PHP action I do the following:
if(isset($_POST['quizid']))
$quizid = $_POST['quizid'];
if(isset($_POST['image']))
$image = $_POST['image'];
var_dump(json_decode($image));
The dump just shows "NULL". When I do this :
var_dump($image);
I just get : string(1) "["
Try to:
imagesarray = encodeURIComponent( JSON.stringify(imagesarray) );
UPDATE
and in php use
$image = json_decode(urldecode($_POST['image']));
I'm not familiar with the $.download method. Presumably it is an AJAX extension that allows for file downloads. I can guess how it probably works.
The problem is that you are not sending a valid HTTP request. JSON needs to be escaped to be sent over HTTP. You could do this yourself using encodeURIComponent, or you could let jQuery's $.param method handle it for you.
var data = $.param({
quizid: quizid,
image: imagesarray
});
$.download('/results/savepdf', data);