Loop through an array with objects - javascript

I get the following array from my back end:
[Object { 7="77.105.239.8", 10="77.105.239.11", 18="77.105.239.19", more...}]
How can I use ng-options to fill my select dropdown with the Ips from the array?
The array above Is the result of an array_diff from my back end In PHP:
foreach($ips as $ip)
{
$taken[] = $ip['ip'];
}
$start = (ip2long($serie->net) + 1);
$antal = pow(2,(32-$serie->mask));
for($i = $start; $i < ($start+$antal-3); $i++)
{
if(end(explode(".", long2ip($i))) != "0")
{
$possible_ips[] = long2ip($i);
}
}
$poss = array_diff($possible_ips, $taken);
return $poss;

If you don't want to or cannot fix the data to be formatted like m4lt3 answer, then you need to do some preprocessing of the data before trying to bind it.
var originalData = [{ 7: "77.105.239.8", 10: "77.105.239.11", 18: "77.105.239.19"}];
var originalObject = originalData[0];
var newData = [];
for (var i in originalObject) {
newData.push({'id': i, 'ip': originalObject[i]});
}
$scope.ipList = newData;
...then you could bind ipList using ngOptions.

I think you can leave your function as is, except change the return statement to: return json_encode($poss);

Actually you are getting an array with only one field which contains an object with the data you need.
My suggestion is, to fix that in the backend. So that you get what you need -> a real array. Like this:
[
{ "id":7, "ip":"77.105.239.8"},
{ "id":10, "ip":"77.105.239.150"},
{ "id":12, "ip":"77.105.239.12"}
]
Since array_diff returns an assoziative array, we need to transform it to a non-assoziative array and return it (either with json_encode or not, depending on you set up):
...
$poss = array_diff($possible_ips, $taken);
$res = [];
foreach ($poss as $key => $value) {
$res[] = $value;
}
return json_encode($res);

Related

make an array with the values of similar keys from JSON array

