Parsing json with php and javascript - 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)
}

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

How return array in function() to javascript on wordpress ajax.php with following code:

it may seem stupid, but i'm in it for a week, help me ...
the "response" in xhr dev-tools chrome does not leave "0", it never returns the array I need ...
Javascript code to get data from wordpress
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
$.post("wp-admin/admin-ajax.php", { getHomeSliderSeries: id }, function (html) {
var data = jQuery.parseJSON(html);
if (data.status == "success") {
var listing = data.list;
var lister = [];
for (var i = 0; i < 20; i++) {
var row = listing[i];
lister.push(seriePoster(row.url, row.rating, row.poster, row.title, row.cat, row.episode));
}
$list.parent(".itemsList").addClass("fadingOut");
setTimeout(function () {
$list.html(lister.join(""));
$list.trigger("destroy.owl.carousel");
createItemSlider();
$list.parent(".itemsList").removeClass("fadingOut");
}, 200);
} else {
return false;
}
});
});
PHP file to return data in array json to javascript show results in html.
wp-admin/admin-ajax.php (theme/inc/core/ajax.php)
function getHomeSliderSeries(){
// i Want see that bellow in xhr response to javascript:
//{"status":"success","list":{}}
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );
My language is not very good, i hope you undestand, thanks atentiton!!
Try ajax callback function in functions.php
function swt_ajax_data() {
$id = isset($_POST['id']) ? $_POST['id'] : '';
// Create an associative array for the response.
$responsedata = array(
'id' => $id,
);
$result = array();
// if need featch the data from the template un comment the bellow five lines and commented the sixth line
//ob_start();
//include('templatepatj');
//$opr_html .= ob_get_contents();
//ob_get_clean();
// $result['data'] = $opr_html;
$result['data'] = $responsedata;// POST array data.
}
return wp_send_json_success($result);
}
}
add_action('wp_ajax_swt_ajax_data', 'swt_ajax_data');
add_action('wp_ajax_nopriv_swt_ajax_data', 'swt_ajax_data');
Localize your script and pass the admin ajax url
// Register the script
wp_register_script( 'ajax-script', 'path/to/myscript.js' );
// Localize the script with new data
$js_array = array(
'ajaxurl' => admin_url('admin-ajax.php'),
);
wp_localize_script( 'ajax-script', 'swtobj', $js_array );
// Enqueued script with localized data.
wp_enqueue_script( 'ajax-script' );
Try Js as like below.
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
var data = {
'action': 'swt_ajax_data', 'id': id
};
$.ajax({
url: swtobj.ajaxurl,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function (response, textStatus, jqXHR) {
var response_data = response.data.data;
if (response_data != "" || response_data.length != 0) {
console.log(response_data);
// write your code here
} else {
// write your code here
}
},
});
});
The data you send in $.post is missing an action property. This property is responsible for telling the admin-ajax.php which function that is registered with a wp_ajax_{function_name} hook should be called.
The value in the action property should match the function_name in wp_ajax_{function_name} and wp_ajax_nopriv_{function_name} to be called properly.
Combine the action property with other properties that you want to send to the backend to pass the data that you need to send.
// Set the action and get the id.
var action = 'getHomeSliderSeries';
var id = $(this).attr("data-show-home-list-series");
// Create object to send data to backend.
// This must include an action property with
// the name of the function on the backend.
var postData = {
action: action,
id: id,
example: 'Send any data as a property. You can also nest objects and arrays.'
};
$.post("wp-admin/admin-ajax.php", postData, function(response) {
if (response.status == "success") {
console.log(response);
}
}, 'json'); // Expect JSON from the backend. Now you don't need to parse.
Now on the server side your getHomeSliderSeries should be called. All the other properties (action included) can now be accessed through the global $_POST variable with their corresponding keys.
For a response, create an associative array with the data you want to return. This is the equivalent of an object in JavaScript. Encode the array to JSON and send it back. Now the frontend should see an object as a response.
function getHomeSliderSeries(){
// Get the id from the post request.
$id = isset($_POST['id']) ? $_POST['id'] : null;
$example_string = isset($_POST['example_string']) ? $_POST['example_string'] : null;
// Create an associative array for the response.
$response = array(
'status' => 'success',
'id' => $id,
'example' => $example_string
);
// Return the array as a JSON string.
return json_encode($response);
// Cuts connection by stopping the function.
die();
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );

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.

convert from PHP to JSON file

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

jQuery AJAX send search criteria to PHP return JSON

I am trying to send a group of variables to a PHP script via AJAX.
Typically, this is what I'd do:
$('.submitSearch').on('click', function()
{
var rep = $('#rep').val();
var num = $('#num').val();
var uid = $('#uid').val();
// and so on
// then I could send each variable to a PHP script
$.post('api/summary.php', {rep: rep, num: num, // and so...}, function(data)
{
console.log(data);
});
});
That's how I'd normally do it.
But now, I am trying send all of the parameters in a single variable I calling searchCriteria, as follows:
$('.submitSearch').on('click', function()
{
var searchCriteria =
{
rep: $('#rep').val(),
num: $('#num').val(),
uid: $('#uid').val(),
// and so on...
}
// then send them to the php script
$.post('api/summary.php', searchCriteria, function(data)
{
console.log(data);
});
});
Then, in the PHP script, retrieve all of the parameters from the variable for processing:
<?php
if($_POST['searchCriteria'] == true)
{
// get the parameters
// build the query
// return JSON
}
?>
My question is: How do I get all of the parameters out of $_POST['searchCriteria'] in the PHP script?
Try wrapping it in a bigger object like this :
Javascript :
$('.submitSearch').on('click', function()
{
var searchCriteria =
{
rep: $('#rep').val(),
num: $('#num').val(),
uid: $('#uid').val(),
// and so on...
}
// then send them to the php script
$.post('api/summary.php', {searchCriteria : searchCriteria }, function(data)
{
console.log(data);
});
});
PHP :
<?php
if($_POST['searchCriteria'] == true)
{
$searchCriteria = json_decode($_POST['searchCriteria']);
// Now you can for each loop throught it for example
foreach($searchCriteria as $key => $value) {
// Do something
}
}
?>
If you want everything in a single $_POST parameter, you need to wrap in another object:
$.post('api/summary.php', {searchCriteria : searchCriteria }, function(data) {
...
});
In the PHP, you would then access them as nested arrays.
$sc = $_POST['searchCriteria']
$rep = $sc['rep'];
$num = $sc['num'];
$uid = $sc['uid'];
I'm not sure what you expect to gain by adding this extra level of wrapping.

Categories

Resources