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
Related
I am trying to upload my intent everything is working fine, i am writing script in V2 and everything works but for parameter webhookState data type is enum ( [here] ) and we have to enter following of the three values ( [here][1]) now when i enter any one and try to upload it shows.
" Unable to load file: SyntaxError: Unexpected token W in JSON at position 98 "
now when I pass WEBHOOK_STATE_ENABLED(or any one) in quotes code uploads successfully (because as per my knowledge it treats it as string and gets executed) and intent is created for my agent but webhook remains off and also training phrases are not there, i am certain that the parameter webhookState is not being activated when i pass in quotes(because of above mentioned reason) Same is the case with rest, like when i try to put in type of training phrases.
{
"name": "Warehouse_Management",
"displayName": "Warehouse_Management",
"webhookState": "WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING" ,
"priority": 50000,
"isFallback": false,
"mlDisabled": false,
"trainingPhrases": [
{
"name":"Try1" ,
"type": "EXAMPLE",
"parts": [
{
"text": "for",
"userDefined": true
},
{
"text": "warehouse",
"entityType": "#Properties",
"alias": "Properties",
"userDefined": true
},
{
"text": "management",
"userDefined": true
}
]
},
{
"name":"Try2" ,
"type": "EXAMPLE",
"parts": [
{
"text": "i want app for ",
"userDefined": true
},
{
"text": "warehouse",
"alias": "Properties",
"entityType": "#Properties",
"userDefined": true
}
]
}
],
"outputContexts": [
{
"name": "Yes",
"lifespanCount": 2
},
{
"name": "No",
"lifespanCount": 2
},
{
"name": "Device_Integration",
"lifespanCount": 2
}
],
"resetContexts": false,
"parameters": [
{
"name": "Properties",
"displayName": "Properties",
"value": "$parameter_name",
"entityTypeDisplayName": "#Properties",
"mandatory": false,
"isList": true
}
],
"messages": [
{
"text":"This is sample response"
}
],
"rootFollowupIntentName": "root",
"parentFollowupIntentName": "parent"
}
Please NOTE that in the attached Json i have put it in quotes so it would get successfully executed and will create intent.
In order for it to be valid JSON, the enum value should be wrapped in quotes. It's expecting the enum value as a String.
I am trying to access the card json value, to no avail.
In my scenario, I am asking the bot about "weather in London" and it replies back with "It is currently 9 degrees celcius in London." via the webhook.
Which is correct and dynamic.
However, I am trying to also pass the values to a card too.
In the json reply, I do get the card as so
{
"id": "REMOVED",
"timestamp": "2017-12-05T11:10:52.033Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "weather in london",
"action": "sayWeather",
"actionIncomplete": false,
"parameters": {
"geo-city": "London"
},
"contexts": [],
"metadata": {
"intentId": "REMOVED",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 626,
"intentName": "Weather"
},
"fulfillment": {
"speech": "It is currently 9 degrees celcius in London.",
"source": "agent",
"displayText": "It is currently 9 degrees celcius in London.",
"messages": [
{
"type": 0,
"speech": "It is currently 9 degrees celcius in London."
}
],
"data": {
"items": [
{
"simpleResponse": {
"textToSpeech": "This is the first simple response for a basic card"
}
},
{
"basicCard": {
"title": "Title: this is a title",
"formattedText": "This is a basic card. Text in a\n basic card can include \"quotes\" and most other unicode characters\n including emoji 📱. Basic cards also support some markdown\n formatting like *emphasis* or _italics_, **strong** or __bold__,\n and ***bold itallic*** or ___strong emphasis___ as well as other things\n like line \nbreaks",
"subtitle": "This is a subtitle",
"image": {
"url": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
"accessibilityText": "Image alternate text"
},
"buttons": [
{
"title": "This is a button",
"openUrlAction": {
"url": "https://assistant.google.com/"
}
}
]
}
},
{
"simpleResponse": {
"textToSpeech": "This is the 2nd simple response ",
"displayText": "This is the 2nd simple response"
}
}
]
}
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "REMOVED"
}
Accessing the value of speech using data.result.fulfillment.speech works fine.
However, when using data.result.fulfillment.data.items.basicCard.image.url it just doesnt work. And if I go up several levels, I do get:
[object Object]
Your help is appreciated.
The items attribute is a list and not an object. As such, you'll have to use a numerical index to retrive the data. In the example you provided the index of the basicCard object is second so your code should look something like this:
data.result.fulfillment.data.items[1].basicCard.image.url
Notice the [1] after items.
Bear in mind that if the order of this list changes you may no longer be retrieving a basicCard object so you may want to add some checking to make sure you're retrieving the data you want.
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);
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?
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.