How to list values in Jquery - javascript

I have a JSON data which is sent to getJSON method. JSON data is
[{"Name":"P1","Description":"D1","Attribute":"E,S","Value":"EV,SV"}]
and getJSON method
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});
I would like to get the alert as
E : EV
S : SV

The code here is assuming you have the pair in order. The idea is split the attribute and value, then select the value with same index to alert.
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
var attrs = v.Attribute.split(",");
var values = v.Value.split(",");
for(var i = 0; i < attrs.length ; i++)
{
alert(attrs[i] + " : " + values[i]);
}
});
});
});

try this
$.getJSON(url, { Name: 'P1' }, function (data) {
var aSplit=data[0].Attribute.split(',');
var vSplit=data[0].Value.split(',');
alert(aSplit[0] + ' : ' + vSplit[0]);
alert(aSplit[1] + ' : ' + vSplit[1]);
});

If data is coming as string, then you need to eval(data) to get a javascript object.
Try :
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
data = eval('('+data+')');
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});

Related

Get list of elements using data-id

I must have a list of label elements with data-id attrib where I use labels values to set img on the main container.
Function changeimage was return nodelist with null elements but I don't have any idea why
Any solutions ?
function getState() {
try {
$.ajax({
type: "POST",
url: "Default.aspx/jsrequest",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ajax").empty();
$.each(data, function () {
$("#ajax").append('<div id="ajaxcontent">
</div>');
$("#ajaxcontent").addClass("ajaxcontent");
$.each(this, function (k, v) {
$("#ajaxcontent").append('<div class="view">'
+ ' <label id="IdOfMachine">'
+ v.MachineId
+ '</label>'
+ '<label class="MachineState" data-id= "'
+ v.MachineId + ' " > '
+ v.CurrentStatus
+ '</label > '
+ '<img id="ChangeImg" src="">'
+ '</img>'
+ '<label id="MachineName">'
+ v.MachineName
+ '</label>'
+ '</div>');
});
});
},
error: function (response) {
alert("something wrong")
}
});
} catch (err) { }
}
window.onload = function () {
getState();
setInterval(function () {
getState();
}, 20000);
}
function ChangeImage() {
let labels = document.querySelectorAll(["data-id"]);
//here i need to loop over element list and then get lables values to set img which show current state of label
}
You could change it to something like this:
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function(i, x) {
var text = $(x).text();
});
}
This should provide you with the text from the label equal to v.CurrentStatus
demo
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function(i, x) {
var text = $(x).text();
console.log(text);
});
}
ChangeImage()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label data-id="1">test1</label>
<label data-id="2">test2</label>
Why not using css selector
function ChangeImage() {
let labels = $('.MachineState').map(() => {
let item = {
id: $(this).data('id'),
value: $(this).text()
}
let imgUrl = `${item.id}-${item.value}.jpg` // for example
$(this).closest('img').attr('src', imgUrl)
return item
});
}
This will generate list of object like this
[{id: 1, value: 'label1'}, {id: 2, value: 'label2'}, ...]

how get data json with parameter

