Unknown Code Error - javascript

I've been trying my hardest to understand the lessons in W3Schools but it is not working somehow!
I've edited it so that you guys would get it much better.
This is the index.html page:
<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p id="demo"></p>
<script>
var myObj, i, x, j = "";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.stringify(this.response);
myObj1 = JSON.parse(myObj);
document.getElementById("demo").innerHTML = myObj1.stuid;
alert(myObj1);
}
};
xmlhttp.open("GET", "sing.php", true);
xmlhttp.send();
</script>
</body>
</html>
And here is the sing.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sacapp";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT stuid, stuname, stucourse, stustat, stulyear, stulog FROM stuinfo");
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
and here is the result of myObj1 [{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"InfoTech","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"CivilEngi","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]
but the document.getElementById("demo").innerHTML = myObj1.stuid; only returns an Undefined answer... what went wrong here?
I don't know what the hell is wrong with it. Can someone please point out any mistakes?

Remove the html from sing.php and only return JSON. Even though you see the correct output in your browser, if you view the source you'll notice the , etc. tags. Your script is seeing those and failing.

It looks like the AJAX request returns HTML, you can check what's being returned by using an alert, change the code to this:
if (this.readyState == 4 && this.status == 200) {
alert(xmlhttp.responseText);
}
If there is HTML in the alert, you should check if the path of the sing.php page is correct in the line:
xmlhttp.open("GET", "sing.php", true);

UPDATED ANSWER.
Ok, I checked everything and had a local setup. You have many mistakes in your code.
Let's take a look at index.html.
It should look like this. (I added comments where you made mistakes.)
<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p id="demo"></p>
<script>
var myObj, i, x, j = "";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this);
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.response); //**IT'S 'response' NOT 'responseText' To look at the object data, you can do console.log(myObj) and see what the object looks like. in the developer window**
document.getElementById("demo").innerHTML = myObj.student_id; //**YOU DON'T HAVE A PROPERTY 'id' BUT YOU DO HAVE 'student_id', again look at the json object in the developer window. **
}
};
xmlhttp.open("GET", "sing.php", true);
xmlhttp.send();
</script>
</body>
</html>
As for 'sing.php', since I don't have your database, I created my own arrays so that I could merge them since I think this is what you're trying to do.
<?php
$outp = array(
'student_id' => '10-00000',
'student_name' => 'Breaker M. North',
'student_course' => 'BSIT',
'student_stat' => 0,
'student_log' => 1
);
$outp2 = array(
"stu_log" => 2,
"course_name" => "IT 202",
"student_id" => "10-00000"
);
echo json_encode(array_merge($outp, $outp2));
?>
When you do echo json_encode($outp + $outp2); you're actually creating and new array and putting $outp and $outp2 as separate values. That's why you had the [], you had two values and not only one. You then had undefined because you couldn't access the property, instead you we accessing the first element of the json array.
On a side note, you could create only one SQL request by using JOIN on student_id... but this is not part of the question.

Related

Insert user-specific data into HTML via PHP, JSON, andJavascript

