I need to get the json STRIPE API data converted into php - javascript

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
}

Related

How to declare a variable in axios get json

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)
})

When using POST with Fetch API to send user input to php file / Session variable it returns undefined array key

I'm trying to send user inputs with Fetch API to my php file using the POST method. I've tried this with XMLHttprequests and has no issue but now I want to start using Fetch API. When I use the GET method to send the variable to the $_SESSION array I have no problem and I can echo it out. When I use the POST method it would return always "Undefined array key" for the variables.
I'm new to this so any help is much appreciated.
PHP
<?php
// a sessions start
session_start();
// session variable
$number1 = $_POST['n1'];
$number2 = $_POST['n2'];
$_SESSION['numbers'] = $_POST;
echo $_SESSION['numbers']['n1'];
echo $_SESSION['numbers']['n2'];
?>
JS
document.getElementById('btn').addEventListener('click', addNumbers);
function addNumbers(){
var input1 = document.getElementById('one').value;
var input2 = document.getElementById('two').value;
fetch('serv.php',{
method:"POST",
body:'n1='+input1+'&n2='+input2,
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then((response) => response.text())
.then((data) => {
output.innerHTML += data;
})
}
I know that I should check if the Session variable is empty or isset but i removed it just for visibility purposes.
A print_r($_POST) output is :
Array ( )
A print_r($_SESSION) is :
Array ( [number2] =>
[num1] =>
[num2] =>
[numbers] => Array ( )
)

HTML sends message to PHP back-end and check the response

I am trying to send data from user end to server end: positionList.html <=> dbUpdate.php
issue seen on the developer console
The data format I am going to send is an array of self-defined Javascript objects. Here's one example: [{"position":"code testing","description":"junior"},{"position":"front end developing","description":"junior"}].
There are two objects in the array above, and each one is a self-defined JS object. The object definition is stated below, it has two properties:
function Entry(inpt1, inpt2) {
this.position = inpt1;
this.description = inpt2;
}
And then I used JSON.stringify method (JS array to JSON string) before $.post to the back end. msgPack is the array with two self-defined JS objects in it. From the developer tool, I could see the JSON string looks normal and the data I received back from the server was a JS string. But console.log(data) doesn't show anything and JSON.parse(data) reports an error.
let myJson = JSON.stringify(msgPack);
let url = "dbUpdate.php";
$.post(url, myJson, function(data){
console.log("getting data back...");
console.log('type of data is: ' + typeof(data));
console.log("data: " + data);
alert(JSON.parse(data));
});
The server side's code is listed below:
<?php
require_once 'pdo.php';
$data = isset($_POST)? $_POST:'nothing here';
foreach($data as $obj) {
echo( json_encode($obj['position']));
}
/*
foreach($data as $obj) {
foreach($obj as $k => $v) {
echo "json_encode({$k} => {$v})";
}
}
*/
?>
I tried several ways to extract the data from the front-end, but it seems the data was not recognized.
var_dump, print_r didn't help either.
My questions are:
Any suggestions regarding the AJAX communication? Is the problem happening at the back-end side? It couldn't get any information from $_POST.
How does PHP back-end know there's a message coming and what methods do we developer have to check that Other than isset($_POST)? My concern is the front-end could send multiple data with different contents.
Thanks.
You can directly send array in the post request by setting it to a key positions and access it in backend via same key. Make sure you send json back so the front end also do a parsing.
let myData = { positions: msgPack};
let url = "dbUpdate.php";
$.post(url, myData, function(data){
console.log("getting data back...");
console.log('type of data is: ' + typeof(data));
console.log("data: " + data);
alert(JSON.parse(data));
});
While in php
<?php
require_once 'pdo.php';
if(isset($_POST['positions'])){
echo json_encode($_POST['positions']); die;
}
else{
$response = [ 'error' => 'No input specified'];
echo json_encode($response); die;
}
?>

How to avoid wrapping PHP result into another array?

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.

Cant get PHP variables using AJAX

I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).
main.php
include ('databaseQueries.php');
if (isset($_POST["points"])){
$points = json_decode($_POST["points"]);
if($_POST["execute"] == 1){
}
}
$advert= array(
'Hello' => 'Hello world!',
'bye' => 'Why bye?',
);
echo json_encode($advert, $another);
pageJs.js
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
databaseQueries.php
$another = "another string";
If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.
What I'm doing wrong and how can I get both the $test array and $another variable?
Thank's in advance!
You are using json_encode incorrectly. From the documentation:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
You are trying to send $another to the function as the options parameter.
You could do something like this:
$ret = array($advert, $another);
echo json_encode($ret);
Unless I'm completely wrong, I can't see where you're sending anything TO your post
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json'
// I would expect a data call here, something like:
data: $(form).serialize(), // OR { points: 3, execute: 1 }
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
I assume that you want to spit back some results with the format of result->key;
So Keeleon's answer above is good:
$ret = array($advert, $another);
echo json_encode($ret);
But you can also do:
//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);
Hopefully, this answers your questions.

Categories

Resources