I have a problem with jQuery to obtain each value from jSon string and modify a div or span or other id with value obtained from a jSon string.
At the start of each PHP file i have an SQL request generate an hidden input with a jSon string as value. This is for multilanguage for example in english the generated string is
<input type="hidden" id="page_json_language_home" value='{
"label_title":"My WebSite",
"label_settings":"Settings",
"label_subscription":"Subscription"
}' />
for french :
<input type="hidden" id="page_json_language_home" value='{
"label_title":"Mon site web",
"label_settings":"Parametres",
"label_subscription":"Abonnement"
}' />
this is work fine !
After that i have a javascript using jquery to match each label_xxx with value
i have many html code like this
<title id="label_title></title>
<div id="label_settings"></div>
or
<span id="label_subscription"></span>
This is my (partial) code in my javascript file i called to obtain the json string from hidden input :
var _getPageJsonLanguage = function(id) {
if (!id)
id = "page_json_language";
else
id = "page_json_language_" + id;
var json = $("#" + id).val();
var data = bsc.data.jsonParse(json);
return data;
};
This is work fine too !
The code in problem is :
data_language = bsc.page.getPageJsonLanguage("home");
var j = 0;
var language = [];
for (i in data_language) {
console.log("i in language = " + i);
language[j] = i;
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
The result can i obtain in browser 1) undefined for each label or 2) label_xxx for each label_xxx
I need help to access each value of each label_xxx .
I can't obtain the value, this is my last try....
I believe the problem is in your for in loop, you never actually grab the value, only the key:
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i]; //changed this line to actually grab the value
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
If you are receiving undefined, it may be due to the JSON not being parsed correctly. Since your using jQuery, you can always run $.parseJSON(json) to be sure.
Fiddle accessing your JSON in a for in loop and logging: http://jsfiddle.net/tymeJV/CKBLc/1/
I hope this will work -
var data_language = JSON.parse($("#page_json_language_home").val());
var language = [];
var j = 0;
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i];
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
Related
I'm pretty new to web programming so, making a logic for a web-page, I made a mistake and now I'm in trouble.
I named some divs like "Dv_1.2.1.3" (without knowing the problems linked to using the dot) and I have issues trying to clone (via jquery called by button) some of these.
The button id contains the id of the div I want to clone, so, my logic is:
1) extract the id of the div;
2) get the div and clone it (giving a new id).
I'm stuck with getting the div because of the dots in the id.
The below code is what I've done so far:
$('.CloneDiv').click(function () {
var SplittedId = (this.id).split('_');
if (SplittedId[0]=='Clone'){
alert('SplittedId 1 =' + SplittedId[1]);
//Modify id to use it to find the div to clone
var UsableId = SplittedId[1].replace(/\./g, '\\\\.');
alert('UsableId =' + UsableId);
//Count existing elements
var ClonedNum = $('#' + 'Dv_' + UsableId + '_').length;
ClonedNum++;
var OrigElem = $('#' + 'Dv_' + UsableId).length;
alert('OrigElem =' + OrigElem); //THIS IS 0
//NO ELEMENTS FOUND BUT THE ELEMENT EXISTS
//Clone the element and give new id
var ClonedElem = $('#' + 'Dv_' + UsableId).clone().attr('id', function( i, val ) {
return val + '_' + ClonedNum;
});
ClonedElem.find("input").val("");
if (ClonedNum > 1){
ClonedNum--;
var AnteId = '#' + 'Dv_' + UsableId + '_' + ClonedNum;
alert(AnteId);
$(AnteId).after(ClonedElem);
}else{
var AnteId = '#' + 'Dv_' + UsableId;
alert('AnteId = ' + AnteId);
$(AnteId).after(ClonedElem);
};
}else if(SplittedId[0]=='Del'){
alert(SplittedId[0]);
alert('Del');
}else{
//error
};
});
Might these help: developer.mozilla.org/en-US/docs/Web/API/CSS/escape , Polyfill: github.com/mathiasbynens/CSS.escape/blob/master/css.escape.jāās
I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}
This is the function that I have
function set(sub) {
var input = prompt("Insert your desired " + sub + " information, leave blank if you use an automated system to generate this information.");
$('#' + sub).html(input).show();
var textarea = $('textarea');
textarea.html(textarea.html().replace(sub+"=",sub+"="+input));
}
Usually the sub is s1, or s2, or s3. Now the issue is that I want the replaced value to reset if the input is blank.
So lets say I input that I want to set s1 to equal a, so in the text area it will replace s1= with, s1=a, now if the input is empty I want the s1=a to revert back to s1=
How about this? It uses a regular expression (Regex) to do the replacements.
function set(sub) {
var input = prompt("Insert your desired " + sub + " information, leave blank if you use an automated system to generate this information.");
$('#' + sub).html(input).show();
var pattern = new RegExp('(' + sub + '=[^&]*)', 'ig');
var $textarea = $('textarea');
// Do Replacements
var content = $textarea.html().replace(pattern, sub + '=' + input);
$textarea.html(content);
}ā
You can replace the html with something like:
$(selector).html(function(i, orig) {
return orig.replace("1234", "5678");
});
I have a php page which includes the following javascript:
<script>
$(document).ready(function(){
$('#search').hide();
});
$('#L1Locations').live('change',function(){
var htmlstring;
$selectedvalue = $('#L1Locations').val();
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
alert('success');
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
alert('string length is' + JSONdata.length);
if(JSONdata.length > 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
}
}
$('#l2locations').html(htmlstring);
}
else
{
alert('i think undefined');
$('#l2locations').html('');
}
}
});
$('#search').show();
});
</script>
what i'm trying to accomplish is dynamically show a combo box if the variable "returnDataFromController" has any items.
But I think I have a bug with the line that checks JSONdata.length.
Regardless of whether or not the ajax call returns a populated array or an empty one, the length always shows a being 1. I think I'm confused as to what is counted when you ask for the length. Or maybe my dataType property is incorrect? I'm not sure.
In case it helps you, the "console.log(returnDataFromController)" line gives the following results when i do get data back from the ajax call (and hence when the combo should be created)
[16:28:09.904] ({'2.5':"Admin1", '2.10':"Admin2"}) # http://myserver/myapp/index.php/mycontroller/getbranches:98
In this scenario the combo box is displayed with the correct contents.
But in scenario where I'm returning an empty array, the combo box is also created. Here's what the console.log call dumps out:
[16:26:23.422] [] # http://myserver/myapp/index.php/mycontroller/getbranches:98
Can you tell me where I'm going wrong?
EDIT:
I realize that I'm treating my return data as an object - I think that's what I want because i'm getting back an array.
I guess I need to know how to properly check the length of an array in javascript. I thought it was just .length.
Thanks.
EDIT 2 :
Maybe I should just chagne the results my controller sends? Instead of returning an empty array, should I return false or NULL?
if (isset($buildingforbranch))
{
echo json_encode($buildingforbranch);
}
else
{
echo json_encode(false);
}
EDIT 3:
Based on the post found at Parse JSON in JavaScript?, I've changed the code in the "success" section of the ajax call to look like:
success: function(returnDataFromController) {
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=returnDataFromController,
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
alert(obj);
}
But i'm getting an error message on
[18:34:52.826] SyntaxError: JSON.parse: unexpected character # http://myserver/myapp/index.php/controller/getbranches:102
Line 102 is:
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
The problem was that the data from the controller is malformed JSON.
Note the part of my post where I show the return data:
({'2.5':"Admin1", '2.10':"Admin2"})
The 2.5 should be in double quotes not single quotes.
I don't understand how / why this is happening but I will create another post to deal with that question. Thanks everyone.
I'm trying to take a jSON encoded string out of my database and loop through the items but I'm having some difficulty. Here's the string in the database:
["volunteers","seat_dedication_program","memberships"]
And here is the code:
//Looks for _checkbox when looping through my database fields (object dbVals) and turns it into a true jQuery array if it finds it.
if( key.search(/_checkbox/i) > 0 ) var arr = $.makeArray(dbVals[key]);
//If it is an array, loop through the array values and show them
if($.isArray(arr)==true){
$.each(arr, function(i, n){
alert(i + " : " + n);
});
}
What I want is this:
//alert
0 : volunteers
//alert
1 : seat_dedication_program etc...
What I'm getting is this:
//alert
0 : ["volunteers","seat_dedication_program","memberships"]
I think I've included all relevant data. Can anyone help me figure out why this is happening?
Thanks.
Using $.makeArray(..) is giving you an array where the only element is the string you gave it. You need to parse the string into a JavaScript object. Use the JSON2.js library to parse then your code would look something like this.
var arr = JSON.parse(dbVals[key]);
if($.isArray(arr)==true){
$.each(arr, function(i, n){
alert(i + " : " + n);
});
}
Just use a regular for loop:
for (var i=0; i<arr.length; i++) {
var n = arr[i];
alert(i + " : " + n);
}
or for large arrays, the slightly optimized:
for (var i=0,l=arr.length; i<l; i++) {
var n = arr[i];
alert(i + " : " + n);
}
or if you really hate for loops:
Array.prototype.each = function (callback) {
for (var index=0,l=this.length;index<l;index++) {
var item = this[index];
// index is second arg since it's optional
callback(item,index);
}
}
arr.each(function(n,i){
alert(i + " : " + n);
});
but I'd recommend the for loop to avoid clashing with library modifications or when Firefox suddenly decide to implement its own each method for arrays (some libraries have already been bitten by this).