I know this site doesn't like "spot my mistake" code, but I'm desperate. I have a website that needs to access user-specific data from a database (PHP), convert the data into a JSON file, and then change a HTML header to display that specific data. The database table has the user email, password, and class name, among other things. I have a login page that establishes the session variables for the email and the password. When the user logs in, I want their class name to be entered into HTML text. I've used dozens of sources, mostly W3schools, and came up with this code:
PHP:
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
if (!$obj) {
die(mysqli_error());
}
$servername = "localhost";
$username = "id5143969_enviroquest1";
$password = "codeteam1";
$database = "id5143969_enviroquest1";
$link = mysqli_connect($servername, $username, $password, $database);
$result = $link->query("SELECT UserClassName FROM ".$obj->UserInfo1." WHERE ".$obj->UserEmail."= '". mysqli_real_escape_string($link,
$_SESSION['useremail']) . "' and ".$obj->UserPassword." = '" . mysqli_real_escape_string($link, $_SESSION['userpassword']) . "'");
if (!$result) {
die(mysqli_error());
}
$_SESSION['classname'] = $result->fetch_assoc();
if (!$_SESSION['classname']) {
die(mysqli_error());
}
echo json_encode($_SESSION['classname']);
Javascript:
function getclassname() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "UserInfo1":"UserClassName"};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("UserClassName").innerHTML = myObj;
}
};
xmlhttp.open("GET", "php2.php" + dbParam, true);
xmlhttp.send();
}
HTML:
<h1 class="text-center" id="UserClassName" name="UserClassName" onload=
"getclassname()"> </h1>
I have no idea what's going wrong, and am too new to coding to figure it out by myself.
Try this (I can't test it, but)—
PHP:
Remove the ?> at the end of the file. Pure-PHP files should always leave off the closing tag.
Change (MYSQLI_ASSOC) to just () - per this and the docs, you don't need it.
Javascript:
Remove the session_start() call
Change
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
to
txt = myObj.UserClassName
The fetch_assoc() call in PHP gives you a mapping that uses the database field names ("each key in the array represents the name of one of the result set's columns" per the docs) for a single row. Therefore, if the JSON encode/decode worked OK, you should be able to refer directly to the field.
To test this, in the developer tools, set a breakpoint at the txt = ... line and see what myObj is.
I don't think you need $obj, dbParam, or ?x=, but I would not suggest changing them unless the above doesn't help.
Good luck!

Javascript passing parameter to php to run mysql query and retrieve result

I am working on a demo webpage which put some products' volumes onto Google Map in some geojson polygons.
The code that to put volume onto Google Map:
map.data.addListener('click', function(event){
//Get area-information from polygon
var area_information = event.feature.getProperty('area');
/*var product_volume = showVolume(area_information); DOES NOT WORK
instead, I am sending the result to a div called p_volume and assign the value of p_volume to product_volume*/
var infowWindow_contentString = '<b>Area: </b>' + area_information+ '<br>' + '<b>Volume: </b>' + product_volume;
polygon_infoWindow.setContent(infowWindow_contentString);
polygon_infoWindow.open(map);
polygon_infoWindow.setPosition(event.latLng);
});
Now the showVolume() function:
function showVolume(area_information){
var xhr;
var result;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var areainfo = "areainfo=" + area_information;
xhr.open("POST", "get-data.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(areainfo);
xhr.onreadystatechange = display_data;
//Display Data
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementbyId('p_volume').textContent = xhr.responseText;
}
else {
alert('There was a problem with the request.');
}
}
}
};
Which calls the get-data.php.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$db_name = "mockdata";
$areainfo = $_POST['areainfo'];
$con = mysqli_connect($servername, $username, $password, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$stmt = $con->prepare('SELECT Volume from mockdata WHERE Area = ?');
$stmt->bind_param('s', $areainfo);
$stmt->execute();
$result = $stmt->get_result();
//echo $areainfo; //Testing if parameter passed into php
while ($row = $result->fetch_assoc()) {
// do something with $row
echo "{$row["Volume"]}";
}
mysqli_close($con);
?>
For each query, I am expecting only one integer from the Volume in my table. I checked the parameter is passed to get-data.php by simply
echo $areainfo;
I learned:
var product_volume = showVolume(area_information);
does not work....
Edit
It seems that the
<div><id = p_volume></div>
is getting the query result. However, my product_volume still couldn't get the result from the p_volume by simply doing
product_volume = getElementbyId('p_volume').innerHTML;
I am wondering what is wrong.
I am new to all these 3 languages. Please be gentle when criticizing "Go learn xxx language".
Thanks in advance.
Okay, I got them to work finally. My code was right when sending the parameter to PHP and have the PHP to process it. Then we need a container (<div>) to receive the data by doing getElementbyId('p_volume') = xhr.responseText.
Then in the Google Map
map.data.addListener('click', function(event){
//Get FSA from polygon
var areainfo = event.feature.getProperty('area');
showVolume(areainfo);
var product_volume = document.getElementById("p_volume").innerHTML;
var infowWindow_contentString = '<b>FSA: </b>' + FSA + '<br>' +'<b>Volume: </b>' + product_volume;
polygon_infoWindow.setContent(infowWindow_contentString);
polygon_infoWindow.open(map);
polygon_infoWindow.setPosition(event.latLng);
});
The data will be retrieved from the hidden <div><id = "p_volume", style = "display: none;">
Please do comment on the security/malpractice aspect since I really want to learn.
Edit
Update:
The code does not update the <div> immediately, it took a couple of clicks more to get the data updated. Can someone explain the synchronization issue in the code? I also have a mouseover action on the polygons in Google Map, they have the same issue.

Updating javascript array with click when new mysql data comes in

I am using the following code to send mysql database content into a javascript array. This works fine when I start the page, but when the database gets a new entry, the new entries are not added to the array when I rerun this bit of code - unless I reload the entire page.
<p><button onclick="save_image()">Send image</button></p>
<script type="text/javascript">
function save_image(){
var userName =
<?php
$conn = new mysqli(.........."); //connect to database
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
console.log(userName)
}
</script>
I realize there are other pages about this topic, but I didn't know how to apply them to my case. If you have some ideas. Thanks.
If you want to get information from the database without reloading the page, you'd need to do an Ajax request to retrieve the information.
Something like this would work:
PHP - ajaxendpoint.php
<?php
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>
JavaScript
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText); //log the response from the database
//if the PHP is returning a JSON object, you can parse that:
var myArray = JSON.parse(xhttp.responseText);
}
}
xhttp.open("GET", "ajaxendpoint.php", true);
xhttp.send();
}
HTML - index.html
<button onclick="getData()">
Load Data via Ajax
</button>
Here is another example Ajax request in this JS Fiddle: https://jsfiddle.net/igor_9000/77xynchz/1/

