Accessing nested properties json - php

I have this json:
{"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}},
{"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \"novel\" mean as it is used in paragraph 8 of \"Turning Down a New Road\"? "}},
{"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}},
{"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}},
{"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]}
I need to get the properties of each element, but I can't get the property of second level, I mean I can´t know if the element is a "text","radiobutton","label", I have no problem with the propeties of third level.
This is my source:
$.ajax({
url: 'generateobject.php',
dataType: 'json',
type: 'GET'
}).done(function(data) {
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(anotherindex, secondLevel) {
alert(secondLevel[0]);//shows [object Object]
$.each(secondLevel, function(yetAnotherIndex, thirdLevel) {
//alert(thirdLevel.y+''+thirdLevel.y);
});
});
});
});
How do I get the property of second level?

Use Object.keys(data) and access the first item. If you run the snippet you should see the types alert as expected:
var data = {"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}},
{"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \"novel\" mean as it is used in paragraph 8 of \"Turning Down a New Road\"? "}},
{"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}},
{"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}},
{"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]};
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(anotherindex, secondLevel) {
alert(Object.keys(secondLevel)[0]);
$.each(secondLevel, function(yetAnotherIndex, thirdLevel) {
//alert(thirdLevel.y+''+thirdLevel.y);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Return array/object to jquery script from AJAX

Hello all and thanks in advance,
Short story, I am using a plugin to dynamically populate select options and am trying to do it via an ajax call but am struggling with getting the data into the select as the select gets created before the ajax can finish.
First, I have a plugin that sets up different selects. The options input can accept an array or object and creates the <option> html for the select. The createModal code is also setup to process a function supplied for the options input. Example below;
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
let dueDate = {};
for (let i = 1; i < 32; i++) {
dueDate[i] = i;
}
return dueDate;
}
}
});
What I am trying to do is provide an object to the options input via AJAX. I have a plugin called postFind which coordinates the ajax call. Items such as database, collection, etc. are passed to the ajax call. Functions that should be executed post the ajax call are pass through using the onSuccess option.
(function ($) {
$.extend({
postFind: function () {
var options = $.extend(true, {
onSuccess: function () {}
}, arguments[0] || {});
options.data['action'] = 'find';
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof options.onSuccess === 'function') {
options.onSuccess.call(this, obj);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
}
});
}(jQuery));
The plugin works fine as when I look at the output it is the data I expect. Below is an example of the initial attempt.
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
$.postFind({
data: {
database: 'dashboard',
collections: {
accountTypes: {
where: {status: true}
}
}
},
onSuccess: function (options) {
let dataArray = {};
$.each(options, function (key, val) {
dataArray[val._id.$oid] = val.type;
});
return dataArray;
}
})
}
}
});
In differnt iterations of attempting things I have been able to get the data back to the options but still not as a in the select.
After doing some poking around it looks like the createModal script in executing and creating the select before the AJAX call can return options. In looking at things it appears I need some sort of promise of sorts that returns the options but (1) I am not sure what that looks like and (2) I am not sure where the promise goes (in the plugin, in the createModal, etc.)
Any help you can provide would be great!
Update: Small mistake when posted, need to pass the results back to the original call: options.onSuccess.call(this, obj);
I believe to use variables inside your success callback they have to be defined properties inside your ajax call. Then to access the properties use this inside the callback. Like:
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
myOptions: options,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof this.myOptions.onSuccess === 'function') {
this.myOptions.onSuccess.call(this);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
It's not clear to me where the problem is without access to a functional example. I would start with a simplified version of what you want to do that demonstrates the proper functionality. My guess is the callbacks aren't setup exactly correctly; I would want to see the network call stack before making a more definitive statement. A few well-placed console.log() statements would probably give you a better idea of how the code is executing.
I wrote and tested the following code that removes most of the complexity from your snippets. It works by populating the select element on page load.
The HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select data-src='test.php' data-id='id' data-name='name'></select>
</body>
</html>
<html>
<script>
$('select[data-src]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-src'),
data: {'v0': 'Alligator', 'v1': 'Crocodile'}
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val (option[$select.attr('data-id')])
.text(option[$select.attr('data-name')]);
$select.append($option);
});
});
});
</script>
And the PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
echo json_encode([
[ 'id' => 0, 'name' => 'Test User 0' ],
[ 'id' => 3, 'name' => $_GET['v0'] ],
[ 'id' => 4, 'name' => $_GET['v1'] ]
]);
Here's a fiddle that also demonstrates the behavior.