i have url : http://cgncrdev.gandsoft.com/ws/get.php?fcid=gen_ncr_id&origin_id=OR10&suborigin_id=OR13
anyway, you can open it url..
i try this but not working
function gen_ncr_id() {
$.getJSON(baseUrl + '/ws/get.php?fcid=gen_ncr_id&origin_id=OR10&suborigin_id=OR13', function(data) {
$.each(data.items, function(key, val) {
alert(val.gen_ncr_id)
opt = '<input type="text" value="' + val.gen_ncr_id + '">'
$(opt).appendTo('#id_ncr')
})
})
}
output : undefined
can help me ?
try this:
var data = {"items":[{"gen_ncr_id('OR10','OR13')":"4.13\/4.10.4\/16\/002"}]};
function getPrefixValue(obj, prefix) {
var result;
var re = new RegExp('^' + prefix);
$.each(obj, function(key, value) {
if (key.match(re)) {
result = value;
return false; // break the each loop
}
});
return result;
}
$.each(data.items, function(key, val) {
var value = getPrefixValue(val, 'gen_ncr_id');
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

getJSON not satisfied

I have 3 selects:
country, region, city
When choosing a country to be updated select the region on the country.
here's the code. like written logically. but the region is not updated
$(document).ready(function() {
$('select[name=ad_country]').change(function() {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', {country: current_country},
function(data) {
$('select[name=ad_region]').empty();
$.each(data.region, function(key, val) {
$('select[name=ad_region]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function(key, val) {
$('select[name=ad_city]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
});
}
);
}
you have an error on your clossing tags
You have missed the '}' at the end.Now try this Code :
$(document).ready(function () {
$('select[name=ad_country]').change(function () {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', { country: current_country },
function (data) {
$('select[name=ad_region]').empty();
$.each(data.region, function (key, val) {
$('select[name=ad_region]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function (key, val) {
$('select[name=ad_city]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
});
});
});

Jquery ajax Check if there results are empty

I am using the following code to pull in data from my database and plot points with google maps. What I want to do is something like, "if response=null, alert('empty')" but everytime I try to work that into this code, something just breaks. If anyone could offer any help that would be awesome.
Here is my code:
<script type="text/javascript">
$(function ()
{
var radius3 = localStorage.getItem("radius2");
var lat3 = localStorage.getItem("lat2");
var long3 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var citya = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://examplecom/test/www/base_search.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
if (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
} else {
alert('hello');
}
}
})
}
});
})
}
</script>
Something like
success: function (data) {
if(!data) {
alert('empty');
return;
}
$.each(data, function (key, val) { ...
should work.
Something like this!
success: function (data) {
if(data.length == 0) {
alert('empty');
return;
}
Something like this?
success: function (data) {
if(data){
//do your stuff here
}
else{
alert('empty');
}
}

Simple ajax request

I am new to ajax and am trying to get the following script working. I just want to take info from a json object and print it to the document.
Here is the JSON file called companyinfo.json:
{
'id':1,
'name':'Stack'
}
The Ajax request looks like this:
ar xhr = false;
var xPos, yPos;
$(function(){
var submitButton = $("#dostuff");
submitButton.onclick = sendInfoRequest;
});
function sendInfoRequest (evt) {
if (evt) {
var company1 = $("#companyInput1").val;
var company2 = $("#companyInput2").val;
}
else {
evt = window.event;
var company = evt.srcElement;
}
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
data: company1,
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
return false;
}
console.log(data.id);
To start simple. I just console.log the data.id to see if the script returned a value from the json file.
To write it to the document I would do something like this, calling the showContents function in the callback function above:
function showContents(companyNumber) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseXML;
$("." + data.companyName.toLowerCase + companyNumber).innerHTML(data.companyName)
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
}
}
I'm pretty new to Ajax, but hopefully that makes some sense. Thanks
if you are trying to get something i think you should add
type:"GET"
on your $.ajax it should look like this.
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
type:"GET",
contentType: "application/json; charset=utf-8",
data: company1, //What is your purpose for adding this?
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
Im not sure about this in your code:
var company1 = $("#companyInput1").val; //should it be with ()??
var company2 = $("#companyInput2").val; //should it be with ()??
should it be with () like this one:
var company1 = $("#companyInput1").val();
var company2 = $("#companyInput2").val();
The easiest way to get and parse JSON is to use $.getJSON
// you need to use a map as your data => {key : value}
$.getJSON("companyinfo.json", {company : company1}, function(data){
console.log(data);
var items = []; // new Array();
$.each(data, function(key, val){
items.push('<li id="' + key + '">' + val + '</li>');
});
// do something with items
});
you can do like this:
$.getJSON("getJson.ashx", { Index: 1 }, function (d) {
alert(d);
});

Categories