PHP echo, outputting full html code (undesired) before object (desired) - javascript

When I echo $jsonstring, seemingly a whole blank html page is sent over (from PHP to Javascript) with the object I requested. Super new all around here, so I don't get why.
my php code:
<?php
//ini_set('display_errors', '1');
//ini_set('error_reporting', E_ALL);
require "localdbcxn.php";
$encoded = file_get_contents('php://input');
$decoded = json_decode($encoded, true);
$email = $decoded['email'];
$password = $decoded['password'];
$identify = mysql_query("SELECT UserId FROM users WHERE UserEmail='$email' AND UserPassword='$password'");
$numrows = mysql_num_rows($identify);
$row = mysql_fetch_assoc($identify);
$userid = $row['UserId'];
$sessionid = mt_rand(1111111111111111,9999999999999999);
$sessionkey = mt_rand(1111111111111111,9999999999999999);
$logindate = date("Y-m-d H:i:s");
$login = "INSERT INTO mobileSession (UserId, SessionId, SessionKey, BeginDate) VALUES('$userid','$sessionid','$sessionkey','$logindate') ON DUPLICATE KEY UPDATE SessionId='$sessionid', SessionKey='$sessionkey', BeginDate='$logindate' ";
if ($numrows == 1) {
mysql_query($login);
$session = array('UserId'=>$userid,'SessionId'=>$sessionid);
$jsonstring = json_encode($session);
echo $jsonstring;
}
?>
Here's what the console(log) shows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>{"UserId":"33","SessionId":8207219793564744}
From UserID til ...4744 is correct, but can anyone help me understand why the html code is being echoed? In my limited experience, I haven't seen this before, and feel that I am doing something wrong.
Thanks!

you must specify the content type before printing json data. before echo set header -
header('Content-type: application/json');

Related

Identify AJAX errors

I have a php file which has svg embedded in php variable. Using an onclick event on the svg elements displayed (lines with ID's) I want to change the colour of the SVG element and then send a parameter to a mysql table to return the x and y coords etc of other lines which join my selected line.
This part unto sending the parameter to mysql table works fine using ajax in my javascript function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/json" />
<title>Enter Exercises</title>
</head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script>
<script type="text/javascript">
function GetPathways(elt)
{
document.getElementById(elt.id).style.stroke = "blue";
var test=elt.id;
var test = document.getElementById(elt.id);
test.setAttribute("x2", "550");
test.setAttribute("y2", "450");
document.getElementById(elt.id).style.visibility = "visible";
var exid = parseInt(elt.id);
$.ajax(
{
type: "POST",
url: 'GetPathways.php',
data: {id: exid},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(message)
{
alert (message);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert("Error code is....:"+xhr.status);
}
});
};
</script>
Ajax calls php file which executes the sql required to return the table rows (multiple). I have tested the query in my phpAdmin and it works fine retrieving some appropriate rows of data.
Ajax script however only executes error function and not the success function.
The success function will eventually use the ID of the returned svg element to be displayed ie update the webpage based on the onclick event. Seems like a good use of ajax to refresh page without reloading.
GetPathways.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/json" />
<title>Get Pathways</title>
</head>
<body>
<?php
//echo "Hello from processing file GetPathways.php"."<br>";
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id";
mysql_query($query);
mysql_close($conn);
?>
</body>
</html>
Error code is 200
You have to echo the data inorder to get response from ajax call and also you did not execute the query. change the GetPathways.php as follows
<?
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id LIMIT 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
mysql_close($conn);
print_r($value);
?>

Updating a webpage with server sent events in PHP

Hi I'm currently working on a personal project which has two components. I want to POST "baby, 1" to my server, and when my server receives that "baby, 1", I want to change the webpage to reflect the date (currently using the date to test). I'm currently using Postman to test and largely borrowing code from W3Schools.
testpage.php
<html lang ="en">
<head>
<meta charset ="UTF-8">
<title>Title</title>
</head>
<body>
<div id = "result"></div>
<script>
if (typeof(EventSource) !== "undefined")
{
var source = new EventSource("server.php");
document.getElementById("result").innerHTML+="thug";
source.onmessage = function (event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
}else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
server.php
<?php
$bool = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["baby"])) {
$bool = $_POST["baby"];
if ($bool == 1) {
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
}
}
}
?>
When I test with the w3schools default code
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
testpage.php updates properly. When I try to POST to server.php with (baby,1) testpage.php does not update. I am really struggling to figure out why this is happening.

Don't show data when i click select form = "id=undefined"