Display JSON Data in HTML using Laravel 4

Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"

How recuperate data from GET method with ajax/jquery

Here is my function to get the data requested from a remote server. All is fine but one thing.
function get_users_request()
{
var result = [];
var idx=0;
$.get("getUsers_actions.php",
function(data) {
for (var key in data)
{
result[idx++]=data[key];
console.log(data[key].login);
}
},
"json");
return result;
}
The output is:
hissou
hbadri
user_1
But when i try to get get_users_request() result an empty array is given [].
Since it's an asynchronous call, you need to make use of a callback when you call the function:
function get_users_request(callback)
{
$.get("getUsers_actions.php", callback,"json");
}
get_user_request(function(data){
//var result = [];
//var idx=0;
//for (var key in data)
//{
// result[idx++]=data[key];
// console.log(data[key].login);
//}
$.each(data, function(k, v){
console.log(v.login);
});
});
To understand the code above, you could simulate an ajax call using a timeout:
var myAjaxResult;
setTimeout(function(){
myAjaxResult = 1; // try to update the value
}, 1000 /* simulates a 1 second ajax call */);
console.log(myAjaxResult); //undefined
Since console.log(myAjaxResult); isn't wrapped in a callback, it will be called immediately, and thus still be undefined.
If we would have waited for at least one second, the value would be set. But instead of presuming a time when the call is completed, we can make a callback function and know exactly when its done:
function myFunc(callback){
setTimeout(function(){
callback(1 /* returns the value 1 to the callback */);
}, 1000 /* simulates a 1 second ajax call */);
}
myFunc(function(callbackData){ //call the function using
//the callback we just specified
console.log(callbackData);
});
Hope this helps! Just let me know if anything is unclear.
This is what can give the result.
function get_users_request(s)
{
var s =new Array(), idx=0;
$.ajax({
url: "getUsers_actions.php",
success: function(data){
$.each(data, function(k, v){
s[idx++] = v.login;
console.log(v.login);
})
},
dataType: "json"
});
console.log(s);
}
You should put return result; after the for loop. The return should be done AFTER the $.get call is finished. Where is it now, the return is accessed right after the $.get call STARTS

Reading JSON from database into combobox using jQuery .each()

