Does not add data to json file - javascript

I have red a lot of posts about how to add data to json file and I tried to put it all together and use for my situation, but it's not working. Basically what I do is get data from html file with javascript, then use XMLHttp request to send that data to php file and from php file I am trying to add the data to .json file. Anywho, it is not adding it and I don't know why and where is the problem.
My question is about the XMLHttp request. Is it correct? Why not?
And about php file. If the problem is in XMLHttp request, would the php file add the data to .json file? I am just trying to get anything in the json file, so i could start thinking about algorithms for making it viable. XMLHttp request is pretty new thing for me. For understanding, here is my code:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Project</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/style_mob.css" type="text/css" rel="stylesheet">
<script src="script/jquery.js"></script>
<script src="script/sendData.js"></script>
</head>
<body>
<div id="top">
<h1>Click only in case of an emergency!</h1>
</div>
<div id="divButtons">
<button class="button" id="polizei">Polizei</button>
<button class="button" id="feuerwehr">Feuerwehr</button>
<button class="button" id="krankenwagen">Krankenwagen</button>
</div>
</body>
</html>
sendData.js:
$( document ).ready(function() {
var type;
var latitude;
var longitude;
var currentdate = new Date();
$(".button").click(function(){
type = $(this).attr("id");
var dateTime = "Date: " + currentdate.getDay() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " time - "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(sendData);
} else {
alert("Geolocation is not supported by this browser.");
}
function sendData(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
var hr = new XMLHttpRequest();
hr.open("POST", "emergencyData.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert("about to send data to php file");
hr.send("type="+type+"&latitude="+latitude+"&longitude="+longitude+"$dateTime="+currentdate+"");
});
});
emergencyData.php:
<?php
header("Content-Type: application/json");
$type = $_POST["type"];
$latit = $_POST["latitude"];
$longit = $_POST["longitude"];
$dateTime = $_POST["dateTime"];
echo $type;
// Loading existing data:
$json = file_get_contents("emergencyData.json");
$data = json_decode($json, true);
// Adding new data:
$data[0] = array('type' => $type, 'latitude' => $latit, 'longitude' => $longit, 'date' => $dateTime);
// Writing modified data:
file_put_contents('emergencyData.json', json_encode($data, JSON_FORCE_OBJECT));
?>

You have a typo in javascript.
hr.send("type="+type+"&latitude="+latitude+"&longitude="+longitude+"$dateTime="+currentdate+"");
You have a $ at dateTime which should be &
Also I think you wanted &dateTime="+currentdate+"" to be &dateTime="+dateTime. Extra +"" is unnecessary.
And last thing, if you want to keep adding new data instead of overwriting old data, in PHP script use:
$data[] = array('type' => $type, 'latitude' => $latit, 'longitude' => $longit, 'date' => $dateTime);
Otherwise everytime the old JSON data will get replaced by new one.

Related

Getting undefined array key when passing data with XMLHttpRequest

I'm trying to pass a long formatted text string to a php process to save to a file. I am use the POST method as the string can be quite long. It seems to run thro the process and gives back the message 'File saved' but with the error message 'Undefined Array Key "data"' on line 2 of the php code. The file does not get saved and no data is being sent across from the XMLHttpRequest in the previous function.
My code is:- This gets 'str' from the previous function and is formatted correctly.
function getGame(str){
//Sends data to the php process "saveGame.php".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
it then goes the the 'saveGame.php' where the problem occurs on line 2.
<?php
$outputString = $_POST["data"];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
fwrite($fp, $outputString);
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
I think my code of the process is okay but there is a problem with passing the "data" variable and I not sure what it is.
I tested the file saving process. I put a dummy string as a value of 'outputString' and it saved it. When I went back and used the current code the file was overwritten and was blank, indicating it had saved a blank string. So it seems no data is been passed to saveTeams.php although the saving of the file works.
I have got a reproducible example below. If you use it with the saveTeams.php file and a file to attempt to save the data to it should display the error I get in an alert drop down.
<!DOCTYPE html>
<head>
<title>Test program</title>
<script language="javascript">
function formatOutput() {
// lots of formatting goes on here
var formattedText = "This is a test"; //test data
getGame(formattedText);
}
function getGame(str){
//Sends data to the php process "save Game".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
</script>
</head>
<body>
<table width="1000" align="center" border="0">
<br />
<tr>
<td width="500"align="center" colspan="3" <button onclick="formatOutput()"/>Click on me</td>
</tr>
</table>
</body>
</html>
Hope this okay. I'm a bit new to this.
You are missing a post key
try changing this line to
var data = 'data='+str;

Javascript output sent to PHP for adding into database

I have wrote a HTML/Javascript code generator but instead of outputting the code to a HTML site i would like the code to be send to php to be added to a database but i cant work out how to get the out put of the javascript into PHP
there is also another javascript doc to go with this if you need it to make it work ..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../voucher_codes.js"></script>
</head>
<body>
<h1>pattern codes</h1>
<ul id="pattern-codes"></ul>
<script>
var patternCodes = voucher_codes.generate({
prefix: "BREAK-",
postfix: "-2019",
length:5,
count: 5,
charset: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
});
function fillList(listId, items) {
var list = document.getElementById(listId);
items.forEach(function(item) {
list.innerHTML += "<li>" + item + "</li>";
});
}
fillList("pattern-codes", patternCodes);
</script>
</body>
</html>
i am wanting the output of the function "fillList" to send the output to PHP if this is possible....
You would have to look into using AJAX or the Axios library to send requests to a server page such as PHP.
Here is a simple AJAX POST server request in Javascript:
`
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
}
};
xhttp.open("POST", "request_page.php", true); // set method and page
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set content type that we are sending POST data
xhttp.send("key=VALUE&key=VALUE"); // POST values
}
</script>
`
On the PHP page if you want to give a response of data to use back in Javascript, make sure to
json_encode($array_values)
the data array before echoing it out and set the headers to
header("Content-Type: application/json")
so you can grab the response data in Javascript and it can be turned into a Javascript {Object} or [Array]

Javascript cannot process JSON text file

I am following some tutorial to pass a JSON text file from server to display the data after some javascript processing on a html file. As a test, try to display a LI of one column, but cannot get any output in the browser. Your help is appreciated.
I tried two approaches.
Approach 1 xmlhttp:
Apparently, the browser complain about the html format:
Uncaught SyntaxError: Unexpected string (15:08:42:080 | error, javascript)
at testJSON3.html:12
Is my xmlhttp call format correct?
Thank you for your help in advance.
Here's JSON text myTutorial.txt:
[
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name 1",
"eventDesc":"2015 class of course name 1"
},
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name21",
"eventDesc":"2015 class of course name "
}
]
And processed by the below html to process the xmlhttp access to the file on server localhost directory phpTWLLT
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost/phpTWLLT/myTutorial.txt";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<li'> + arr[i].courseCode +'</li><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Approach 2 getJSON():
This one is interesting. If the server side is static array ($DEBUG = true:), javascript is able to process and get browser display. But fail when generate the text from mysql ($DEBUG = false).
I am scratching my head to get the $DEBUG=false work? Apparently, both cases generated a valid JSON text.
If $DEBUG is set true,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"0","first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr#example.com"},{"active":"1","first_name":"John","last_name":"Doe","age":"47","email":"john_doe#example.com"}]
the list displayed in browser.
0
1
If $DEBUG is set false,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"1"},{"active":"1"}]
The browser display is blank.
html file:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<!--
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'> </script>
-->
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<!-- this UL will be populated with the data from the php array -->
<ul></ul>
<script type='text/javascript'>
$(document).ready(function () {
/* call the php that has the php array which is json_encoded */
//$.getJSON('json_encoded_array.php', function(data) {
$.getJSON('json_encoded_array.php', function (data) {
/* data will hold the php array as a javascript object */
$.each(data, function (key, val) {
$('ul').append('<li id="' + key + '">' + val.active + '</li>');
});
});
});
</script>
</body>
</html>
PHP script: json_encoded_array.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/* set out document type to text/javascript instead of text/html */
$DEBUG = true;
if ($DEBUG) {
header("Content-type: text/javascript");
$arr = array(
array(
"active" => "0",
"first_name" => "Darian",
"last_name" => "Brown",
"age" => "28",
"email" => "darianbr#example.com"
),
array(
"active" => "1",
"first_name" => "John",
"last_name" => "Doe",
"age" => "47",
"email" => "john_doe#example.com"
)
);
} else {
require_once('connection.php');
// $m_id= 8 has many enrolled course and 11 got exactly one course enrolled.
$m_id = 8;
$p_id = 1;
$qry1 = "SELECT distinct event.active as active, subject.code as 'courseCode', subject.name as 'courseName', event.event_desc as 'eventDesc' FROM applicant, event, subject, part where applicant.applicant_id = $m_id and applicant.event_id = event.id and event.subject_id=subject.id and part.id = subject.owner_id and part.id = $p_id order by event.active DESC, event.from_month DESC ";
mysqli_set_charset($bd, 'utf-8');
$result = mysqli_query($bd, $qry1);
$arr = array();
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ( $rs = mysqli_fetch_assoc($result) ) {
$colhead = "active";
$str = $rs['active'];
$arr[$i] = array($colhead => $str);
$i++;
// just generate two record for testing
if ($i === 2)
break;
}
}
}
echo json_encode($arr);
?>
For approach 2, did you try debugging the javascript code to check if the data variable contains the expected data?
You could also check the network tab to see if the response data sent from your server is correct.

