The following is the php code:
<?php
session_start();
if(isset($_SESSION["loggedUser"])) {
generateAndProvideData($_SESSION["loggedUser"]);
} else {
//error handling
}
function generateAndProvideData($loggedUser) {
$connection = establishConnectionToDatabase();
$UserData = retrieveUserData($connection, $loggedUser);
echo json_encode($UserData);
}
function retrieveUserData($connection, $loggedUser) {
return $connection->query("
SELECT name, vorname, email
FROM benutzer
WHERE id = '".$loggedUser."'
")->fetchAll(PDO::FETCH_ASSOC);
}
function establishConnectionToDatabase() {
try {
$connection = new PDO('mysql:host=localhost;dbname=------------','------','-----');
} catch(PDOException $e) {
echo $e->getMessage();
}
return $connection;
}
?>
On the scriptside, it was called like this:
function populateUserData() {
$.post('../include/getUserDataForBenutzerprofil.php', {
//nothing to transmit
}).then((data) => {
data = JSON.parse(data)
console.log("data from getUserDataForBenutzerprofil.php is ", data)
//$('#name').val(data.name)
})
}
Now, as far as I understand php, it creates an array with the names of the columns being the keys to the respective values.
However, the array that is returned to the front-end seems to be multidimensional, see the following output:
[{"name":"----","vorname":"-----","email":"---.---#example.de"}]
Why is that? And is there any way around it?
This way, I always have to address the numerical index "0" first, and then in the second index write out the respective associative key. While this isn't a major issue, it feels rather "unclean", since this is neither necessary nor was it intended.
According to https://www.w3schools.com/js/js_json_parse.asp
When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.
and
As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.
so try changing your response format to json.
function populateUserData() {
$.ajax({
type: "POST",
url: "../include/getUserDataForBenutzerprofil.php",
// data: {},
dataType: "json" //<-- this
}).then((data) => {
data = JSON.parse(data)
console.log("data from getUserDataForBenutzerprofil.php is ", data)
})
}
Assuming the response is a valid JSON string of course.
Related
I am using axios.get to retrieve the element I want, and it return successfully with json data showen below:
It gooes fine, with [ and { perfectly allocated. Here is my duty, I want to retrieve one column element (this json only has one templete), let's say OrederReferencePreffix, it returns undefined instead of [[\t ... I've try these declaration below:
var attempt_one= json_only[0].InvoiceNumberPreffix; //undefined
var attempt_two= response.data.InvoiceNumberPreffix; //undefined
var attempt_three= response.data[0].InvoiceNumberPreffix; //undefined
var attempt_four= json_only.InvoiceNumberPreffix; //undefined
The php returns the correct one like above, and in js
axios.get('http://localhost/backend/get_templete.php', {
params: {
clciked_cpy: cpy
}
})
.then(function(response) { //attempt above, need to put my ans in here; tried
var json_only = pre_cpy_cut.exec(response.data.toString());
console.log("=]" + json_only);
} #reponse.data
in case you need, php:
$json = array();
while($row = mysqli_fetch_assoc($result)) {
$json[] = $row;
}
mysqli_free_result($result);
echo json_encode( $json, JSON_UNESCAPED_SLASHES ); //return as same as the picture above
#response.data already gives me json and stuff for me already. Why it still not return the column data I want? How to do that.
I think you could gave more informations about your code, but for what I understood you aren't manipulating the JSON correctly. You need to parse the data retrieved by the axios request. Try:
axios.get('http://localhost/backend/get_templete.php', {
params: {
clciked_cpy: cpy
}
})
.then(function(response) {
const parsedResponse = JSON.parse(response.data)
// now you can access correctly the response data.
console.log(parsedResponse.anyVariableYouWant)
})
I need help converting some json data into a php array. I am using the STRIPE API. It is first inputted into a javascript array
// The items the customer wants to buy
var purchase = {
items: [{ id: 2235 }]
};
Then ajaxed like so
fetch("create.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(purchase)
})
on the server side (php)
header('Content-Type: application/json');
try {
// retrieve JSON from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
//echo $json_obj;
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => calculateOrderAmount($json_obj->items),
'currency' => 'usd',
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
Where I get into trouble is the calculateOrderAmount function. The function looks like so (the return is just hard coded for now but I will replace with an amount)
function calculateOrderAmount(array $items): int {
// I need to loop through the array and break out the
// product ids
return 1400;
}
For the life of me I cannot figure out how to loop through the array and get the id value. I intend on looping through the array id, getting the values from my mySQL database and returning it.
Can anyone give me an idea of what to do?
I recommend changing your json_decode() call to include the second argument, which specifies if the JSON will be decoded to a PHP object (false) or an associative array (true), like so:
$json_obj = json_decode($json_str, false);
This way you're not depending on the JSON_OBJECT_AS_ARRAY flag setting to determine if you get an object or an array when decoding JSON.
Next, inside calculateOrderAmount(), you can do something like this:
foreach($items as $item) {
// Do something with $item->id
}
I am a Laravel learner. What I am trying to learn now is to send a JSON file from a back end into the front-end, so that I will use this JSON file to draw a graph.
In my model, I write a function that will extract the values and time stamp created_at. Here is a piece of code that will return the google page speed value associated with a single website and the time stamp.then I want to use JS to draw the graph where the vertical value is the google page speed and the horizontal is the time stamp created at.
Anyone who can help me? Do I need to change the return value to an array?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Notification;
use App\Status;
class ChartController extends Controller
{
public function speedHistory(){
$o_status = Status::where('name','speed')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get();
if($o_response){
return response()->json($o_response);
}
// return an empty json array instead of false
//return false;
return response()->json(array());
}
}
and trhe route is
Route::get('json','ChartController#speedHistory');
keeps complaining the methods is not defined. this is my model
lass Notification extends Model
{
protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
You could use the json() method on response().
The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:
$array = ['data'];
return response()->json($array);
Laravel Documentation (json-response)
In your function:
public function speedHistory(){
try{
$o_speed = Status::where('name','speed')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values', 'created_at')->orderBy('created_at','DESC')->get();
if($o_response === null)
//You can use this to go in catch: "throw new Exception();" or "return false" if you want
throw new Exception();
// Returns a json to be consumed in ajax
return response()->json(['status' => 1, 'code' => 200, 'message' => 'Your message', 'value' => $o_response->values, 'timestamp' => $o_response->created_at], 200);
}catch(\Exception $e){
return response()->json(['status' => 0, 'code' => 400, 'message' => $e->getMessage()], 400);
}
In your ajax you consume this way:
var request = $.ajax({
// Here's your route of speedHistory
url: "YOUR_ROUTE",
type: "GET",
dataType: "json"
});
request.done(function(response) {
if(response.status == '1'){
$("#youDiv").html(response.value + ' - ' + response.timestamp);
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
To improve on my answer, you will need to return 'response()->json()' which will change the content type to json, essentially making the response a so called "JSON file".
Can you try this? I think you are trying to get values and created_at from a collection which should not work. I assume you use L5, see Danis Abols comment otherwise.
public function speedHistory(){
$o_status = Status::where('name','speed')->first();
$o_response = Notification::where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get();
if($o_response){
return response()->json($o_response);
}
// I would return an empty json array instead of false
//return false;
return response()->json(array());
}
Update: added Notification:: based on comments from op
Try this
return json_encode(array('value' => $o_response->values,'timestamp' => $o_response->created_at));
I'm pretty confused and every way I've tried I keep getting internal error 500.
I'm trying to parse THIS json using PHP and return it to the client side.
inventory.php
/**
* Fetches users inventory.
*/
$userId = $_GET['userId'];
$inventoryUrl = 'http://steamcommunity.com/id/' . $userId . '/inventory/json/730/2/';
if ($userId) {
$url = file_get_contents($inventoryUrl);
$json = json_decode($url);
print_r($json);
}
And with jQuery I'm trying to fetch that object and parse it so I can insert it into html.
$.when(getUserInventory('koraktor')).done(function(data){
var inventory = data;
var selectItemsElem = $('#select-items');
console.log(inventory);
//console.log(inventory);
});
function getUserInventory(userId) {
var inventoryUrl = 'inventory.php';
return $.ajax({
url: 'inventory.php',
data: {userId: userId},
})
.done(function(data) {
return data;
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
});
In console it shows:
I need to parse $object->rgInventory->rgDescriptions
I'm just not sure how though.
SO my question is, how do I correctly parse this object so I can use a for loop and how would I use the for loop so I can insert each item into html?
You can enumerate the properties of the rgInventory part of your object. These are your items.
for(var item in inventory.rgInventory) {
if (inventory.rgInventory.hasOwnPrioperty(item) )
console.log(item.id)
}
I have this function in php
public function get_updated_session_value()
{
$sql = "SELECT IF(Session = 12345678 , 1,0) AS login FROM `psf_users` WHERE id = 236";
$var = $this->addDb($sql)->execute();
$Session = $var['login'];
return json_encode('2');
}
and the javascript code to fetch this value,
function check() {
$.ajax({
url : 'auctions.php',
type : 'get',
// dataType: 'json',
data : {page:'__request', module:'PSF_auctions', action:'get_updated_session_value'},
success: function(data) {
console.log(data);
}
});
}
also, this function runs every 5 seconds via
setInterval(check, 5000);
the problem is, console.log(data); prints nothing, i believe that means it is not getting any data (or json response) from the php function. am i missing something?
It can't work as you're returning the value. The difference between returning a value and emitting a response is that the latter writes a response on the HTTP stream whilst the first one merely returns the control to the parent with a specific value.
Sanjay has spotted it very well, and I'd recommend that you use a very simple function to wrap up your responses:
function emit_response( $status_code, $data ) {
http_response_code( $status_code ); // 200 is it's success. find more http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
die( json_encode( array(
"status_code" => $status_code,
"data" => $data )));
}
Then modify that echo (though it's fine as well) with
emit_response( 2 );
and since the response is valid JSON, JavaScript will love it; in your callback, you can simple do this:
success: function(res) {
var response = JSON.parse( res );
// response.data will be 2. :)
// ... rest of the code ...
Replace return with echo like this:
public function get_updated_session_value()
{
$sql="SELECT IF(Session = 12345678 , 1,0) as login FROM `psf_users` WHERE id=236";
$var= $this->addDb($sql)->execute();
$Session= $var['login'];
echo json_encode('2');
}