Accessing items in array - javascript

I have an object returned from a $.ajax request. This is an example:
[{"id":"14","branchName":"Catcliffe","address1":"26 Main Street","address2":"","address3":null,"city":"Catcliffe","county":"South Yorkshire","postcode":"S60 5SR","country":"UK"}]
I am having a brain freeze on how to access items in the array, for example how would I set a variable to the 'branchName'...
This is the code I used to get the data:
$("#branchID").change(function(){
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch){
$("div#results").html(branch);
}
});
});

You need to get the first element in the returned array using it's index, [0], then you can grab the property you want from that, .branchName.
$("div#results").html(branch[0].branchName);
Example fiddle

I just assumed that you are holding that object in a variable called xObj.
Try,
console.log(xObj[0].branchName)
But you should parse it before accessing the values since you have not mentioned the type,
var xObj = JSON.parse(branch);
console.log(xObj[0].branchName)

You have to use indexer, to access the element of array. As array contains object you go to use dot . operator to access object properties like branchName
Live Demo
$("div#results").html(branch[0].branchName);
Your code would be
$("#branchID").change(function () {
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function (branch) {
$("div#results").html(branch[0].branchName);
}
});
});

You would get the branchName property from the first (and only) item in the array:
$("div#results").html(branch[0].branchName);

use object and using its property we can access it branch[0].branchname
$("#branchID").change(function()
{
var id = $(this).val();
$.ajax(
{
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch)
{
var branchname= branch[0].branchname;
$("div#results").html(branch);
}
});
});

To handle multiple objects you can loop the result using a for loop like the one given below:
for(var i in branch)
{
var id = branch[i].id;
var branchName = branch[i].branchName;
//....
//Iterate other objects as well
}

Related

javascript and jquery weird array object

i have stuck on this weird thing for 03 day and don't understand why it created that object "id[]" when jquery sending data to server. i tried to push the element to new array so i can get the normal {id: 'value01'} but it does not work, the server response is still showing the weird array in object: {'id[]': 'value01}. i am stuck on this because if i do var id = masoid[0] it work as the server show normal {id: 'value01'} but i need to filter the array before sending it. Thank you for your time
here is jquery code
function onlyUnique(value, index, self) {
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
if(isNumeric(value)){
return self.indexOf(value) === index;
}
};
// var id = {masoid.filter(onlyUnique)};
// var idDaFilter = new Array;
// id.forEach(element => {
// idDaFilter.push(element);
// });
var id = masoid.filter(onlyUnique);
console.log(id);
$.ajax({
url: deleteUrl,
type: 'POST',
data: {id:id},
});
the server response:
server code
let id = JSON.parse(JSON.stringify(req.body));
console.log(req.body);
You're using the method filter in the variable id. This method return a new array (shallow of original), so this is why you're getting 'id[ ]' on response. Use find instead.
var id = masoid.find(onlyUnique);
See an example here.
When you set var id = masoid[0] you're getting the first element of that array, than it works.
See more details on documentation find method and filter method

How can I assign dictionary values to javascript variables (jQuery / AJAX API call returned in JSON)

I have a well running AJAX request that queries data from a third party API that returns the data in JSON. I now want to assign the values from the returned JSON data to javascript variables to make further manipulation to the data itself in my AJAX success function before updating the frontend.
In the below example I would like to assign the value of key name to my Javascript team variable.
What would be the best way to accomplish this?
This is the returned structure:
{
"api":{
"results":1,
"teams":[
{
"team_id":66,
"name":"Barcelona",
"code":null,
"logo":"Not available in Demo",
"country":"Spain",
"founded":1899,
"venue_name":"Camp Nou",
"venue_surface":"grass",
"venue_address":"Carrer d'Ar\u00edstides Maillol",
"venue_city":"Barcelona",
"venue_capacity":99787
}
],
This is my AJAX request:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/http://www.api-football.com/demo/api/v2/teams/team/" + team_id,
success: function(response) {
var team_data = response
console.log(team_data)
team = // how to assign team name from API callback to variable
console.log(team)
$("#selectedClub").html(response);
}
});
});
You can use dot notation to navigate through objects
team_data.api.teams[0].name //output: "barcelona"
In you example there is only one item inside teams array, so the above example should works fine, but let's suppose that in your response there is more than 1 team on teams then you could do something like this:
var teamList = [];
$.each(team_data.api.teams, function(index, team){
teamList.push(team.name);
})
and it will give an array with all team names from your ajax response
put JSON in js obj variable
var obj = JSON.parse('{ <key:value>,<key:value>...}');
Make sure the text is written in JSON format, or else you will get a syntax error.
Use the JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("name").innerHTML = obj.name + ", " + obj.country;
</script>

How to return first item from a nested JSON array using jQuery