change a php variable using POST

trying to change a php variable via js and echo back but its not working, been on it for days!!
I have a function handleServerResponse() called below, that alerts connection status, and getting the ok at status 200 so cant understand why my php variabe is not changing! driving me insane!
function process() // send the info to the server
{
if(xmlHttp)
{
try
{
xmlHttp.open("GET","myFile.php?phpvar="+jsvar,true);
xmlHttp.onreadystatechange = handleServerResponse; //alerts connection status = all ok
xmlHttp.send(null);
}
catch(e)
{
alert(e.toString());
}
}
}
// server side script
<?php
echo '<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>';
$phpvar;
$phpvar = $_GET['phpvar'];
echo "new phpvar value = ".$phpvar;
?>
Any help at all would be greatly appreciated.
Cheers
The following code achieves the aim you've stated. Not sure what your problem is, since you've neglected to post a complete example.
phpVarTest.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function myAjaxGet(url, callback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
callback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
}
ajax.open("GET", url, true);
ajax.send();
}
function onDocLoaded()
{
byId('testBtn').addEventListener('click', onTestBtnClicked, false);
}
function onTestBtnClicked(e)
{
var jsvar = 'some arbitrary text';
var url = 'phpVarTest.php?phpvar='+jsvar;
myAjaxGet(url, onAjaxDone);
}
function onAjaxDone(ajaxObj)
{
byId('outputDiv').innerText = ajaxObj.response;
}
</script>
<style>
</style>
</head>
<body>
<button id='testBtn'>Initiate ajax request</button>
<div id='outputDiv'></div>
</body>
</html>
phpVarTest.php
// server side script
<?php
echo '<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>';
$phpvar;
$phpvar = $_GET['phpvar'];
echo "new phpvar value = ".$phpvar;
?>
output
// server side script
<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>new phpvar value = some arbitrary text
Note: you should place the comment in the php file inside of the php tags - otherwise, you'll see it in the output, as shown above.

