Im trying to populate a combobox with data from database.
When I access mystream.php?theLocation=NewYork
I get this JSON response
RESULT
{"result":
[{"theID":"36"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork"},
{"theID":"37"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork"},
{"theID":"40"},{"theStream":"0817-31334"},{"theLabel":"dsfg ghjg"},{"theLocation":"NewYork"}]}
Applying the answer from this post
loop through JSON result with jQuery
I came up with this JSON
$.getJSON(
'mystream.php',
'theLocation=NewYork',
function(result){
$('#cmbNewYork').empty();
$.each(result, function(i, item){
$('#cmbNewYork').append('<option value=' +item.theStream+ '>'+item.theLabel+'</option>');
alert(item.theStream);
});
}
);
My resulting combo box only contains undefined.
How to properly loop thru JSON response?
Thanks
EDIT (ADDED)
mystream.php
$sql = "SELECT * FROM Streams WHERE theLocation='$loc'";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('theID'=>$row['theID']),
array('theStream'=>$row['theStream']),
array('theLabel'=>$row['theLabel']),
array('theLocation'=>$row['theLocation'])
);
}
echo json_encode(array('result'=>$result));
Two issues:
The primary issue that your JSON format is very strange: It's an array of objects each of which has one name/value pair:
{"result": [
{"theID":"36"},
{"theStream":"0817-05131"},
{"theLabel":"hgjbn"},
{"theLocation":"NewYork"},
{"theID":"37"},
{"theStream":"0817-05131"},
{"theLabel":"hgjbn"},
{"theLocation":"NewYork"},
{"theID":"40"},
{"theStream":"0817-31334"},
{"theLabel":"dsfg ghjg"},
{"theLocation":"NewYork"}
]}
That's 12 separate objects.
You should have objects with all of those properties together:
{
"result": [
{
"theID": "36",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
{
"theID": "37",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
{
"theID": "40",
"theStream": "0817-31334",
"theLabel": "dsfg ghjg",
"theLocation": "NewYork"
}
]
}
That's three objects, each with four properties.
Re your edit to the question, you can do that like this:
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'theID'=>$row['theID'],
'theStream'=>$row['theStream'],
'theLabel'=>$row['theLabel'],
'theLocation'=>$row['theLocation']
)
);
}
Note how that's creating one array per loop, rather than four.
The second issue is that you probably need result.result, rather than just result, on this line:
$.each(result.result, function(i, item){
// ----------^^^^^^^
...since result is your overall anonymous result, which has a single property, result, which has your array.
If you fix those, your loop should start working.
You don't have to do the result.result thing if you don't want to. Instead, you could have your JSON define an array instead of an object with a single property referring to the array:
[
{
"theID": "36",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
(and so on)
]
You haven't shown the PHP code creating $result, so I can't show you how to do that, but A) You don't need to, the result.result thing is fine, and B) If you want to, I'm sure you can figure it out.
Related
JS:
$.getJSON('services/get_locations.php', {region: $("#oblast").val()}, function(data) {
console.log(data);
});
PHP:
$result = json_encode($raw['data']);
echo $result;
exit;
Result from var_dump($result) is:
{
"10971":"\u0433\u0440. \u0412\u0418\u0414\u0418\u041d",
"179":"\u0441. \u0410\u041a\u0410\u0426\u0418\u0415\u0412\u041e",
"919":"\u0441. \u0410\u041d\u0422\u0418\u041c\u041e\u0412\u041e"
}
As you can see, first ID is 10971.
However, the result of console.log(data) is:
{179: "с. АКАЦИЕВО", 919: "с. АНТИМОВО", 10971: "гр. ВИДИН"}
Why is data being reordered?
Javascript objects with numeric keys will always get ordered in ascending order of the numeric key values
If order is important change structure to an array something like [{id:179, value: "...."}] or [[10971,"wrd"],[179,"xyz"]]
Example with no ajax. Note the log order is different than the constructed order (ascending key values)
const data = {
"10971":"\u0433\u0440. \u0412\u0418\u0414\u0418\u041d",
"179":"\u0441. \u0410\u041a\u0410\u0426\u0418\u0415\u0412\u041e",
"919":"\u0441. \u0410\u041d\u0422\u0418\u041c\u041e\u0412\u041e"
}
console.log(data);
console.log('Keys:', Object.keys(data))
I am trying to merge loop data to json object ,every time I am getting the last result of loop only ,so I declared that variable as a array ,its coming fine and I got my result but the format is not coming properly ,there is extra square brackets ,which I dont want ,because while parsing in front end ,its creating problem.
Below i am providing my codes.
{
"status": "success",
"statusReason": "Favouritelist",
"result": {
"Favouritelist": [
[ //want to remove this square bracket
{
"branch_id": "1234",
"branch_name": "avis1",
"branch_image": "uploads/avis.png",
"branch_gps": "12.9250,77.5938",
"branch_address": "eredfdf",
"branch_phone": "2147483647",
}
],//want to remove this square bracket
[//want to remove this square bracket
{
"branch_id": "1234",
"branch_name": "avis1",
"branch_image": "uploads/avis.png",
"branch_gps": "12.9250,77.5938",
"branch_address": "eredfdf",
"branch_phone": "2147483647",
}
]//want to remove this square bracket
]
}
}
My CI code
foreach ($tempquery->result() as $res1){
$car_id = $res1->car_id;
if(empty($timestamp)){
$this->db->select("IFNULL(branch.branch_id,'') as branch_id,IFNULL(branch.name,'') as branch_name,IFNULL(branch.image,'') as branch_image,IFNULL(branch.gps,'') as branch_gps,IFNULL(branch.address,'')as branch_address,IFNULL(branch.phone,'')as branch_phone,(select IFNULL(avg(rating),0) from branch_rating where user_id='$user_id' and delete_status ='false' )as branch_rating,IFNULL(car_id,'') as car_id,IFNULL(cars.name,'') as car_name,IFNULL(cars.image,'') as car_image,IFNULL(model,'') as model,IFNULL(price,'')as price,IFNULL(year,'')as year,IFNULL(type,'')as type,IFNULL(`no_of_seats`,'')as `no_of_seats`,IFNULL(`gear_type`,'') as `gear_type`,IFNULL(color,'') as color,insurance,status,IFNULL(description,'') as description,(select IFNULL(avg(rating),0) from car_rating where user_id='$user_id' and delete_status ='false' )as car_rating,car_types.typename AS carType,cars.petrol_type,car_types.car_type_id,cars.delivery_charges,cars.services");
$this->db->from("branch");
$this->db->join("cars","branch.branch_id=cars.branch_id");
$this->db->join('car_types', 'cars.car_type_id = car_types.car_type_id');
$this->db->where("cars.car_id",$car_id);
$this->db->where("branch.delete_status" , "false");
$this->db->where("cars.delete_status" , "false");
$car_details= $this->db->get();
$cdetail_new[]=$car_details->result(); ///added [] to mearge dat
}
Response::code_200("Favouritelist", array("Favouritelist" => $cdetail_new));
Can any one suggest me ,where I am doing wrong..
Thank you in ADV
Looks like the source is packed with the array. The result() function here, perhaps gives it as an array?
$car_details->result();
If that's the case, you might want to unwrap it here. You can use this notation if you are using latest version of PHP:
$cdetail_new[] = $car_details->result()[0];
If not, try the older one:
$result = $car_details->result();
$cdetail_new[] = $result[0];
You can check if this is the issue or not, i.e., if the result() is giving output as an array with a single element by using:
$car_details = $this->db->get();
var_dump($car_details->result()); // Is this resulting as an array?
die();
$cdetail_new[] = $car_details->result(); ///added [] to mearge dat
I am currently in a bind, JQuery is unable to parse the following json strings
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
The above strings when parse through JSON.parse create the following arror:
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 112 of the JSON data
The PHP code which creates the string above is this:
public function getCustomerSuggestions($name){
$customers = $this->model->where('name','LIKE','%'.$name.'%')->show();
if(count($customers)>=1){
foreach($customers as $customer){
$list[] = ['value' => ucfirst($customer->name),'data' => $customer->id];
}
}
else{
$list[] = ['value' => 'No Customers Found', 'data'=> NULL];
}
$full_list['query'] = 'Unit';
$full_list['suggestions'] = $list;
return json_encode($full_list);
}
As you can see I am using the function json_encode to create the JSOn string so there should be no issue but it still doesnt work.
Edit
The json is sent using an autocomplete tool called DevBridge Autocomplete which takes the JSON strings and creates a suggestion list. The code I am using is
$('input[name=\"customer\"]').devbridgeAutocomplete({
serviceUrl: '".SITE_PATH."/ajax/admin/quotes/getcustomer',
minChars: 1,
onSearchStart: function (query){
var searchinput = $(this).val();
$('.autocomplete-suggestions').html('Searching: '+searchinput);
},
onSelect: function(suggestion){
var selection = $(this).val(suggestion.value);
$('input[name=\"customerid\"]').val(suggestion.data);
$.get('".SITE_PATH."/ajax/admin/quotes/getcustomerdetails',{id: suggestion.data},
function(response){
var obj = $.parseJSON(response);
$.each(obj, function(key, value){
$('#'+key).val(value);
});
});
}
});
It seems you have two JSON objects after each other. That's simply invalid. There can only be a single value at the root of a JSON "document". If you want to send down multiple objects, you need to put them in an array.
It seems getCustomerSuggestions is called multiple times and the return value of each call is returned to the client. Instead, the method should return an array, the caller should collect the return values in an array and JSON encode that array.
Well, your JSON string is NOT valid.
It should be,
[
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
,
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
]
But as Felix Kling said, check your PHP code.
I'm trying to move some processing from client to server side.
I am doing this via AJAX.
In this case t is a URL like this: https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.
First problem, I need to send a bunch of these URLs through this little function, to just pull out "1081244497" using my example. The following accomplishes this in javascript, but not sure how to make it loop in PHP.
var e = t.match(/id(\d+)/);
if (e) {
podcastid= e[1];
} else {
podcastid = t.match(/\d+/);
}
The next part is trickier. I can pass one of these podcastid at a time into AJAX and get back what I need, like so:
$.ajax({
url: 'https://itunes.apple.com/lookup',
data: {
id: podcastid,
entity: 'podcast'
},
type: 'GET',
dataType: 'jsonp',
timeout: 5000,
success: function(data) {
console.log(data.results);
},
});
What I don't know how to do is accomplish this same thing in PHP, but also using the list of podcastids without passing one at a time (but that might be the only way).
Thoughts on how to get started here?
MAJOR EDIT
Okay...let me clarify what I need now given some of the comments.
I have this in PHP:
$sxml = simplexml_load_file($url);
$jObj = json_decode($json);
$new = new stdClass(); // create a new object
foreach( $sxml->entry as $entry ) {
$t = new stdClass();
$t->id = $entry->id;
$new->entries[] = $t; // create an array of objects
}
$newJsonString = json_encode($new);
var_dump($new);
This gives me:
object(stdClass)#27 (1) {
["entries"]=>
array(2) {
[0]=>
object(stdClass)#31 (1) {
["id"]=>
object(SimpleXMLElement)#32 (1) {
[0]=>
string(64) "https://itunes.apple.com/us/podcast/serial/id917918570?mt=2&uo=2"
}
}
[1]=>
object(stdClass)#30 (1) {
["id"]=>
object(SimpleXMLElement)#34 (1) {
[0]=>
string(77) "https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2"
}
}
}
}
What I need now is to pull out each of the strings (the URLs) and then run them through a function like the following to just end up with this: "917918570,1081244497", which is just a piece of the URL, joined by a commas.
I have this function to get the id number for one at a time, but struggling with how the foreach would work (plus I know there has to be a better way to do this function):
$t="https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2";
$some =(parse_url($t));
$newsome = ($some['path']);
$bomb = explode("/", $newsome);
$newb = ($bomb[4]);
$mrbill = (str_replace("id","",$newb,$i));
print_r($mrbill);
//outputs 1081244497
find match preg_match() and http_build_query() to turn array into query string. And file_get_contents() for the request of the data. and json_decode() to parse the json responce into php array.
in the end it should look like this.
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?'.http_build_query(['id'=>25,'entity'=>'podcast'])));
if(preg_match("/id(\d+)/", $string,$matches)){
$matches[0];
}
You may have to mess with this a little. This should get you on the right track though. If you have problems you can always use print_r() or var_dump() to debug.
As far as the Apple API use , to seperate ids
https://itunes.apple.com/lookup?id=909253,284910350
you will get multiple results that come back into an array and you can use a foreach() loop to parse them out.
EDIT
Here is a full example that gets the artist name from a list of urls
$urls = [
'https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.',
'https://itunes.apple.com/us/podcast/dan-carlins-hardcore-history/id173001861?mt=2'
];
$podcast_ids = [];
$info = [];
foreach ($urls as $string) {
if (preg_match('/id(\d+)/', $string, $match)) {
$podcast_ids[] = $match[1];
}
}
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?' . http_build_query(['id' => implode(',', $podcast_ids)])));
foreach ($json_array->results as $item) {
$info[] = $item->artistName;
}
print '<pre>';
print_r($info);
print '</pre>';
EDIT 2
To put your object into an array just run it through this
foreach ($sxml->entries as $entry) {
$urls[] = $entry->id[0];
}
When you access and object you use -> when you access an array you use []. Json and xml will parse out in to a combination of both objects and arrays. So you just need to follow the object's path and put the right keys in the right places to unlock that gate.
I am currently making an auto-complete form. Right now, the values of suggestions are from inside a JavaScript list:
<script type="text/javascript">
$('#textarea').textext({
plugins : 'autocomplete suggestions tags filter',
suggestions: [
'Basic',
'Cobol',
'Go'
]
});
I am using a function to get my list of names from a database:
$users->selectFirstnameSurname();
$userQueryResult = $users->queryResult;
$listOfNames = $users->listOfNames;
I am taking the values by appending firstname and lastname from the database, like this:
public function selectFirstnameSurname() {
$query = $this->db->prepare("SELECT * FROM `users` ORDER BY `username`");
$listOfNames[] = '';
try{
$query->execute();
foreach ($query as $row) {
array_push ($listOfNames, $row['firstname'].' '.$row['lastname']);
}
$this->queryResult = $query->fetch();
$this->listOfNames = $listOfNames;
} catch(PDOException $e){
die($e->getMessage());
}
}
What I want to do is get the values of array $listOfNames and replace the suggestions from the script.
You need to have a way to deliver the dataset so that your javascript code can access it. If your dataset is static and JS does the filtering, you could just statically dump them as a JS Object (JSON) like
[
{
"id": 1,
"label": "user name"
},
{
"id": 2,
"label": "other user"
}
]
The exact format of the JSON of course depends on your autocomplete implementation.
Or to make it more dynamic (good idea if you have a big dataset) you could make a simple API called over AJAX to fetch the data. If you need more detail, you can refer a tutorial like http://www.pontikis.net/blog/jquery-ui-autocomplete-step-by-step