So I built an array of objects for passing to PHP, but I am wondering wether this is the cleanest way to pass them and will be the easiest to deal with in PHP.
I am partly thrown off by the fact that the number of group components are variable based on what my google maps reverse-geocoder returns.
Each group will be inserted as a separate row into MySql with the parameters of 'name' and 'type'
var neighborhood = extractLongFromAddress(results[0].address_components, "sublocality");
var town = extractLongFromAddress(results[0].address_components, "locality");
var stateShort = extractShortFromAddress(results[0].address_components, "administrative_area_level_1");
var stateLong = extractLongFromAddress(results[0].address_components, "administrative_area_level_1");
var country = extractLongFromAddress(results[0].address_components, "country");
var groups=[];
if(town && stateShort){
groups.push({name: town+", "+stateShort,
type:"city"
});
}
if(neighborhood && stateLong){
groups.push({name: neighborhood+", "+stateShort,
type:"neighborhood"
});
}
if(stateLong){
groups.push({name:stateLong,
type:"state"
});
}
if(country){
groups.push({name:country,
type:"country"
});
}
console.log(groups);
sincere thanks for any help. It is greatly appreciated.
Just convert the array to a JSON string by JSON.stringify() and send it to php; In PHP you'll do json_decode()
Related
I want to extract Lat/Long values from the below mentioned array. Please help me.
var products = {"PolygonCords":"[[51.65040675460229,0.034332275390625],[51.613752957501,0.028839111328125],[51.61034179610213,0.1812744140625],[51.642737480428536,0.157928466796875]]"};
Parse the json string using JSON.parse() and iterate over array using forEach
var products = {
"PolygonCords": "[[51.65040675460229,0.034332275390625],[51.613752957501,0.028839111328125],[51.61034179610213,0.1812744140625],[51.642737480428536,0.157928466796875]]"
};
JSON.parse(products.PolygonCords).forEach(function(v) {
console.log(v[0], v[1])
})
I'm trying to set up a comments system on photos.
I understand how to use $.getJSON when the array is like this:
get.php:
$var = 5;
echo json_encode(array('var'=>$var));
main.php:
$.getJSON("get.php",function(data){
number = data.var; // number = 5
});
But I have a more complex thing.
My comments table has these 4 columns: id | photo_id | comment | date
For example let's say we're trying to retrieve the comment data from the photo with
photo_id == 1.
We don't know how many comments there might be.
In getcomments.php:
$photoid = 1;
$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");
while($commentrow = $comment->fetch_assoc()) {
$comments[] = $commentrow;
}
Then you encode it:
echo json_encode($comments);
Which prints something like this (the photo has 2 comments):
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
How do I declare variables for the comments array?
$.getJSON("getcomments.php",function(data){
// how do I declare variables for the comments array, especially since you don't know how many there might be?
});
Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.
If you want to display the comments you need to loop over the array. You can use for loop or forEach function.
$.getJSON("getcomments.php",function(data){
data.forEach(function(comment) {
$('div').append('<span>' + comment.comment + '</span>');
});
});
To display two JSONs you need to combine them into one JSON object.
echo json_encode(array('img' => $img1link, 'comments' => $comments));
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
Using this JSON, data is an array and you should manage it as an array. You can loop through it using simple loops (for, while...) or using new functional methods like forEach, map, filter....
Please try with this example:
$.getJSON("getcomments.php",function(data){
data.forEach(function(item, index, all) {
console.log(item.comment);
});
});
Declare an object, and push it to the array.
var commentsArr = [];
for (var i = 0; i < data.length; i++) {
var objToPush = {
id: data.id,
comment: data.comment,
date: data.date
}
commentsArr.push(objToPush);
}
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
I get data is undefined, i guess i can't ['productId'] in an array, but i think i need this structure in the json, i tried a couple of variation but it never was, what i needed
i just want to send a json via ajax.
jQuery(':checked').each(function(i){
data[i]['productId'] = jQuery(this).parent().find('.productId').val();
jQuery(this).parent().find('.attrGrp').each(function(j){
data[i]['attrGrps'][j]['uid'] = jQuery(this).find('.active').attr('id');
data[i]['attrGrps'][j]['amount'] = jQuery(this).parent().find('.amount').val();
});
});
jQuery.post(newSession, {json: data.serializeArray()});
is there any better way for doing it? or how can i make it work?
help appreciated ;/
You need to initialize arrays and objects before using them. String indexes are only possible with objects. Try this:
var data = [];
jQuery(':checked').each(function(i)
{
data[i] = {};
data[i].productId = jQuery(this).parent().find('.productId').val();
data[i].attrGrps = [];
jQuery(this).parent().find('.attrGrp').each(function(j)
{
data[i].attrGrps[j] = {};
data[i].attrGrps[j].uid = jQuery(this).find('.active').attr('id');
data[i].attrGrps[j].amount = jQuery(this).parent().find('.amount').val();
});
});
Alternatively you could use jQuery().serialize, post everything in the form and sort it out on the server.
I am not totally familiar with javascript, jquery.
I am trying to do the following. Note a-f are names for the dropdown menus. Can someone help clarify? thanks
var a_params = $("#a").serializeArray();
var b_params = $("#b").serializeArray();
var c_params = $("#c").serializeArray();
var d_params = $("#d").serializeArray();
var e_params = $("#e").serializeArray();
var f_params = $("#f").serializeArray();
params.push({ name: 'menu_mode', value: '2-1' });
$.get("./scripts/model.cgi", a_params,b_params,c_params,d_params,e_params,f_params, function(data){
$("#grapharea").html(data);
$("#prog").html(" ");
});
More Comments: in the cgi script i am dumping the inputs to see if i am receiving the values from the a-f_params but this isn't the case. Any ideas why?
You have to create 1 array(or jquery-object in this case) from all object's, and serialize this array.
$('#a,#b,#c,#d,#e,#f').serializeArray();
But this is only needed, if you dont want to serialize e.g. all input-fields.
Otherwise you can use simply
$('#form').serializeArray();