I want to loop ajax response
response = [
["u.profile"],
["r.useractivity"],
["i.items_job"],
["i.setup"],
["search"],
["i.items_assortment"]
]
I want data = u.profile;
data = r.useractivity;
etc
Tried Method :
$.each(response,function(key,value){
console.log(key+":"+value);
});
Getting error in console
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [["u.profile"],["r.useractivity"],["i.items_job"],["i.setup"],["search"],["i.items_assortment"]]
The problem is that your response var is an array of arrays (an object) and the default keys are integers.
It would be an easier (and better) way if you could change it into an array of strings like this one :
var response = ["u.profile",
"r.useractivity",
"i.items_job",
"i.setup",
"search",
"i.items_assortment"];
With this, you can easily loop your response like this :
for(var info in response)
console.log(info+':'+response[info]);
Hope this will help !
Related
I have a URL like this http://localhost/phpdemo/edit_data.php?edt_id=1. Here I need the query string value which is 1. By using Angular.js, I am getting the following output in browser's console.
id is : Object {}
My code is given below.
update.js:
var app=angular.module("edit_data", []);
app.controller("updateController",function($scope,$http,$location){
$scope.errors = [];
$scope.msgs = [];
var id=$location.search();
console.log("id is :",id);
$http.get('js/edit.php',{"user_id":$location.hash()}).success(function(response){
console.log('response',response);
});
$scope.update_data=function(){
$http.post('js/update.php',{"first_name":$scope.first_name,"last_name":$scope.last_name,"city":$scope.city}
).success(function(data, status, headers, config){
if(data.msg!=''){
$scope.msgs.push(data.msg);
}else{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
}
});
Please help me to resolve this issue.
$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:
var id=$location.search().edt_id;
Location service Search Little Brief
search(search, [paramValue]);
This method is getter / setter.
Return search part (as object) of current url when called without any parameter.
Change search part when called with parameter and return $location.
// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var searchObject = $location.search();
// => {foo: 'bar', baz: 'xoxo'}
// set foo to 'yipee'
$location.search('foo', 'yipee');
// $location.search() => {foo: 'yipee', baz: 'xoxo'}
This $location.search(); return an array, so
console.log("id is :",id[0]);
Can you try with above.
UPDATE:
$location.search()['edt_id']
It must return the value 1
I am having some trouble updating a Flot bar chart from an Ajax request to a PHP script that returns JSON data.
The PHP script is:
$vars = array(
'result' => "success",
'msg' => AJAX_SUCCESS,
'series' => "Group One,80,Group Two,10"
);
echo json_encode($vars);
This is returned to a variable 'series'
var data = [series.series];
This outputs to the console:
Group One,80,Group Two,10
I also have a commented out variable which is:
//var datatwo = [ ["Group One", 80], ["Group Two", 10] ];
This also outputs to the console
Group One,80,Group Two,10
The actual javascript to create the graph is
$.plot("#group-month-graph", [data], options);
The options are assigned at another location of the script.
Im trying to figure out what Im doing wrong as when I alert the returned data or output it to the console the values are identical, however the returned data will not draw the graph whereas if I use the commented out value it does.
Hope that makes sense. I have cut down the full script as I dont think that the issue lies anywhere else.
You are returning a String while the plugin is expecting an Array. You should return [["Group One",80],["Group Two",10]]
Change your php series structure to:
$vars = array(
'result' => "success",
'msg' => AJAX_SUCCESS,
'series' => array(array("Group One",80),array("Group Two",10))
);
Also, you should be getting the series array using data and not [data]
$.plot("#group-month-graph", data, options);
Using jQuery 1.7.2 and jQuery UI 1.8.18. If I use local data for the source attribute, everything works as expected. According to the documentation, a source array can be an array of string values or an array of objects:
Array: An array can be used for local data. There are two supported
formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
Additionally, the source attribute can be a URL that responds with JSON data formatted as shown above:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
If my JSON responder returns a simple array of strings, autocomplete works exactly as it should. If, however, my JSON responder returns an array of objects formatted as above, the request is made to the URL but the dropdown list is never populated. The JavaScript console shows no errors.
The autocomplete invocation looks like this:
var source_url = '/json/codes.php?type=globalcode&cid=25';
$('.gcode').autocomplete({
minLength: 2,
source: source_url
});
The responder is written in PHP. It is just a stub until I get this problem solved:
header('Content-Type: application/json, charset=UTF-8');
...
if( !$_REQUEST['type'] || !$_REQUEST['cid'] ){
echo('[]');
return false;
}
if( $_REQUEST['type'] == 'globalcode' ){
$cid = sprintf("%d", $_REQUEST['cid']);
$stub = "[ { label: 'Label for 1234', value: '1234' }, { label: 'Label for 5678', value: '5678' } ]";
echo( $stub );
return false;
}
Again, it works with both kinds of arrays when the data is local and it works with an array of string values when the data is remote. When the data is a remote array of objects, the list is never populated and JavaScript throws no errors.
You have invalid JSON, this is never logged in the console.
JSON cannot have single quotes, use double quotes, also use JSONLint to check your JSON.
This is the valid version of your JSON:
[
{
"label": "Labelfor1234",
"value": "1234"
},
{
"label": "Labelfor5678",
"value": "5678"
}
]
You could use json_encode() instead
$stub = array(
array(
"label"=>"Labelfor1234",
"value"=>"1234"
),
array(
"label"=>"Labelfor5678",
"value"=>"5678"
)
);
echo json_encode($stub);
eSo I've got some parsed php data whiched I've fetched from my database and then parsed to JSON with json_encode(). Then I've used JSONparse() to make objects of my array. My code looks like this:
$.get("fetchDatabase.php", function(data){
var parsedData = jQuery.parseJSON(data);
}
I'm left with the array parsedData which looks like this:
[
{"person0":{"name":["Erik Steen"],"age":["1"]}},
{"person1":{"name":["Frida Larsson"],"age":["1"]}},
{"person2":{"name":["Abdi Sabrie"],"age":["2"]}},
{"person3":{"name":["Achraf Malak"],"age":["3"]}},
{"person4":{"name":["Adam Anclair"],"age":["1"]}}
]
I've placed those arrays in an array named
var peopleArray= { people: [ parsedData ] };
So far so good. Now what I want is being able to access certain persons attribute. Like names or age. How do I target those attributes? I've tried to print those attributes with no luck. I tried:
alert (peopleArray.people[0].person1.name);
Whiched returns:
Uncaught TypeError: Cannot read property 'name' of undefined
How can I access those attributes?
Apart from the typo ("namn") the problem is you're putting an array inside an array:
var peopleArray = { people: [ parsedData ] };
Since parsedData is an array then what you end up with is a structure like this:
// peopleArray
{ people : [ [ { "person0" : ... }, ... ] ] }
// oops -----^
See the problem? Since parsedData is a already an array the correct code would be:
var peopleArray = { people: parsedData };
I'm returning rows from a mysql database in php and then making an array of all these rows and then json encoding this. I am then trying to turn that json into autocomplete for jquery, not that relavent. The issue I have is that once I have it in json, there is no defining the rows. How do I access the same json.id that is in every "row" returned in json? here is a sample json object I'm using
[{"id":"95833","fname":"john","lname":"walker","email":"john.walker#john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train#john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}]
I do I access the first id, or the second one?, etc
Here's some sample code showing how to iterate over your data:
var data = [{"id":"95833","fname":"john","lname":"walker","email":"john.walker#john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train#john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}];
for( var i = 0; i < data.length; i ++ )
{
var item = data[i];
var thisID = item.id;
// do something clever here
}
jQuery will parse the JSON into a Javascript array of objects for you:
data[0].id // First id
data[1].id // Second id
I think, I think you're trying to access the "columns", not the rows. Incidentally, this general problem of the relation model of the a SQL database not matching the object model of most languages is called "The Impedance Mismatch", and it sucks. Your particular issue could be addressed (in jQuery) with:
$.map(data, function(n) { return n.id } );
Which will return an array containing all the id values.
If you are using jQuery 1.6 then it's very simple
// to get ['id', 'fname', 'lname', 'email', 'major', 'year', 'gender', 'created']
// you only need to map the first element of the data array and return the key.
var columnArray = $.map(data[0], function (val, k) {
return k;
});
Happy Coding :)