I have a json string in my sql database.
get_survey_results.php
<?php
// including some cfg & functions
include_once("config.php");
include_once("funcs.php");
// setting connection and getting user id
$con = setConnection();
$hash = $_COOKIE['hash'];
$query = "SELECT user_id FROM `users` WHERE hash='$hash' LIMIT 1";
$result = mysqli_query($con, $query);
$data = $result->fetch_assoc();
$id = -1;
if (sizeof($data) > 0) {
$id = $data['user_id'];
}
// if user id is exist get jsonstring from database
if ($id > 0) {
$q = "SELECT results FROM `survey_results` WHERE user_id='$id' LIMIT 1";
$r = mysqli_query($con, $q);
$d = $r->fetch_assoc();
echo json_decode($d['results']); // !!!
// PS $d['results'] exist, it is a json string
// tried also echo $d['results'] but get no result
}
else {
// otherwise get false, false is getting ok in responce, but not results above
echo "false";
}
closeConnection($con);
?>
I want to return it in JS using XMLHttpRequest:
var json
var data = new FormData()
// AJAX CALL
var xhr = new XMLHttpRequest()
xhr.open('POST', "php/get_survey_results.php", true)
xhr.onload = function(){
var jsonString = this.response
console.log("JSON STRING IS")
console.log(jsonString) // !!! returns empty
};
But it returns nothing in case user exist, otherwise returns false. I marked problem places as !!!
Related
I'm trying to get a response from an SQLite DB, using an XHR on a PHP file, but I'm unsure how to handle the SQLite Object that's being returned Currently, I'm just trying to console.log the response but I'm getting the error in the title. Do I need to stringify the response perhaps?
<?php
$database = new SQLite3('cookieOrders.sqlite');
$statement = $database->prepare('SELECT creation_time FROM orders WHERE order_id = 1;');
$result = $statement->execute();
echo $result;
?>
-
function populateOrders() {
var x = new XMLHttpRequest();
x.onreadystatechange=function(){
if (x.readyState==4 && x.status==200){
var response = x.responseText;
console.log(response);
}
}
x.open("GET","./php/queryDB.php",true);
x.send();
return false;
}
You have to fetch data. Currently you are trying to echo a SQLite3Result object, which is the result of execute() :
$result = $statement->execute() ;
$row = $result->fetchArray() ;
echo json_encode($row) ;
// or echo $row['creation_time'] ;
// or print_r($row) ;
On trying to return some data from a GET request via AJAX, I'm continuously greeted with this nasty error message ...Unexpected token { in JSON... and I can clearly see where it's coming from. Note that this only happens if I have more than one(1) item being returned from the database. If I only have one(1) item I am able to access it data.id, data.user_name, so on and so forth.
{
"id":"39",
"user_id":"19",
"user_name":"Brandon",
"content":"Second Post",
"date_created":"2018-01-24 21:41:15"
}/* NEEDS TO BE A ',' RIGHT HERE */ {
"id":"37",
"user_id":"19",
"user_name":"Brandon",
"content":"First",
"date_created":"2018-01-24 15:19:28"
}
But I can't figure out how to fix it. Working with data, arrays, and objects is an artform I have yet to master.
JAVASCRIPT (AJAX)
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/mouthblog/test.php');
xhr.onload = () => {
if (xhr.status == 200) {
const data = xhr.responseText;
const jsonPrs = JSON.parse(data);
console.log(jsonPrs);
} else {
console.log('ERROR');
}
};
xhr.send();
PHP (this is where the data is coming from)
<?php
class BlogRoll extends Connection {
public function __construct() {
$this->connect();
$sql = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
FROM `posts`
ORDER BY `date_created` DESC";
$query = $this->connect()->prepare($sql);
$result = $query->execute();
if ($result) {
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
header('Content-Type: application/json;charset=UTF-8');
echo json_encode($row);
}
} else {
echo 'NO POSTS TO DISPLAY';
}
}
}
I've been at this for a couple of hours now, everything similar to my problem on SO seems to be something different and I can't really find a decent plain JavaScript tutorial on returning real data. Everyone wants to use jQuery.
The reason why your code is failing is because you are using
echo json_encode($row);
This will echo an array for every row, but it is not valid JSON. I have corrected your PHP code (note: it has not been tested)
<?php
class BlogRoll extends Connection {
public function __construct() {
$this->connect();
$sql = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
FROM `posts`
ORDER BY `date_created` DESC";
$query = $this->connect()->prepare($sql);
$result = $query->execute();
$returnArray = array(); // Create a blank array to put our rows into
if ($result) {
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
array_push($returnArray, $row); // For every row, put that into our array
}
} else {
// Send the JSON back that we didn't find any data using 'message'
$returnArray = array(
"message" => "No data was found"
);
}
header('Content-Type: application/json;charset=UTF-8'); // Setting headers is good :)
exit(json_encode($returnArray)); // Exit with our JSON. This makes sure nothing else is sent and messes up our response.
}
}
Also, you stated this:
If I only have one(1) item I am able to access it data.id, data.user_name, so on and so forth.
That is correct because the array only contains that one item. The example you would access it via data.0.id, data.1.id, data.2.id, etc as each row is in its own array.
You must print only once, e.g. a data "package" from which you will reference the items on the client-side correspondingly. But in your code you're actually printing for each row a data "package".
The solution is to create an array and save the whole fetched data into it. After that the array should be json-encoded and printed.
if ($result) {
// Save the fetched data into an array (all at once).
$fetchedData = $query->fetchAll(PDO::FETCH_ASSOC);
// Json-encode the whole array - once.
// header('Content-Type: application/json;charset=UTF-8');
echo json_encode($fetchedData);
} else {
echo 'NO POSTS TO DISPLAY';
}
I have a javascript file in which I am doing an ajax request to foo.php
in order to get an array of mysql results.
Here is my javascript file.
//foo.js
$(document).ready(function(){
$.ajax({
url:"foo.php",
type:"POST",
data:{
action:"test",
remail:"foo"
},
success:function(data){
var messages = data;
console.log("Ext req");
try{
console.log(JSON.parse(data));
}catch(e){
console.log(data);
}
},
failure:function(){
}
})
});
In order to receive my array of results from php I do the following:
//foo.php
<?php
if(isset($_POST)){
$action = $_POST['action'];
if(empty($action)){
return;
}
switch($action){
case "test":
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
echo json_encode($ar);
break;
}
}
?>
This returns an array of objects to my ajax request which then I can handle according to my needs.
However if I try to move the php code inside the switch statement into a function and return the encoded result of the function I only get an empty array as response.
Here is how I am trying to do it:
<?php
function test(){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
if(isset($_POST)){
$action = $_POST['action'];
if(empty($action)){
return;
}
switch($action){
case "test":
$result = test();
echo json_encode($result);
break;
}
}
?>
Any ideas why this happening?
UPDATE
$con is a variable that comes from another file which I include
When you moved your query logic into a function, $con, MySQL's connection object is not available. Use GLOBAL $con; inside your function.
Read this to understand Variable Scope
Method 1
Using GLOBAL keyword
function test(){
GLOBAL $con;
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
Method 2
Pass an argument to a function
function test($con){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
Call it like this:
test($con);
Global variables if not used carefully can make problems harder to find as other solution suggested. Pass $con as argument to your function:
function test($con){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
Let us talk about the problems you have:
You pass a failure function to $.ajax. You surely wanted to use error instead of failure. See here.
You have a messages variable initialized, but unused inside success. Get rid of it.
You check for isset($_POST), but that will always be true. You wanted to check isset($_POST["action"]) instead, or you wanted to check whether it is a POST request.
$con is not available inside the function. You will need to either initialize it inside the function or pass it to it and use it as a parameter.
Hi Brothers and Sisters
My First post , im new to json and am having a problem getting data into a jvqmap I can get it working if I just add a var ie
var sample_data = ({
"gb":"6","us":"3"
});
but not dynamically, I think in need to pass a a object as the inbound data is appearing as a json array in console just a hunch but don't have a clue how to do it with the ajax. json response below. if someone could assist I would be eternally grateful,1 years php not really cutting through the mustard.
$.ajax({
url: 'countries.php',
dataType: 'json',
success: function(json) {
data = [];
for (i in json) {
data[i] = json[i];
}
// var data = JSON.parse(json);
console.log(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" +
xhr.responseText);
}
});
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: null,
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
scaleColors: ['#C8EEFF', '#006491'],
normalizeFunction: 'polynomial',
selectedRegions: [],
values: data_arr
,
onLabelShow: function (event, label, code) {
if(data[code] > 0)
label.append(': '+data[code]+' Attendees');
} });
Countries.php page
header('Content-type: application/json');
$conn = new mysqli("localhost", "root", "", "wordpress2");
//$result = $conn->query("
$query = "SELECT * from countries";
//MySQL query
$json = array();
$result = $conn->query($query); //MySQL query is executed, and result stored in the variable $result
while($row = $result->fetch_assoc()){ //the result is an associate array, this array is assigned to $row variable
$json[] = $row['CNT_ISO'].'"'. ':'. '"' .$row['attendees'] ;
To generate an object like the one you manually created for testing, you can create a stdClass() object, fill its properties with the required data and then return that by calling json_encode() on your object and it will be converted automatically to a JSON String to be passed back to the javascript.
You can also make the query more efficient by only returning what you actually want from the query.
Its also a good idea to add some status checking after any query call.
$conn = new mysqli("localhost", "root", "", "wordpress2");
$query = "SELECT CNT_ISO, attendees from countries";
$result = $conn->query($query);
if ( $result === FALSE ) {
echo $conn->error;
exit;
}
$countries = new stdClass() // create a new object
while($row = $result->fetch_assoc()){
$countries->{$row['CNT_ISO']} = $row['attendees'];
}
echo json_encode($countries);
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.