I'm currently experiencing a few problems whilst parsing .JSON.
Ok, so 'element.lineStatuses' can return 1 or 2 opjects in an array but I only want to return the first object from array. I've tried a multitude of different solutions, however, none seem to work...
Please note: I am unable to use '$.first()' as a solution as my application depends on an older version of jQuery.
$.ajax({
url:"https://api.tfl.gov.uk/line/mode/tube,overground,dlr,tflrail/status",
dataType: 'json',
type: 'get',
cache: false,
beforeSend: function() {
$("#loadingDiv").show();
},
success: function(data){
console.log(data);
var jObject = data;
$.each(jObject, function(index, element) {
$("#lines").append("<li class=\"lineName\"><h2>" + element.name + "</h2></li>");
// console.log(element.name);
// element.lineStatuses; can contain 1 or 2 opjects in an array but i only want to return the first objectin array.
var status = element.lineStatuses;
// loop to get line status
// gets all objects
$.each(status, function(index, element) {
var desc = element.statusSeverityDescription;
//console.log(desc);
$("#lines").append("<p class=\"currentStatus\">" + desc + "</p>");
});
});
}// end success
});// end ajax
If you what you want is to get only the first element of an array-like object in an array of its own, you can use slice to create a shallow copy:
var status = [].slice.call(element.lineStatuses, 0, 1);
If you're sure element.lineStatuses is an array and not simply array-like you can use the simpler:
var status = element.lineStatuses.slice(0, 1);
Try this:
var status = element.lineStatuses[0];

Writing specific value from database to HTML via AJAX/jQuery

First time question, hoping for some advice:
Code on webpage:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response);
}
});
});
});
};
</script>
</form>
This returns a string that I would like to work with that looks like this:
Answer:
[{"id":"1","answer":"Pull logging","question_id":"5","feature_id":"1","answer_id":"9"}]
Ideally what I would like to do is only select the 'value' to the maxmail_answer 'key' (hopefully those are the right terms?) to the webpage instead. Right now there is only one value but there will be more in the future so something that could parse this string for a specific key and only output those values.
Visually I would see:
Answer: Pull logging ( and then another Answer: for each value I pull out )
First time ever using this site and these languages so total noob and would appreciate some guidance.
Thanks!
You do not to stringify the JSON response, you can get the value of the key you want using the object notation . as follows:
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
//var response = JSON.stringify(data); // no need for this line
$('#response').delay(3600).fadeIn(600);
// catch the answer here
// your result returns within an array so you need to catch the first index
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
});
});
});
};
Besides, ids are unique, you can only access a single element via id selector #, you do not need a .each
What you are receiving from your server is an array of objects in the JSON format. The sample that you have put has the length of "1" and therefore, if want to reach the "id" of the first array, it would be like this:
// var response = JSON.stringify(data); (// don't stringify it!
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+data[0].id);
You need here a loop to go through your array of results and display each result
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$.each(response,function(index,value){//the each loop
$('#response').append("<p>Answer: </p>"+value.answer);//get the answer using . notation
});
}
Json.stringify() returns your javascript object as json data, but i think in your case your response is a json data which you need to manipulate. Json.parse() does this for you and you can access your answer as a property of the javascript object.
success: function(data) {
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
if your json data has multiple result and you need to work through all of them use a loop.
$.each(response,function(index, object){
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+object.answer);
});
First of all. Thank you to everyone who commented on this to help me get started in the right direction. I was able to get what I needed working!! Here is the solution:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#controlpanel:input').each(function () {
var iv = $(this).val();
$('#response').html("");
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var newdata = JSON.stringify(data);
var response = JSON.parse(newdata);
$('#response').delay(3600).fadeIn(600);
$.each(response, function(array, object) {
$('#response').append("<p>Answer: </p>"+object.answer);
});
}
});
});
});
};
</script>
</form>
I needed to parse the data correctly. So I used JSON.stringify to get the data into a string that JSON.parse could use to manipulate the data. But function(index,object) wouldn't work because my output was not an index, but an array. So when changing to function(array,object) this allowed me to get my data just the way that I needed.
Again thanks to everyone for their help!

creating a associative array/hash in javascript

I have a form with different groups of checks boxes and trying to pass all the selected values into an array then pass that data into a ajax request.
$('#accessoriesOptions input').each(function(index, value){
if($(this).attr('checked') ){
var newItem =[];
var obj = {};
obj[$(this).attr('value')] = $(this).attr('name'); //I have an hash table with the key-value
wizard.searchArray.push(obj);
}
})
$.ajax({
data : wizard.searchArray
})
I get a wizard.searchArray like :
[0] = {'acc_1' : 'vase'},
[1] = {'acc_3' : 'ceramic'}
I need to create a key-value as I use the key to work out which part of the filtering to use.
The problem
When I do the ajax request, from firebug I see the request as :
/wizard-demo/?undefined=undefined&undefined=undefined
In this case just push add the properties to the obj and use it directly, that's the pair that'll get serialized property when used as the data property, like this:
var obj = {};
$('#accessoriesOptions input').each(function(index, value){
if(this.checked){
obj[this.value] = this.name;
}
})
$.ajax({
data : obj
});
Though this is backwards from a normal <form> submission, if that's what you want it's this instead:
obj[this.name] = this.value;
If you wanted to send the entire form, there's a much shorter/built-in .serialize() method for this:
$.ajax({
data : $("#accessoriesForm").serialize()
});

Categories

Resources