How to declare a variable in axios get json - javascript

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

Related

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

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
}

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.

Parsing json with php and javascript

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

response from php to javascript via json

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

POST'ing JSON with Codeigniter returns a 500 error

I'm having trouble returning data from my controller using an ajax post function. What happens here is the user will input a style number, submit that number to the controller. The controller grabs the value submitted, queries the database and returns the results to the controller then the controller returns an array that I then encode into json. But I keep getting a 500 Internal Server Error???
Here is my Controller
//return schools based on style id
public function search() {
$input = json_decode($this->input->post('obj'));
$style_id = $input['style_id'];
$parent_id = $input['parent_id'];
$data = array();
if ($q = $this->page_model->search_results($style_id, $parent_id)) {
$data = $q;
}
echo json_encode($data);
}
Here is my Model
//get all entries
function search_results($style_id, $parent_id) {
$options = array(
'Style' => $style_id,
'Parent_ID' => $parent_id
);
$this->db->select('*');
$this->db->from('pages');
$this->db->join('entry', 'pages.Page_ID = entry.Parent_Page_ID', 'inner');
$this->db->where($options);
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result();
}
}
Here is my javascript
//dress style search
$($searchBtn).click(function(event) {
var style_id,
parent_id,
obj = {};
//get the value of the input fields
searchVal = event.currentTarget.previousSibling.value;
parentID = event.currentTarget.parentElement.childNodes[3].value;
//The object to be passed to the controller
obj = { 'style_id' : searchVal, 'parent_id' : parentID };
//POST the values in json notation, return the search results in json notation
$.post(base_url + 'index.php/page/search',
obj,
function(data) {
console.log(data);
},
'json');
return false;
});
base_url=http://localhost:8888/lexsreg
BTW - If I comment out return false, I do get a json string echoed from my controller.
Thanks in advance!
You must include the csrf token. There are a few ways to do this, as explained in these two blogs.
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
http://codeigniter.com/forums/viewthread/176318/
Well, the first step is making sure that you're loaded page_model. Then I would make sure you're getting the right columns in the where clause -- do you need to identify those by <table-name>.?
Then basic CI debugging start with log_message: call log_message('DEBUG', $this->input->post('obj')); followed by log_message('DEBUG', json_decode($this->input->post('obj')));.

Categories

Resources