I have a API php functions that executes a SQL query from the database and encodes the values in JSON.
eg
function getApiCall(){
$sql = 'SELECT * AS "Total" from tablename"';
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_OBJ);
$db = null;
echo json_encode($user);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
The value on calling the URL http://localhost/getapicall/apikey in the browser is
{"Total":"80"}
In my front end HTML page using JavaScript, the API URL is called
<script type="text/javascript">
var myJSON = $.get('../v1/getapicall/default');
document.getElementById("txt1label").innerHTML = myJSON;
</script>
But the value displayed is [object object] , how do I display the value of the json data i.e 80 in this case?
If I try putting
document.getElementById("txt1label").innerHTML = myJSON.Total;
The value gets displayed as undefined.
$.get() is an asynchronous function, which means it won't return your data right away- it has to make a round trip to your server first.
Instead you pass it a function to be executed when the data is returned from your endpoint.
var myJSON = $.get('../v1/getapicall/default', function(result) {
document.getElementById("txt1label").innerHTML = result.Total;
}));
You need to pares your json data and also wait for the get request to complete. Get being asynchronous.
<script type="text/javascript">
$.get( '../v1/getapicall/default', function( data ) {
var obj = JSON.parse(data);
document.getElementById("txt1label").innerHTML = obj.Total;
});
</script>
Related
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.
I am trying to use a localStorage variable in a php function so I decided to use jquery post() to do so. Afterwards, I want to echo back data to my original file and set it inside a global variable. I have 3 files that connect to each other (its just a bit complicated).
quick_match.php
dataString = "";
$.post("ajaxCtrl.php", {action: "doQuickMatch", numCard: localStorage['numCard'], UI: "<?php echo $_REQUEST['UI']; ?>"}, function(data){ dataString = data; });
ajaxCtrl.php
if($action == "doQuickMatch")
{
//Start Quick Match
$result = $user->getQuickMatch($numCard);
echo $result;
}
User.php
(A big query here but I guarantee it works)
// Perform Query
$result = mysql_query($query);
//Hold the array objects in a string
$string = "";
// Iterate through results and print
while ($row = mysql_fetch_assoc($result)) {
$string .= '{ image: \'http://personals.poz.com'.$row['my_photo'].'\', user_id: \''.$row['id'].'\', user_prof: \'http://127.0.0.1/personalz.poz/v2/member.php?username='.$row['id'].'\'};';
}
return $string;
After all of this, I'm supposed to use the string and split it so I can get an array and continue on with what I was doing. However, the callback keeps on returning nothing so I am not sure what I did wrong. Can anyone offer insight to this please? Thank you in advance.
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 JS script of:
function addTasteingNote(userID,beerID)
{
//get values
var note = $('#note1').val();
var ajaxSettings = {
type: "POST",
url: "a.php",
data: "u="+userID+"&b="+beerID+"&n="+note,
success: function(data){
} ,
error: function(xhr, status, error) { alert("error: " + error); }
};
$.ajax(ajaxSettings);
return false;
}
and the php script to add to the db is:
<?php
error_log("starting code");
require_once('connect.inc.php');
$u = $_GET['uID'];
$b = $_GET['bID'];
$n = $_GET['n'];
//do some checks etc
$db = new myConnectDB();
error_log("Successfully created DB");
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ($u, '$b', '$n')";
error_log($query3);
$result = $db->query($query3);
?>
The problem is that the error log shows nothing being put into the query:
[01-Nov-2013 23:40:29] Successfully created DB
[01-Nov-2013 23:40:29] INSERT INTO x (userID,beerID,note) VALUES (, '', '')
I have put alerts in the success of the ajax call, so I know that values are being passed through...
You need to give data like
var ajaxSettings = {
type: "POST",
url: "a.php",
data: {u:userID,b:beerID,n:note},
success: function(data){
}
data wont be and Query string,And since you are posting the values through ajax you need to get them via POST only like
$u = $_POST['u'];
$b = $_POST['b'];
$n = $_POST['n'];
And your query should be like
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ('".$u."', '".$b."', '".$n."')";
And Better to use escape strings with your POST variables to prevent from SQL injection.
You are using post method so, you need to get data using $_POST or $_REQUEST instead of $_GET
$u = $_REQUEST['u'];
$b = $_REQUEST['b'];
$n = $_REQUEST['n'];