I am trying to setup a jquery autocomplete input based on the user's input in a previous field.
I have a php script that returns a json variable to this jquery post function. however I can't seem to set up my array correctly after.
I have tried just setting a variable to the data and processing the array outside of the $.post function, but still no luck.
I am just unsure how and why the sub-value of my array is alerted correctly when the "parent" value as such is shown as null?
function populateMetrics(light_id){
var availableMetrics = [];
$.post(
"getLightMetrics.php",
{
light_id: light_id,
},
function(data) {
$.each(data, function(index, item){
alert(index); //correct index
availableMetrics[index] = [];
availableMetrics[index]['value'] = item.benchmark_id;
alert(availableMetrics[index]['value']); //correct value
alert(availableMetrics[index]); //null?
availableMetrics[index]['label'] = item.benchmark_variant + "-" + item.benchmark_metric;
alert(availableMetrics[index]['label']); //correct
alert(item.benchmark_id + " = " + item.benchmark_variant + "-" + item.benchmark_metric);
alert(availableMetrics[index]); //still null
});
alert(availableMetrics); //all null, but correct amount
$( "#metric" ).autocomplete({
source: availableMetrics,
focus: function( event, ui ) {
$( "#metric" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#metric" ).val( ui.item.label );
$( "#metric_id" ).val( ui.item.value );
return false;
}
});
},
"json"
);
}
Multi-dimensional arrays in JavaScript can only have integer-based indexes. They don't work like Associate Arrays do in PHP.
The code you're looking for is probably
var availableMetrics = [];
$.each(data, function(index, item) {
availableMetrics[index] = {
value: item.benchmark_id,
label: item.benchmark_variant + "-" + item.benchmark_metric
};
});
This will create an array of objects that have value and label properties. You would then be able to retrieve the values from your array using either of these notations:
availableMetrics[index]['value'];
availableMetrics[index].value;
Related
I'm trying to loop through some JSON but once it gets to the values that are url's, they are returning as undefined. Here's a simplified example of my JS
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data){
$("ul.mapList").append(
'<li id="store-' + data.restaurant + '">'+
'<div class="singleLocation">' +
'<button class="directions">DIRECTIONS</button>' +
'Restaurant Details' +
'</div>' +
'</div></li>'
)
})
});
And my JSON:
{ "restaurant":31, "restaurantName":"Shenandoah", "address":"19075 IH 45 S Suite 480", "city":"Shenandoah", "state":"TX", "zip":77385, "phone":"(936) 271-9217", "directions":"https://www.google.com/maps/dir//Pei+Wei,+19075+I-45+%23480,+Shenandoah,+TX+77385/#30.1826863,-95.4533763,17z/", "url":"/texas/31-shenandoah"}
The two keys at the end, "directions" and "url" are the only ones that return as undefined. What am I doing wrong?
Problem is here:
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data) {
You are overwriting variable data in function(i, data), consider to change it to value or something else.
Use this code:
$.getJSON( "ajax/ejemplo.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "" + val + "" );
});
$( "", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
$.getJSON("https:../houston-locations.js",function(data){
console.log(data);
$.each(data, function( key, value ){
console.log(data.directions);
console.log(data.url);
});
});
the right use of $.getSOn is as above
I found the solution to be something so simple.. It was a cache issue so the new JSON data wasn't being loaded. I did however change the overwriting 'data' values. Thanks everyone!
I am using jquery to call for a Json object from the server. This is my call:
$.getJSON( url, function( data ) {...}
I am getting back (from console.log) the following object:
> 0: Object
cable key: "1"
cable type: "Building Wire..."
> 1: Object
cable key: "2"
cable type: "PVC Wire..."
...
I am trying to access both key and value like the examples below without any luck.
$.getJSON( url, function( data ) {
$.each( data, function( key, value ) {
$( "#CableType" ).append( $( "<option value='" + value['cable key'] + "'>" + value['cable type'] + "</option>" ) );
});
})
Thanks for any help
You are trying to get a property of the VALUE instead of the object. Use
data['cable key']
instead of
value['cable key']
Beside, adding elements to the DOM inside a loop is inefficient. You need to collect your html in a string, and after the loop ends, put it in the DOM. You can do something like this:
$.getJSON( url, function(data){
var htmlCollection = "",
propertyName;
data.forEach(function(pair){
htmlCollection += "<option value='" + pair['cable key'] + "'>" + pair['cable type'] + "</option>";
});
$( "#CableType" ).append(htmlCollection);
});
I´m having some trouble setting the initial value of my Jquery UI Slider. The main problem (I think) is that the initial value I'm setting is being generated AFTER the slider is created (the initial value is coming from a Jquery.ajax).
Here is what I have:
<script type="text/javascript">
$(window).load(function(){
function ReadVars() {
$.ajax({
//Post to fetch values from computer B
url: "somefile.php",
type: "post",
datatype: "html",
data: {
foo: "foo",
bar: "bar",
},
success: function(response){
//Computer B responds with several values separated by
// a comma e.g. "0,23,1,hello,etc"
var responseSplitted = response.split( "," );
//The second value from the response (in this case 23)
//should be the initial value of the slider
var SliderStart = responseSplitted[1];
console.log("Slider start = ", SliderStart);
},
});
}
var Init = false;
if( !Init ) {
console.log( "Init" );
Init = true;
ReadVars();
}
setInterval( ReadVars, 10000 ); //Update respond every 10 seconds
$("#slider1").slider({
value: SliderStart, //SliderStart should be 23.. but is not working
//because SliderStart does not exist at the moment this part is run
min: 0,
max: 60,
slide: function (event, ui) {
$("#slider1Value").val(ui.value + " kg");
},
stop: function(){
var value = $(this).slider( "option", "value" );
console.log( "value = ", value );
}
});
$( "#slider1Value" ).val( $( "#slider1" ).slider( "value" ));
});
</script>
<body>
<input id="slider1Value" type="text">
<div id="slider1" style="width:300px;"></div>
<input type="text" id="slider1Value" />
</body>
If I include the following two lines under the "success: function(response){}", then it works.
$( "#slider1" ).slider( "option", "value", SliderStart );
$( "#slider1Value" ).val( $( "#slider1" ).slider( "value" ) + " kg" );
However, I just want to set the initial value once and not every 10 seconds. Is there anyway of doing this?
If you move all the code that creates your slider to the success function of your Ajax call, then the slider will be created as soon as your initial value is available.
I hope you can follow me in this fiddle.
I'm trying to send an extra variable to my source in jquery autocomplete. This can usually be achieved by just adding the variable after your sourche URL like so: source:'myURL.php?supplier=myvariable' .
The var I'm trying to send however is dynamic, it's a variable that is either true or false depending on a checkbox that is checked or not. Like so:
var dynamicVar = $('#y').prop('checked');
$('#y').change(function(){
dynamicVar = $('#y').prop('checked');
console.log(dynamicVar);
});
Now I tried to use this variable in my source for autocomplete like so:
source:'myURL.php?supplier='+dynamicVar
As you can see in my fiddle (if you look for the GET URL in console), this variable is always false, whether the checkbox is checked or not.
How do I edit my code so that the requested URL in my demo ishttp://fiddle.jshell.net/DLLVw/482/show/myURL.php?supplier=false&term=whatItyped when the checkbox is unchecked, and http://fiddle.jshell.net/DLLVw/482/show/myURL.php?supplier=true&term=whatItyped when the checkbox is checked?
P.S. type in the input field to see the GET url
UPDATE: artm's code returns the correct content, however this breaks the autocomplete functionality on the input.
ORIGINAL NON-Dummy code:
jQuery:
var dynamicVar = $('#zxc').prop('checked');
$('#zxc').change(function(){
dynamicVar = $('#zxc').prop('checked');
dynamicVar = $('#zxc').is(':checked');
console.log(dynamicVar);
});
function getChecked(){
return $('#zxc').is(':checked');
}
$('#q').autocomplete({
source: function(request, response) {
$.ajax({
url: "getklanten.php",
data: {
term : request.term,
supplier : $('#zxc').is(':checked')
}
});
}
}) .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.naam + "</a>" )
.appendTo( ul );
};
Response in console:
[{"naam":"Company name","id":12345}]
See http://jsfiddle.net/DLLVw/483/
When you pass dynamicVar to the autocomplete, it uses the value of dynamicVar at the time when you called autoComplete. So it's always false, ragardless of the state, since dynamicVar doesn't change when you change the check box. If you want to pass dynamic values you need to use:
$('#x').autocomplete({
//source:'myURL.php?supplier='+dynamicVar
source: function(request, response) {
$.ajax({
url: "myURL.php",
data: {
term : request.term,
supplier : $('#y').is(':checked')
}
});
}
});
I am working on Dynamic Web Project in Eclipse and using HTML 5 and Javascript as well.
I could manage to parse JSON file that is saved locally in my system though the code below:
$.getJSON( "/Users/Documents/workspace2/sample.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Let's suppose this is the JSON file:
{"resource":"A","literals":["B","C","D"]}
My question is: Is there any possibility to have an array of strings to store these elements that are inside the JSON file after parsing. I am quite new to jQuery and couldn't really manage to see these elements stored in an array of strings, for example. Could anyone help me with this issue please.
Try this way :
jsonFile.json
{
"resource":"A",
"literals":["B","C","D"]
}
myFile.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$.getJSON( "jsonFile.json", function( data ) {
var items = [];
$.each( data, function( key, val1 ) {
items.push( "<li><a href=#'" + key + "'>" + val1 +"</a></li>");
});
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
</script>
</head>
<body>
//result will be displayed here
</body>
</html>
Output :
var abc = JSON.stringify({"resource":"A","literals":["B","C","D"]});
var ab = JSON.parse(abc);
var arr=$.map(ab, function(value, index) {
return [value];
});
Hope it helps.