Passing an array from Angular to php - javascript

I have a dropdown form where you can select one or more items. The selected items I want to send to a backend php script that will insert the selected values into a database.
This is my angular insert function:
insertRepair: function (id_telefon, id_culoare, arrayPiese) {
console.log(arrayPiese);
http.get('../php/insert_reparatii.php', {
params: {id_telefon: id_telefon, arrayPiese: arrayPiese,
id_culoare: id_culoare}
}).then(function () {
}
}
The call to this function is done like this:
serviceHttp.insertRepair($scope.phoneMP.selected.id, $scope.colorMP.selected.id, $scope.selectedPiesaMP.selected);
If I print into the console the arrayPiese array it will print for 2 selected items, something like this:
["Adezivi_Rama", "Polarizator"]
Now in the backend I retrieve the array list:
$arr = $_REQUEST['arrayPiese'];
If I print the $arr variable I get only one of two items printed.
Need to mention that I migrated from jquery to angular, and from jquery I was able to send the entire array like this:
var arrayPiese = [];
$('.select2-selection__choice').each(function () {
arrayPiese.push($(this).attr('id'));
});
The url looks like this arrayPiese=Adezivi_Rama&arrayPiese=Polarizator&id_culoare=1&id_telefon=18
Do I need to serialize the array before sending it to php? Or what would be the best approach in sending an array to backend??

You can pass array as json,
http.get('../php/insert_reparatii.php', {params: {id_telefon: id_telefon, arrayPiese:angular.toJson(arrayPiese),
id_culoare: id_culoare}
}).then(function () {
}
Then in your PHP script, convert json to PHP array,
$arrayPiese = json_decode($_GET['arrayPiese'], TRUE);

arrayPiese=Adezivi_Rama&arrayPiese=Polarizator will result in a single variable $_REQUEST['arrayPiese'] with the value Polarizator because the latter overwrites the first one.
If you want to pass an array, you have to append brackets to the query parameter name:
arrayPiese[]=Adezivi_Rama&arrayPiese[]=Polarizator
…which will result in a PHP variable $_REQUEST['arrayPiese'] with an array value like:
[
0 => 'Adezivi_Rama',
1 => 'Polarizator'
]

Related

How to push each object value into array from json?

I have a JSON response with key-values like:
....
"usp-custom-90":"45.45257926613316,9.178168599999935"
....
Note usp-custom-90has dash!
I need something like (fields doens't exist, it's just an example):
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Where coordsB is an array defined before.
The json would be:
],
"usp-custom-90":"45.47841306255037,9.120865849999973",
"_links":{
"self":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts\/128402"
}
],
"collection":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts"
}
],
"about":[
I need to push the value of each "usp-custom-90"
Full code (wrong as it is using fields which doesn't exist):
fetch('https://www.example.it/wp-json/wp/v2/posts?per_page=50&status=publish')
.then(res => res.json())
.then(data =>{
var coordsB = [];
console.log(data);
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Based on the data sample linked in the comments, the structure is an array of objects, each object containing a usp-custom-90 property. This is a perfect situation for the map operator for arrays.
So in the above code, this one line will do it all for you. It will create the array and populate it with all the values you're looking for.
var coordsB = data.map(x=> x["usp-custom-90"])
Something along these lines would do I guess.
Object.entries(object).reduce((ac,[k,v],i,a)=>(ac.push(v['usp-custom-90']),ac),[])
Looks like from your paste bin main object is an array with objects inside which have the key you want then:
YourMainArray.reduce((ac,d,i,a)=>(ac.push(d['usp-custom-90']),ac),[])
Tested it, gives you this:
["45.45257926613316,9.178168599999935", "45.47841306255037,9.120865849999973", "9.924,-84.090", "44.948,9.039", "45.464150416139695,9.1906395499999", "45.651,11.303", "43.83734441524854,7.905822499999999", "45.05926341591318,9.3354875", "44.872988115810074,13.85009094999998", "44.97805886586813,8.895478499999967", "45.472119466144186,9.173527250000006", "45.165,9.183", "41.937,12.441", "45.464993216140186,9.147909499999969", "45.48624411615216,9.16677489999995", "45.209,9.147", "45.464993216140186,9.147909499999969", "41.848264464222716,12.665936949999946", "45.464993216140186,9.147909499999969", "45.46851557705748,9.139416449999999", "44.507,11.314", "36.731,14.873", "36.222,-121.759", "10.093,77.060", "45.454327616134165,9.175796900000023", "45.469282816142574,9.176045000000045"]

Overwriting Original Values In Collections

I am fetching data from database and storing it on $groups. It has different created_at for each entry.
I want to overwrite on created_at field in collection, just before returning it to the view, and have nice ->diffForHumans() version.
$groupsArray = $messages;
foreach($groupsArray as $key => $group) {
var_dump($groupsArray[$key]['created_at']); // works: 2015-10-17 21:55:46.000000'
var_dump($groupsArray[$key]['created_at']->diffForHumans()); // Error: A two digit month could not be found Data missing
$groupsArray[$key]['created_at'] = $groupsArray[$key]['created_at']->diffForHumans(); // Not Working
}
return $groupsArray->toJson();
If I change groupsArray = $messages->toArray();, the '// Error' bit of above chunk changes to Call to a member function diffForHumans() on string.
Eventually, I need to return it as json as it is ajax request. I want to overwrite on created_at, so I can use group[i]['created_at'] in javascript part in the view, after returning and get Carbon versions.
First, make sure 'created_at' is in your $dates array in your model.
Like described on http://laravel.com/docs/5.1/eloquent-mutators#date-mutators
Second, you can iterate and update over a collection by doing the following:
$messages->transform(function ($item, $key) {
$item->difference = $item->created_at->diffForHumans(); // 10 hrs ago
return $item;
});
$messages->toJson();
use &you can replace the original value !
foreach($groupsArray as &$key => &$group) {
var_dump($groupsArray[$key]['created_at']);
var_dump($groupsArray[$key]['created_at']->diffForHumans());
$groupsArray[$key]['created_at'] = $groupsArray[$key] ['created_at']->diffForHumans(); // Not Working
}

Parsing a Multidimensional array from php to Javascript via json

I am trying to send an array from php to javascript through ajax and am having some troubles.
My php array code looks something like this:
if($_REQUEST['action'] == 'miniCart'){
foreach($_SESSION['cart']['items'] as $item){
$message[$item['id']]['name'] = $item['name'];
$message[$item['id']]['price'] = number_format($item['price'], 2, '.', '');
$message[$item['id']]['qty'] = $item['count'];
}
$message = json_encode($message,true);
}
And this builds an array that looks something like this:
[2] =>
[name] => "Product 1"
[price] => "$15.00"
[qty] => "2"
[1] =>
[name] => "Product 2"
[price] => "$15.00"
[qty] => "3"
My JS code looks something like this:
var miniCart = function () {
$(".tester").on("click", function(event) {
var action = 'miniCart';
$.ajax({
type: "POST",
url: "cart/cart.php",
data:"action=" + action + "&ajax=true",
success: function(string){
var obj = jQuery.parseJSON(string);
alert( obj.name);
}});
});
}
My Json that is sent from php to JS looks like this:
{“2”:{“name”:”Product 1”,”price”:”15.00”,”qty”:”3”},”1”:{“name”:”Product 2”,”Price”:”15.00”,”qty”:”3”}}
I understand that this wont work, if someone can help finish this so that I can construct another array on the JS side that would be most helpful. My problem is that I can't parse them out correctly. I have tried many variations of JSON parsing but I think the "2" in the beginning is throwing it off. The item ID will never always be changing depending upon the order.
Perhaps I'm trying to engineer this incorrectly. I ultimately want to use these variables to build a shopping cart table.
Please assist.
Thank you kindly.
And this builds an array that looks something like this:
You're actually building an associative array in PHP, not a 0-indexed array. It then gets converted into a JSON object (with item IDs as keys), not a JSON array.
To get the name of the item with ID "2" in javascript:
alert(obj["2"].name);
You can iterate over the JSON object like this:
for (var key in obj) {
console.log("Item ID: " + key);
console.log(obj[key]);
}

Getting value from javascript tags in array form

Here I created tag using web tutorials.
JSFIDDLE : http://jsfiddle.net/karimkhan/A5TJh/1/
Inside:
for (var i in tags){
tagString.push(tags[i].value);
}
if I alert(tags[i]) it alerts correctly.
But when I use tags before end of function that it alerts undefined.
My purpose is to store all tags in an array and push POST this array to PHP file. But the issue is I am not able to retrieve tags value in array. As it is already in tags array, I thought I could access it directly.
You need values like 1, 2, 3 or tags names like tag1, tag2, tag3?
Call someMethod with argument like tagString
instance.tagit({
tagSource: availableTags,
tagsChanged: function () {
//Get the tags
var tags = instance.tagit('tags');
var tagString = [];
//Pull out only value
for (var i in tags) {
tagString.push(tags[i].value);
}
someMethod(tagString);
//Put the tags into the input, joint by a ','
input.val(tagString.join(','));
function someMethod(tags) {
console.log(tags);
// call POST action
}
}
});
I think it's easier to just retrieve the values from the DOM, rather than try to store them in an array. If you store them in array as they are being created, then you have to keep an eye on changes, such as if the user deletes one of the tags.
So I would just retrieve the values when the user performs their submit action. The values are stored in a hidden unordered list and each has a class of .tagit-choice, so just iterate over the list and retrieve the text values:
DEMO
$('.tagit-choice').each(function () {
alert($(this).contents(':not(a)').text());
});
Naturally, you can use the each method to create an array once you're ready to post like this:
tagsForPost = [];
$('.tagit-choice').each(function (i) {
tagObj = {value: i, label: $(this).contents(':not(a)').text()};
tagsForPost.push(tagObj);
});
console.log(tagsForPost);

How to append database values to JSON data

I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]
database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
Below is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
Please help me here.
There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)

Categories