Find redirected img source

I have a URL to the latest Webcam shot http://cam.hackerspace.sg/last.jpg and it redirects to its source filename for example. 1364124301.jpg
I want to read the Epoch '1364124301' in Javascript so I can convert it to a timestamp. Though logging the img.src shows the old original URL. So how do I get '1364124301' without using Jquery?
Thanks!
Using JavaScript alone it seems impossible to get the redirect location: A XMLHTTPRequest hides the redirect transparently and an iframe does not allow to access it's URL if it's from another domain.
If you have a PHP enabled website the following will allow to get the redirect. (All code is without any capture of error conditions for simplicity, one will need to add error handling before using it).
First, to get the redirect location, some PHP, the file is called getRedirect.php:
<?php
$redirect = '';
$urlToQuery = $_GET['url'];
$urlParts = parse_url($urlToQuery);
$host = $urlParts['host'];
$path = $urlParts['path'];
$address = gethostbyname ($host);
$socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect ($socket, $address, 80);
$request = 'GET '.$path.' HTTP/1.1'."\r\n";
$request .= 'Host: '.$host."\r\n";
$request .= 'Connection: Close'."\r\n\r\n";
socket_write($socket, $request);
$answer = socket_read($socket, 8192);
socket_close($socket);
$answerLines = explode("\r\n", $answer);
foreach ($answerLines as $line) {
$lineParts = explode(':', $line, 2);
if($lineParts[0] == 'Location') {
$redirect=trim($lineParts[1]);
break;
}
}
header('Content-Type: text/plain; charset=us-ascii');
header('Content-Length: '.strlen($redirect));
echo $redirect;
?>
Second, the image display page which uses JavaScript to set up the image and to query the redirect location (via XMLHTTPRequest to getRedirect.php):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function updateImage() {
var imgParent = document.getElementById("imgContainer");
// delete existing image if exists
var imgChild = imgParent.firstChild;
if(imgChild!=null) imgParent.removeChild(imgChild);
// insert new image with actual redirect
var newImg = document.createElement("img");
newImg.src = "http://cam.hackerspace.sg/last.jpg";
imgParent.appendChild(newImg);
var redirect = getRedirect("http://cam.hackerspace.sg/last.jpg");
var timestamp = redirect.substring(redirect.lastIndexOf("/") + 1, redirect.lastIndexOf("."));
document.getElementById("imageDate").innerHTML="Timestamp="+timestamp;
}
function getRedirect(url) {
var redirect = "";
var req = new XMLHttpRequest();
req.open('GET', 'getRedirect.php?url='+url, false);
req.onreadystatechange = function () {
if (req.readyState == 4) {
redirect = req.responseText;
}
};
req.send(null);
return redirect;
}
</script>
</head>
<body>
<button onclick="updateImage();">update image</button>
<div id="imgContainer"></div>
<p id="imageDate"></p>
</body>
</html>
Using XMLHTTPRequest, you can read the newUrl after being redirected in XMLHTTPRequest.responseURL property. By comparing the newUrl with the originUrl, you can find out if it's a redirect.

Categories