I have an array in JSON array format. I want to extract the values of common keys and make a new array with this.
I've tried this
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
where sale_date and total are the keys.
but this code returned an array of undefined objects.
my array named data looks like
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
I'm expecting two arrays date[2017-12-26 11:05:05, 2017-12-26 11:05:18 ] and amt[500, 500]
I'm getting data as a ajax response From the code below.
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data = $row;
print json_encode($db_data);
}
}
And this how my ajax request looks like
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});
var data = [
{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}
];
var date = [];
var amt = [];
for(var i in data){
console.log(i);
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
PHP Code :-
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$data = array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data[] = $row;
}
}
echo json_encode($db_data);
Ajax Request :-
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
data = JSON.parse(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});
You need to encapsulate your object between array
var data = [{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
var date = [];
var amt = [];
for(var i=0;i<data.length;i++){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
This is not a JavaScript but PHP issue.... you are sending invalid JSON. The following:
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
Should actually look like:
[{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
You need to change your PHP code to this:
// Add content type so that jQuery knows you're sending JSON
header("Content-Type: application/json");
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$db_data = array();
while ($row = $result->fetch_assoc()) {
$db_data[] = $row;
}
echo json_encode($db_data);
Sending Content-Type header should be enough but you should also change your jQuery code just to be sure:
$(document).ready(function() {
$.post("ajax-req-handler.php", {
key: "draw-line-chart"
}, function(data) {
console.log(data);
var date = [];
var amt = [];
for (var i in data) {
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
}, "json");
// the 4th parameter is dataType set to json
});
//Hope this will be of help.
var data = [ {"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"} ];
var date = amt = [];
X = 0;
while (x < data.length) {
date.push(data[x].sale_date);
amt.push(data[x].total);
x++;
};
console.log(date);
console.log(amt);
Explanation:
line 1 is the array of objects which represent the data u are pulling from ur json data.
Line 2 is the declaration of the two variable arrays which is assigned to and empty array. So, I used the short form of declaring multi-variable on the same line of statement.
Line 3 is the initialization of the counter "x" that will help break the While Loop once the it counts to the last Object in the array "data".
Line 4. Then the While Loop which keep iterating through the array " data". The conditional statement there always check if the counter "x" is < (less than) the length of the array In each iteration it.
Line 5. In the While Loop block code using the counter "x" as index of the array to access the property "sale_date" of the object in that array index and push it to the array "date" (I.e adding it at the end of the array "date").
Line 6. The same as line 5, accessing the property total in that index of the array " data" and push it to array "amt".
Line 7 increment the counter " x" by 1 and assign it to back to x which is used to reevaluate the While Loop.
Line 8 & 9 is just a console log that displays what's in date and amt respectively.
Thanks
Hope this makes sense to u... Please, Let me know your feedback.

Create an associative array in jquery using php array

I need to create an assosiative array in jQuery from PHP.
Here is my script so far. selectedStoresDict is json encoded array with values ["Lahore", "Islamabad"]
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = {};
for( i = 0 ; i <= selectedStores.length; i++) {
data['id'] = i;
data['text'] = selectedStores[i];
}
console.log(data, "Hello, world!");
However my console is showing that its not an array. I want something like this:
[{ id: 1, text: 'Lahore' }, { id: 2, text: 'Islamabad' }]
I think this should be a JS question instead of a PHP one, but here you have. You were almost there:
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = [];
for( i = 1 ; i <= selectedStores.length; i++) {
data.push({
id: i,
text: selectedStores[i]
});
}
console.log(data, "Hello, world!");
An array in JS is represented with [], so you need to initialize it like that, then just push the info (in this case, and object with keys and values). Also for ids starting with 1, you must initialize i = 1.
No need to loop thru.
Just json_encode the array
<?php
$selectedStoresDict[] = array("id"=>1,"text"=>"Lahore");
$selectedStoresDict[] = array("id"=>2,"text"=>"Islamabad");
?>
<script>
console.log('<?php echo json_encode($selectedStoresDict); ?>');
</script>

Jquery post a Array

I am having a Array which is generated by my Javascript in run time.
once that array is full with all the values I want to send it using POST to the server.
How can I do that ...
Pseudo code:
for(i=0;i<result.data.length;i++)
{
result.data[i].id
}
$.post("receiver.php", { xxxxx }, function(data){ console.log(data);});
How can I get that xxxx updated in the post
I checked the documentation in jquery but they are expecting to give all the values in POST.I do not want to do that.
Also, I want to send post only once so that traffic will be less.
EDIT
You can use join() to get all your array values converted to a string, using some char to separate it.
EDIT 2: As Kumar said he was using 2 arrays
var idsArray;
var namesArray;
for(i=0;i<result.data.length;i++)
{
idsArray[] = result.data[i].id;
namesArray[] = result.data[i].name;
}
var ids = idsArray.join(",");
var names = namesArray.join(",");
$.post("receiver.php", { ids:ids, names:names }, function(data){ console.log(data);});
similar to iBlue's comment, You can just send an object with post; you don't have to define the object in the post function, { } are simply the delimiters to define objects, which are similar to PHP associative arrays:
$.post('reciever.php', myData, function(data){ /*callback*/ });
The only thing is that you setup myData as an object like follows:
myData = {
0: 'info',
1: 'info'
}
//or even something like this
myData = {
someProp: 'info',
someProp2: {
anotherProp: 'moreInfo'
}
}
you can also use non-numerical indexes with objects, and easily add properties:
myData[2] = 'info';
or you can loop through it, just in a slightly different way:
for(i in myData){
myData[i]; //Do something with myArr[i]
}
the for in loop will also loop through non-numerical properties. And you can still get the length of myData by
myData.length;
EDIT:
Instead of sending a string:
IDs = {}
Names = {}
for(var i = 0; i < result.data.length; i++){
IDs[i] = result.data[i].id;
Names[i] = result.data[i].name;
}
$.post('reciever.php', {IDs: IDs, Names: Names}, function(data){});
In the PHP file you would access them like so
$_POST['IDs'][0] = "some id";
$_POST['Names'][0] = "some name";
EDIT:
Actaully I think the indexes are sent as strings, so might have to do
$_POST['IDs']['0']
Not sure, but it seems like you want to do this:
var sendObj = {};
for (var i=0; i<result.data.length; i++) {
var id = result.data[i].id,
name = result.data[i].name; // or some similiar computation
sendObj[name] = id;
}
$.post("receiver.php", sendObj, function(data){ console.log(data);});
This will send the result.data as name=id-value-pairs.

Search JSON Array based on variable?

I've got a JSON Array that I need to search:
[
{
"Device_ID":"1",
"Image":"HTC-One-X.png",
"Manufacturer":"HTC",
"Model":"One X",
"Region":"GSM",
"Type":"Phone"
},
{
"Device_ID":"2",
"Image":"Motorola-Xoom.png",
"Manufacturer":"Motorola",
"Model":"Xoom",
"Region":"CDMA",
"Type":"Tablet"
},
{
"Device_ID":"8",
"Image":"null",
"Manufacturer":"Motorola",
"Model":"Xoom 2",
"Region":"CDMA",
"Type":"Tablet"
}
]
Using the keyword: $_GET['keyword']; I need to be able to do the following.
Search the combined value of Manufacturer and Model, ie. Motorola Xoom. Then, for whichever set of values matches this, output them to variables.
For example: If the Keyword was HTC, then it would search the array and output:
$DeviceID = 1 $Image = HTC-One-X.png $Manufacturer = HTC $Model = One
X $Region = GSM $Type = Type
However if the keyword was Motorola, then it would need to output all entries that include Motorola.
What im trying to do, is output a live view of all JSON Array entries, as the user types the keyword. However I want this to run on the users computer to reduce the load on the server.
Does anyone know the best way to go about this?
well if you have a selection box with the values for the manufacturer in the options section it's as easy as:
HTML:
<select id="selectionBox">
<option>...</option>
</select>
<div id="outPut">
output goes in here
</div>
Javascript:
var selectedValue = document.getElementById("selectionBox").value;
for(var i = 0; i < jsonObject.length; i++){
if(jsonObject[i].Manufacturer === selectedValue){
//considering your object is an array let's
for(var key in jsonObject[i]){
document.getElementById("outPut").innerHTML += jsonObject[i][key] + "</br>";
}
}
}
that'll pretty much print everything in the object onto the output div, the rest is up to your styling.
Here's a function for filtering the JSON. Displaying the data is up to you.
var devices = <your JSON array>;
function filter(keyword, data) {
var filteredArray = [], i, j;
for (i = 0, j = data.length; i < j; i++) {
if ((data[i].Manufacturer && data[i].Manufacturer.indexOf(keyword) !== -1) || (data[i].Model && data[i].Model.indexOf(keyword) !== -1)) {
filteredArray.push(data[i]);
}
}
return filteredArray;
}
// Example usage
var MotorolaDevices = filter('Motorola', devices);

Convert js Array() to JSon object for use with JQuery .ajax

in my app i need to send an javascript Array object to php script via ajax post. Something like this:
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
alert(saveData);
$.ajax({
type: "POST",
url: "salvaPreventivo.php",
data:saveData,
async:true
});
Array's indexes are strings and not int, so for this reason something like saveData.join('&') doesn't work.
Ideas?
Thanks in advance
Don't make it an Array if it is not an Array, make it an object:
var saveData = {};
saveData.a = 2;
saveData.c = 1;
// equivalent to...
var saveData = {a: 2, c: 1}
// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;
Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
//creating a json object
var jObject={};
for(i in saveData)
{
jObject[i] = saveData[i];
}
//Stringify this object and send it to the server
jObject= YAHOO.lang.JSON.stringify(jObject);
$.ajax({
type:'post',
cache:false,
url:"salvaPreventivo.php",
data:{jObject: jObject}
});
// reading the data at the server
<?php
$data = json_decode($_POST['jObject'], true);
print_r($data);
?>
//for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
//include the follwing files
//<!-- Dependencies -->
//<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
//<!-- Source file -->
//<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
Hope this helps
You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:
var a = [];
for (key in saveData) {
a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
There is no need of converting it into JSON because its already a json object.
To view the same use json.toSource();
When using the data on the server, your characters can reach with the addition of slashes eg
if string = {"hello"}
comes as string = {\ "hello \"}
to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>

Categories

Resources