I need to be able to select a country in a selectbox, and then get all the states from that country.
I'm trying to do something like this: how-to-display-json-data-in-a-select-box-using-jquery
This is my controller:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
and my javascript:
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
success: function (data) {
console.log(data);
}
});
console.log shows me something like this:
["71","SomeState0"]["72","SomeState"]["73","SomeState2"]["74","SomeState3"]
So, what i need is to append all states in a new selectbox.
But I'm trying to read this array doing this in the success callback:
$.each(data, function(key,val){
console.log(val);
});
In the result, each line is a word, like this:
[
"
7
1
"
,
"
s
....
]
Why does that happen, and what am I missing?
JSON is not made of independent blocks. So this will never do:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
The output will be treated as text, and the iterator will loop the object's elements... which are the single characters.
You need to declare a list, or a dictionary. I have included some examples, depending on how you use the data in the jQuery callback. Note: PHP-side, you may also need to output the proper MIME type for JSON:
$states = array();
foreach($this->settings_model->get_state_list() as $state)
{
// Option 1: { "71": "SomeState0", "72": "Somestate2", ... }
// Simple dictionary, and the easiest way IMHO
$states[$state->CODSTA] = $state->STANAM;
// Option 2: [ [ "71", "SomeState0" ], [ "72", "SomeState2" ], ... ]
// List of tuples (well, actually 2-lists)
// $states[] = array($state->CODSTA, $state->STANAM);
// Option 3: [ { "71": "SomeState0" }, { "72": "SomeState2" }, ... ]
// List of dictionaries
// $states[] = array($state->CODSTA => $state->STANAM);
}
Header('Content-Type: application/json');
// "die" to be sure we're not outputting anything afterwards
die(json_encode($states));
In the jQuery callback, you specify the datatype and content type with charset (this will come in handy as soon as you encounter a state such as the Åland Islands, where a server sending data in ISO-8859-15 and a browser running a page in UTF8 can lead to a painful WTF moment):
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#comboId").get(0).options.length = 0;
$("#comboId").get(0).options[0] = new Option("-- State --", "");
// This expects data in "option 1" format, a dictionary.
$.each(data, function (codsta, stanam){
n = $("#comboId").get(0).options.length;
$("#comboId").get(0).options[n] = new Option(codsta, stanam);
});
},
error: function () {
alert("Something went wrong");
}
have you tried using $.map() instead?
http://api.jquery.com/jQuery.map/
$.map(data, function(index, item) {
console.log(item)
})
You should use GET not POST since you are not actually creating anything new serverside.
Read a bit about REST and why using GET is the proper noun here.
I've added a JSFiddle example that you can run straight away.
http://jsfiddle.net/KJMae/26/
If this is the JSON that the PHP service returns:
{
"success":true,
"states":[
{
"id":71,
"name":"California"
},
{
"id":72,
"name":"Oregon"
}
]
}
This is our HTML code:
<select id="country">
<option value="">No country selected</option>
<option value="1">USA</option>
</select>
<select id="states">
</select>​
This is what the code to add that to the select could look like:
// Bind change function to the select
jQuery(document).ready(function() {
jQuery("#country").change(onCountryChange);
});
function onCountryChange()
{
var countryId = jQuery(this).val();
$.ajax({
url: '/echo/json/',
type: 'get',
data: {
countryId: countryId
},
success: onStatesRecieveSuccess,
error: onStatesRecieveError
});
}
function onStatesRecieveSuccess(data)
{
// Target select that we add the states to
var jSelect = jQuery("#states");
// Clear old states
jSelect.children().remove();
// Add new states
jQuery(data.states).each(function(){
jSelect.append('<option value="'+this.id+'">'+this.name+'</option>');
});
}
function onStatesRecieveError(data)
{
alert("Could not get states. Select the country again.");
}​
As for the PHP, here's a simple example that should give the same result as JSON used in example above. (Haven't tested it, from top of my head, no php here.)
$result = new stdClass;
$result->states = array();
foreach($this->settings_model->get_state_list() as $state)
{
$stateDto = new stdClass();
$stateDto->id = $state->CODSTA;
$stateDto->name = $state->STANAM;
$result->states[] = $stateDto;
}
$result->success = true;
die(json_encode($result));

send a multidimensional array to php

I have an unknown number of inputs and i want to write them in a database. I tried some different ways but nothing worked. I dont know the number of the inputs, so i need something like a multidimensional array
javascript:
var temp=new Array();
var obj;
$("#mitarbFuktionen fieldset").each(function(){
i=$(this).parent().children().index($(this));
if ($(this).hasClass("New")){
temp[0]='New';
temp[1]=$("legend",this).text();
//.....
obj+=JSON.stringify(temp)
}else if ($(this).hasClass("Remove")){
temp[0]='Remove';
temp[1]=$("legend",this).text();
//.....
obj=$.toJSON(temp);
}
})
$.post("ajax/MitarbSave.php",{
anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
titel:$('#neuMitarbTitel').val(),
nation:$('#neuMitarbNat').val(),
//.....
'kom[]': obj
}, function(data){
alert(data);
})
PHP:
$output= json_decode($_POST["kom"], true);
echo var_dump($output);
Just to provide an answer to my comment:
$(document).ready(function()
{
var test = [];
test.push('a');
test.push('b');
$.post('ajax/script.php',
{
Param : test
},
function(resp)
{
}, 'json');
});
jQuery will automatically convert an array when passed as an param to an Ajax request, to a multi-dimensional array.
You could also just build an object, an pass that:
var obj={};
$("#mitarbFuktionen fieldset").each(function(){
var i=$(this).index();
obj[i]={};
obj[i][$(this).is(".New") ? 'New :' : 'Remove :'] = $("legend", this).text();
});
$.post("ajax/MitarbSave.php",{
anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
titel:$('#neuMitarbTitel').val(),
nation:$('#neuMitarbNat').val(),
kom: obj
}, function(data){
alert(data);
})​;​
just add the array to your input fields in HTML like:
<input type="text" name="neuMitarb[NUMBER][anrede]">
<input type="text" name="neuMitarb[NUMBER][titel]">
//...
So you let html create your array. Submitting your form like regular form submit with ajax

Categories