I am a jQuery beginner and hope someone can help me with this and also provide me some explanations.
I have an Ajax call that returns a JSON encoded string with two values for each item, an itemID and an itemVal - an example looks as follows (using console.log
):
console.log(data) result:
string(225) "[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"},...]"
The number of items here varies but if an itemID is listed than there is always a corresponding itemVal.
itemID is a unique integer, itemVal is plain text.
Everything works so far but here comes my problem:
For each itemID here I have to do something with the corresponding itemVal, e.g. say just log it to the console or alert it for testing.
I know there are various approaches for this like jQuery.each, $.each, for, foreach
etc. but since I just started recently I am not sure how I can iterate through this resp. how I can select the single itemIDs from it.
I tried different approaches, incl. $.parseJSON(data)
which failed and it seems the problem is that my input before being decoded is a two-dimensional array instead of a one-dimensional one (I hope I am using the right terms here) which caused them to either return an error or to alert every single character of my string.
Update - failing example as per the answer below
$.ajax({
type: "post",
url: "ajax.php",
cache: "false",
data: {
node: 'fetchCountries',
itemIDs: itemIDs // a list of integers
},
success: function(data){
console.log(data);
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
}
});
Update 2 - My PHP:
case "fetchCountries":
$intval_itemIDs = array_map("intval", $_POST["itemIDs"]);
$itemIDs = implode(",", $intval_itemIDs);
$stmt = $conn->prepare("SELECT itemID, en FROM Countries WHERE itemID IN(" . $itemIDs . ") ORDER BY itemID");
$stmt->execute();
$result = $stmt->get_result();
while($arrCountries = $result->fetch_assoc()){
$countries[] = array("itemID" => $arrCountries["itemID"], "itemVal" => $arrCountries["en"]);
}
var_dump(json_encode($countries));
break;
Expected outcome (for testing):
console.log("China");
console.log("France");
console.log("Germany");
// ...
Can someone help me with this ?
Many thanks, Tim