Passing variable to php MySQL script with Javascript

I borrowed this code from another source.
Now, I am attempting to modify it.
I need to pass the contents of $q to my php page and use this as a where clause in my SQL statement.
My Javascript:
<script>
function subject(str) {
if (str == "") {
document.getElementById("subject").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("subject").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","form_get.php?q="+str,true);
xmlhttp.send();
}
}
</script>
Inside the html select code I am using:
onchange="subject(this.value)"
My PHP
$q = intval($_GET['subject']);
//if (!empty($_GET['q'])){
//$q = $_GET['q'];
//}
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";
As you can see, I am passing the $q into my SQL statement.
I understand that intval returns a number, but when I try other types, such as strval, it breaks the script. It als breaks the script when I tried the commented out section above.
When I change the php to: $q=$_GET["q"]; I get the error: form_get.php?q=Reading 500 (Internal Server Error).
This tells me that $q is indeed pulling from the options list, but something else is going on...
the problem is with your php you suppose to get the q and not subject
$q = intval($_GET['q']);
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";
$q = intval($_GET['subject']);
This looks wrong - should that not be $q = intval($_GET['q']);?

PHP not Sending JSON Object to JavaScript

<?php
header("Content-Type: application/json");
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
require_once("connect_db.php");
$i = 0;
$jsonData = '{';
$sqlString = "SELECT * FROM tablename ORDER BY RAND() LIMIT $limit";
$query = mysqli_query($con, $sqlString) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$i++;
$id = $row["id"];
$title = $row["title"];
$cd = $row["creationdate"];
$cd = strftime("%B %d, %Y", strtotime($cd));
$jsonData .= '"article'.$i.'":{ "id":"'.$id.'","title":"'.$title.'", "cd":"'.$cd.'" },';
}
$now = getdate();
$timestamp = $now[0];
$jsonData .= '"arbitrary":{"itemcount":'.$i.', "returntime":"'.$timestamp.'"}';
$jsonData .= '}';
echo $jsonData;
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var myTimer;
function ajax_json_data(){
var databox = document.getElementById("databox");
var arbitrarybox = document.getElementById("arbitrarybox");
var hr = new XMLHttpRequest();
hr.open("POST", "json_mysql_data.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
arbitrarybox.innerHTML = d.arbitrary.returntime;
databox.innerHTML = "";
for(var o in d){
if(d[o].title){
databox.innerHTML += '<p>'+d[o].title+'<br>';
databox.innerHTML += ''+d[o].cd+'</p>';
}
}
}
}
hr.send("limit=4");
databox.innerHTML = "requesting...";
myTimer = setTimeout('ajax_json_data()',6000);
}
</script>
</head>
<body>
<h2>Timed JSON Data Request Random Items Script</h2>
<div id="databox"></div>
<div id="arbitrarybox"></div>
<script type="text/javascript">ajax_json_data();</script>
</body>
</html>
PHP code goes on a separate file called "json_mysql_data.php". I'm just following this tutorial from https://www.youtube.com/watch?v=-Bv8P5oQnFw and it runs fine for him but not for me. I tested "connect_db.php" with mysql alone and it works fine. It seems to me like php doesn't go pass if (isset ($_POST['limit'])) but why...On the html file I get the "requesting..." message from the javascript code which means is waiting for PHP. Thanks for your help guys.
You check for the ready state and change the content of databox with the response JSON inside the onreadystatechange function:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
databox.innerHTML = "requesting...";
…
}
But you change the HTML of the databox:
databox.innerHTML = "requesting...";
Still inside the block of the onreadystatechange function and after you receive the response, so the databox will always say "requesting..." no matter what you receive. You have to move the part that prints "requesting..." outside of it:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
}
…
databox.innerHTML = "requesting...";
…
Update:
Also, it seems that your function ins't defined correctly, as you can see, the one on the MDN reference pages example receives a parameter:
req.onreadystatechange = function(aEvt) {
…
}
But yours doesn't have such parameter:
hr.onreadystatechange = function() {
…
}
Ans that's it.
Thank you for your help #arielnmz. I found the problem. PHP was having issues with the getDate() function because the date.timezone field was not configured in the PHP.ini file. Adding the following line to the file fixed the problem:
date.timezone = "UTC"

Categories

Resources