Help me please.. it show "select_modelcar.php?brandid=undefined" when i choose select form but i try to paste this code in url and define id "select_modelcar.php?brandid=40", have the results. i want to choose same categories in select form such as when i choose brand "Toyota", it'll show all car model in Toyota brand (Camry, Yaris, etc.).
when i click select form >>
past in url and define id >>
select_brandcar.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<?php $servername = "localhost";
$username = "root";
$password = "usbw";
mysql_connect($servername,$username,$password);
mysql_select_db("carspecth");
?>
<body>
<script>
function ValueID(){
document.getElementById("getval").innerHTML = ('select_modelcar.php?brandid='+this.value);;
};
</script>
<select name="select_brandcar" id="select_brandcar" onclick="ValueID();" >
<option>Press Choose</option>
<?php
$sql = sprintf ("SELECT * FROM brand" );
$res = mysql_query ($sql);
while ($arr = mysql_fetch_array($res)){
printf ("<option value='%s'>%s</option>" ,$arr['brandid'], $arr['brandname']);
}
?>
<span id="getval"></span>
</body>
</html>
select_modelcar.php
<?php
mysql_query("SET NAMES UTF8");
include 'include_connectdb.php';
#$varbrandid = $_GET['brandid'];
#$sql = sprintf("SELECT * FROM maingeneration WHERE brandfk = %s", $varbrandid);
/*id ของตาราง catagory*/
#$res = mysql_query($sql);
printf("<select name='select' id='select'>");
while ($arr = mysql_fetch_array($res)) {
printf("<option value='%s'>%s</option>", $arr['maingenerationid'], $arr['maingenerationname']);
}
printf("</select>");
?>
Here are some suggestions:
Replace onclick with onchange
Pass the value of the select like this: onchange='ValueID(this.value);'
Then change the function to get that value:
function ValueID(brandid){
document.getElementById("getval").innerHTML = ('select_modelcar.php?brandid='+brandid);;
};

Display content dynamically with Dropdown (with connection to DB)

im pretty new into this stuff and I just tried to do an AJAX request with Javascript and PDO and PHP to create a dropdown function that reacts dynamically in order to display new content.. Since my knowledge is quite limited here I created it by combining snippets of code I got from various pages and videos. The error is:
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH) in /var/www/xxx/html/listing.php on line 22
This is my listing.php page where the dropdown and the new content should be displayed:
<!DOCTYPE html>
<html>
<head>
<title>listing</title>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keywords" content="">
<link href=".css" type="text/css" rel="stylesheet">
<link href="favicon.ico" type="image/x-icon" rel="shortcut icon">
</head>
<body>
<select name="user" id="user-select">
<option value="">Choose a user</option>
<?php foreach ($subjects->fetchAll() as $user); ?>
<option value="<?php echo $user['subject_id']; ?>"><?php echo $user['subject']; ?></option>
<?php endforeach; ?>
</select>
<div id="user-profile"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/global.js"></script>
This is the global.js file:
$('#user-select').on('change', function() {
var self = $(this);
$.ajax({
url: 'https://www.xxx.de/partials/user.php',
type: 'GET',
data: { user: self.val() },
success: function(data){
$('#user-profile').html(data);
}
});
});
And the partials/user.php, which contains the connection to the database:
<?php
$dsn = "xxx";
$user = "xxx";
$pw = "xxx";
try {
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if (isset($_GET['user'])) {
$userQuery = "
SELECT
subjects.subject_id,
subjects.subject,
FROM subjects
WHERE subjects.subject_id = :subject_id
";
$user = $pdo->prepare($userQuery);
$user->execute(['subject_id' => $_GET['user']]);
$selectedUser = $user->fetch(PDO::FETCH_ASSOC);
print_r($selectedUser);
}
?>
Any help is appreciated and I am thankful for any tips !
Stupid mistake.. I simply forgot to include the connection on the listing.php page to fill the foreach loop.
->
On listing.php before the !DOCTYPE html begins:
<?php
$dsn = "xxx";
$user = "xxx";
$pw = "xxx";
try {
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$usersQuery = "SELECT fach_id, fach FROM faecher";
$users = $pdo->query($usersQuery);
?>
Try replacing ; with : in php foreach statement
<?php foreach ($subjects->fetchAll() as $user): ?>

Connecting to database via PHP and displaying contents on browser

I am connecting to an SQL server via PHP script and displaying the contents retrieved on the browser.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
href="http://cdn.sencha.com/ext/trial/5.0.0/build/packages/ext-theme-neptune/build/resources/ext-
theme-neptune-all.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/php" src="connection.php"></script>
</head>
<body>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function() {
d3.json("connection.php", function (data) {
document.write(data);
});
});
connection.php
<?php
// Server Name
$myServer = "10.112.1.2";
// Database
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"logs", "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($myServer, $connectionInfo);
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$sql = "SELECT * FROM dbo.logsData";
$data = sqlsrv_query( $conn, $sql );
if( $data === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
All 3 files are in the same folder.
The browser just displays a null and I don't hit any of the logging information from the .php file. Is my method right? Am I using the right javascript event?
Change your connection.php in this way:
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
header('Content-Type: application/json');
}
You need to change mime type of your response. Moreover you cannot print out anything else than json data. That's way I removed from your code these lines:
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
Try using a relative pathname for connection.php here: d3.json("connection.php"
Something like "/dirname/connection.php".
You can test connection.php alone using a full pathname, like http://www.yourserver.xxx/dirname1/dirname2/...connection.php

Categories

Resources