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]);
}
Related
I have the following controller action:
public JsonResult GetInvestors(int bank)
{
var investors = _context.Investors
.Where(i => i.BankNumber == bank)
.Select(i => new { InvestorId = i.InvestorId.ToString(), InvestorName = i.InvestorName + " (" + i.BankNumber + ")" })
.OrderBy(i => i.InvestorName)
.ToDictionary(i => i.InvestorId, i => i.InvestorName);
return Json(investors, JsonRequestBehavior.AllowGet);
}
And the following javascript to call that action that for now just starts the debugger so I can browse the result:
function getInvestors(bank)
{
$.ajax
({
url: "/InvestorDetail/GetInvestors",
type: "POST",
data: { bank: bank },
dataType: "json",
success: function (returnedData) { debugger; }
});
}
If I watch investors in the controller action, it is sorted by the investor name, which is what I want. However, when I get to the javascript debugger and watch returnedData, the data comes in sorted by the investor ID.
Alternately, if I put OrderBy after ToDictionary and order by Value, in the javascript debugger the json structure of the result is different but it is sorted by investor name like I want.
Why would the sort order change when returned from a Dictionary?
Thank you.
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
See official msdn documentation
You can use sorted Dictionaries though, or sort it properly on the client side.
You can't sort a dictionary, although you can get a representation of a sorted dictionary!
You could try something like
import collections
Dictionary_Sorted = collections.OrderedDict(x)
x being an object with key valued pairs.
This is the same case for C# as well.
I like to change my Dictionary to a list by say.
var newList = thisDictionary.ToList();
newList.Sort((a,b) => a.Value.CompareTo(b.Value));
I like the one liner approach. It is simple and elegant.
If you would like to sort it descending then switch the values as such.
newList.Sort((a,b) => b.Value.CompareTo(a.Value));
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"]
I want to get some data from a form making AJAX call. I am getting the data as a string in my PHP page. The string looks like
'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''
Now I want to convert this entire string into array which would look like
["fname"] => "abc",
["lname"] => "xyz"... and so on
The ajax call is like below:
fname = $("#form-fname").val();
lname = $("#form-lname").val();
email = $("#form-username").val();
pwd = $("#form-password").val();
phone = $("#form-phone").val();
gender = $("#form-gender").val();
dob = $("#form-dob").val();
var user = {"fname":fname,"lname":lname,"email":email,"pass":pwd,"phone":phone,"gender":gender,"dob":dob};
$.ajax({
type: "POST",
url: "doRegistration.php",
data: user
})
.done(function( msg ) {
window.location.href = "../profile.php";
})
.fail(function(msg) {
sessionStorage.setItem("success","0");
window.location.reload();
});
And here is my PHP code:
$content = file_get_contents("php://input");
file_put_contents("log1.txt",$content); //This produces the string I get above
Now I try to convert the string into array as above
$dec = explode(",",$content);
$dec1 = array();
for($i=0;$i<count($dec);$i++)
{
$dec1[i] = substr($dec[i],strpos($dec[i],":"));
}
//After this $dec1 is empty and count($dec1) gives 0.
But this does not give me the required array. I have checked several answers here, but they do not solve my issue. I tried to google but did not find any resolution. Is there something wrong in the code? Kindly help. Thanks in advance.
Change quotes and add braces. Then you can decode resulting json
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
print_r(json_decode('{' . str_replace("'", '"', $string) . '}', true));
result
Array
(
[fname] => abc
[lname] => xyz
[email] =>
[pass] =>
[phone] =>
[gender] =>
[dob] =>
)
In your code above, you are using the index of the for loop for the key of the array. If you are trying to archive (I believe it is called dictionary in Java). You can try the following code:
<?php
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
$pieces=explode(',',$string);
foreach($pieces as $array_format){
list($key,$value) = explode(':',$array_format);
$array[$key]=$value;
}
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'
]
I've had a good search and am stumped. It may be a simple answer, but after 80 hours of work so far this week, I just can't see it...
In my app I pass some variables to a Web Service, which passes back a single structure containing key/value pairs.
$.ajax({
type: "POST",
url: "it_submitcall.php",
data: {callService: "getcall", callid: $("#callNumber").val()},
dataType: "HTML",
success: function(data){
//do stuff here
},
error: function(data){
// unable to communicate with web service stuff here
}
});
The response I get back is
Array
(
[CALLID] => 44497
[CALLERNAME] => Chris
[TEAMID] => 1175
)
How do I access the elements above in javascript? Any pointers would be greatly appreciated...
Many thanks.
On the PHP side use json_encode to turn the Array into JSON e.g:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Then on the JavaScript side use JSON.parse() to get a JavaScript object back - in your case:
success: function(data){
var obj = JSON.parse(data);
},
As #phenomnomnominal notes, you can use json_encode() on a PHP object to turn it to JSON (and, notably, json_decode() to turn it from JSON to a PHP object)
Once you've got that down, nicely, PHP and JS "hash"-like objects act a lot alike (in PHP, we call these associative arrays and in JavaScript, object literals).
In php, you access an array $your_var like this:
$value = $your_var[ 'key' ];
You can also use variables:
$key = 'key';
$value = $your_var[ $key ];
In JavaScript, it's very similar:
var value = your_var[ 'key' ];
Alternatively:
var key = 'key';
var value = your_var[ key ];
And there's one more syntax that's helpful and more efficient when you don't need variable access to a key:
var value = your_var.key