A front-end developed is sending a array of data formated as a JSON object with an Ajax call.
The json object looks like this:
{
"name": " Test Name ",
"image_url": "test URL",
"include": [
"1"
],
"dimension": [
null
],
"media_type": [
null
],
"match": [
"1"
],
"content": [
"test content"
],
"sorting": {
"rating": "50",
"language": "50",
"CS Weight": "50",
}
}
How I can read it in my PHP controller. Can I just get it just this way:
$data = $_POST;
Because the variable that contains the JSON object in this case has no name, I cannot get it this way
$data = $_POST['data']
Edited Part
From the front-end, the data is sent this way:
sendAjax: function(value, url, callback){
xhr = $.ajax({
type: 'POST',
url: url,
data: value
}).done(function(message){
callback(message);
}).fail(function(jqXHR, textStatus){
console.log('failed to submit form, error type: '+textStatus);
});
}
Read it from the script's input, which is where you can get the "raw" POST data:
$json = file_get_contents('php://input');
$data = json_decode($json);
This should work assuming you're using jquery on your front end. Just paste this into your javascript console and run it (make sure you replace the path with your web address. The parameters should come through correctly.
data = {
"name": " Test Name ",
"image_url": "test URL",
"include": [
"1"
],
"dimension": [
null
],
"media_type": [
null
],
"match": [
"1"
],
"content": [
"test content"
],
"sorting": {
"rating": "50",
"language": "50",
"CS Weight": "50",
}
}
$.ajax({url:'/YOUR/PATH/HERE', data: {data: data}, type: 'post', dataType: 'json'})
Occurred to me after posting, are you asking how do you parse the JSON once received or how to get it to show in the $_POST hash?
Related
I have below code which is going to invoke REST endpoint and return response back. I just tried to print the response.body in the console and It works perfectly fine.
var express = require('express');
var app = express();
var PORT = 8001;
var request = require('request');
var HashMap = require('hashmap');
var endPoint="http://sandbox.dev.amazon.com/idsearch/environment/amazon/";
app.get('/productId/:proId',async (req,res) => {
try
{
var headers ={
"accept":"application/json"
}
var options = {
url:endPoint.concat(req.params.proId),
headers:headers
}
request(options, (error,response,body)=> {
console.log(response.body) // It returned response as below output JSON file
res.send("STATUS CODE : 200");
});
}
catch(error)
{
throw error;
}
});
Output:
{
"<Some dynamic Content>": {
"type": "PROD-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
}
The above output contains all the responses with respective Endpoint URL which is expected. But I just want to fetch only the object contains "Status: 1". I'm just wondering that How can I manipulate the response.body object to get the below JSON as output.
Expected Output:
{
"callSummary":[
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
]
}
I just want to iterate the response.body obj and check the status as 1 if it's then I need to fetch all the details and form it as above payload. This is dynamic content but the template format is static.
I tried the below code to iterate the response.body but no luck.
var string = JSON.stringify(response.body);
var objectValue = JSON.parse(string);
var obj = objectValue.callSummary;
console.log(obj.length); // It returned undefined.
Please lead me to achieve this.
To return that json, just
res.json(response.body['<Some dynamic Content>'].callSummary);
Adding some validation and error handling would be a good idea before sending the response.
In case your key is just an example and you never know your first key value, and you always want the values of the first key
res.json(Object.values(response.body)[0].callSummary);
Object.values returns an array, so you can iterate the values if you want manage more than the first one
I have the following json which is returned by Influxdb which I can decode with PHP with out any issue i.e I use the following code:
$json_result = json_decode($json_result, true);
$http_result_series_0 = $json_result["results"][0]["series"][0] ["values"][0][5];
Now I would like to do the decoding with javascript in order to dynamically fill a table. But no matter how I try to do it, it's not working. I know that there's a similar way in javascript to decode the Array i.e:
json_result.results[0].series[0].values[0][5]
The json:
"{
"results": [
{
"statement_id": 0,
"series": [
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://twitter.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:12Z",
"xps",
200,
"GET",
1.358607871,
"success",
0,
"success",
"200",
"test.com",
"LTE"
]
]
},
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://google.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:10Z",
"xps",
301,
"GET",
0.051518655,
"success",
0,
"success",
"301",
"test.com",
"LTE"
]
]
},
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://amazon.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:11Z",
"xps",
301,
"GET",
0.536477796,
"success",
0,
"success",
"301",
"test.com",
"LTE"
]
]
}
]
}
]
}
"
What I'm doing wrong? Every help is appreciated. Thanks!
EDIT:
The Influxdb API returns a pretty formated JSON. Currently I output the whole JSON with:
var json_result = '<?php echo $javascript_json_result;?>';
document.getElementById("jsonoutput").innerHTML = JSON.parse(json_result);
which outputs the whole json. But I would like to output only single values.
document.getElementById("jsonoutput").innerHTML = json_result.results[0].series[0].values[0][5]
trhows the following error:
e2e_check_new.php:172 Uncaught TypeError: Cannot read property '0' of undefined at e2e_check_new.php:172
What I'm doing wrong?
var json_result = '<?php echo $javascript_json_result;?>';
You are trying to output the JSON as a string in JavaScript by wrapping it in ' but you aren't escaping any of the characters in the JSON which have special meaning in JavaScript (like \ or a new line or ' - it looks like you definitely have at least new lines in your JSON).
Don't try to generate a string of JSON. Just output the JSON directly so it will be treated as a JavaScript object literal.
var my_object = <?php echo $javascript_json_result; ?>;
document.getElementById("jsonoutput").innerHTML = my_object;
… of course, this will convert the object to the string [Object object] which isn't useful. You can deal with the data structure in the usual ways though (i.e. access properties etc).
I'm quite new javascript and am having trouble extracting data from an ajax request before loading to a webpage.
The data from the ajax request is something like:
{
"success": {
"user1": [
["2018-01-30", {
"Type": "None",
"Body": "Message 2"
}],
["2018-01-29", {
"Type": "None",
"Body": "Message 1"
}]
],
"user2": [
["2018-01-28", {
"Type": "None",
"Body": "Message 2"
}],
["2018-01-27", {
"Type": "None",
"Body": "Message 1"
}]
],
"user3": [
["2018-01-26", {
"Type": "None",
"Body": "Message 2"
}],
["2018-01-25", {
"Type": "None",
"Body": "Message 1"
}]
]
}
I can extract the Type and Body data using the below code, Which lists all the items out on the webpage.
$.ajax(
{
url : '/ajax_get_messages',
type: "GET",
dataType : 'json'
}).done(function(messages)
{
$.each(messages.success, function(index, message)
{
$('#messages').append(`
<div class='message'>New Sender`)
$.each(message, function(index, item)
{
$('#messages').append(`
<p>Date: ${item[0]} | Type: ${item[1]['Type']} | Body: ${item[1]['Body']}</p>
</div>`)
});
});
})
What I'm struggling to do is get the user's names user1, user2 etc and put it in place of `New Sender', so all the messages from a user are grouped together in it's own div. I've looked at Object.keys but that didn't seem to be correct for this.
I'm also aware that the appending to the html isn't working correctly because of the $.each(message, function(index, item) in the middle. Is there a way around this?
The JSON you provided is invalid, but I cleaned it up. You should be able to use the index in the first loop to get the name:
Here's an example
You can always console.log the current element in any loop to see exactly what's available to you
i wondering if there any solution to get data from json in this format:
{ "#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">":[{"id":68,
"name":"johnny",
"description":"Hello my first Description",
"created_by_user_id":16530,
"created_at":"2016-01-28T13:17:51.827Z",
"updated_at":"2016-01-29T10:40:40.011Z",
"receiver_group_id":3,"dynamic_fields":{
"files":[
{
"id":2,
"date":"2016-01-29T10:40:35.720Z",
"path":"http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public":null
}
]} }]}
like i want to have a name and description. but if i call in ajax like this:
$(function(){
$.ajax({
url: './dataModel.json',
dataType: 'json',
method: 'GET',
success: function(data){
console.log(data[0].name);// error name is not defined
console.log(data.name); // undefined
}
});
})
may be you guys have some idea how can i get the name and description? thank you so much for any kind of suggestion and idea.
best regard,
ape
Try this:
var input = {
"#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">": [{
"id": 68,
"name": "johnny",
"description": "Hello my first Description",
"created_by_user_id": 16530,
"created_at": "2016-01-28T13:17:51.827Z",
"updated_at": "2016-01-29T10:40:40.011Z",
"receiver_group_id": 3,
"dynamic_fields": {
"files": [{
"id": 2,
"date": "2016-01-29T10:40:35.720Z",
"path": "http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public": null
}]
}
}]
};
var output = Object.keys(input).map(function(key) {
return input[key];
})[0];
alert(output[0].name);
I have the following ajax request...
Ajax
function initUpdate()
{
var id = $(this).attr('id').split('_')[1];
//grab id from link update_xxxx
//get all gallery information
$.ajax(
{
type: 'POST',
url: 'ajax/update',
data: {"id": id},
dataType: 'json',
success: function(json)
{
//query was successful now populate form
$("input[name='galleryName']").val(/*what goes here?*/);
}
});
}
That returns the following data
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
}
]
}
How would I access "name" to insert in the val()?
Thanks!
What have you tried? I would think you could get to it via:
json.selected_gallery[0].name
selected_gallery is a JavaScript array, so you would access the first item in the collection using [0] in order access the first item's properties.
UPDATE
You could access other items in the array if they existed:
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
},
{
"id": "5005",
"name": "blah",
"clientRef": "405",
"clientName": "Dave "
},
{
"id": "6006",
"name": "boo",
"clientRef": "605",
"clientName": "Doug"
}
]
}
To get the second item in the array, you'd reference it as:
json.selected_gallery[1].name (or id or clientRef or ...). You can get to the third item via json.selected_gallery[2].name.
Hope this helps.