How to read json response - php

I have a json response in the form of data with format like this. It is part of the whole data released
JSON Data Here
I have made ​​a script to read the data :
$(document).ready(function() {
$.getJSON('http://services.berthojoris.com/json/baca2.php', function(data) {
for(var i=0; i<data[0].actionDetails.length;i++){
document.write('Judul Halaman : '+ data[1].actionDetails[i].pageTitle+"<br>");
document.write('URL : '+ data[1].actionDetails[i].url+"<hr>");
}
});
});
But the data generated using getJSON only 1, 2 or 5 data. While there are actually a lot of results generated process.
How do I capture all of the data generated??
I just wanted to take the pageTitle and url data from the data.

At first glance, you are mixing data[0] and data[1] (it will display all action details from the first item in the data array)
$(document).ready(function() {
$.getJSON('http://services.berthojoris.com/json/baca2.php', function(data) {
for(var i=0; i<data[0].actionDetails.length;i++){
document.write('Judul Halaman : '+ data[0].actionDetails[i].pageTitle+"<br>");
document.write('URL : '+ data[0].actionDetails[i].url+"<hr>");
}
});
});
If you want to display all action items in data
$(document).ready(function() {
$.getJSON('http://services.berthojoris.com/json/baca2.php', function(data) {
$.each(data, function(idx, item){
$.each(item.actionDetails, function(idx, actionDetail){
document.write('Judul Halaman : '+ actionDetail.pageTitle+"<br>");
document.write('URL : '+ actionDetail.url+"<hr>");
})
})
});
});
Also note, you may have to use $('body').append(string) instead of document.write(string)

Related

Autocomplete from selected data in combobox : jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

Im trying to make autocomplote for my form, the data was from selected combobox.
Heres my controller :
public function cari(){
$kode_list=$this->request->getVar('list_produksi_toko');
//$kode_list=$_GET['kode_list'];
$cari['hasil'] =$this->produksiModel->mencari($kode_list);
echo json_encode($cari);
}
model :
public function mencari($keyword)
{
//$query= $this->builder()->getWhere('list_produksi_toko',array('kode_list'=>$id));
$query = $this->groupBy('kode_list')->like('kode_list', $keyword)->findAll();
return $query;
}
and javascript in my view :
<script>
$('#produk').change(function(){
var list_produksi_toko = $(this).val();
$.ajax({
url:"/Produksi/cari",
method: 'post',
data:{list_produksi_toko: list_produksi_toko},
success:function(data){
jQuery.parseJSON(data);
// var ddas = data.buyer
alert (data);
$.each(data, function(key, val){
$('#buyer').val('<value="'+data['buyer']+'">');
// document.getElementById('nama_barang').value=val.nama_barang;
// document.getElementById('jenis_kain').value=val.jenis_kain;
// document.getElementById('warna').value=val.warna;
// document.getElementById('pcs').value=val.pcs;
});
}
})
});
// $.ajax({
// url: '/ProduksiModel/getProduksi',
// data:"produk="+produk ,
// }).success(function (data) {
// var json = data,
// obj = JSON.parse(json);
// $('#buyer').val(obj.nama);
// $('#status_order').val(obj.status_order);
// $('#nama_barang').val(obj.nama_barang);
// $('#jenis_kain').val(obj.jenis_kain);
// $('#warna').val(obj.warna);
// $('#pcs').val(obj.pcs);
// });
// }
</script>
I have a problem to show each data to each form, with this code it show error in the console like this:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in {"hasil":[{"kode_list":"LPT20060001","tanggal":"2020-06-08","status_order":"Full order","buyer":"IK001,Ik Collection","nama_barang":"IK05900,Renata Blouse","jenis_kain":"Mosscreep","warna":"IK05910,Grey","pcs":"63","tanggal_input":"2020-06-18","user":"Dena","keterangan":"Cutting Done"}]}
I already try to alert the data and it show :
{"hasil":[{"kode_list":"LPT20060001","tanggal":"2020-06-08","status_order":"Full order","buyer":"IK001,Ik Collection","nama_barang":"IK05900,Renata Blouse","jenis_kain":"Mosscreep","warna":"IK05910,Grey","pcs":"63","tanggal_input":"2020-06-18","user":"Dena","keterangan":"Cutting Done"}]}
How can I fix it?
You probably need to change the variable type of data to loop through it. You can check the type of the variable by console.log(typeof data). Following is the possible solution for your problem, see if this helps you.
success:function(data){
console.log(typeof data); // should be string
data = jQuery.parseJSON(data);
console.log(typeof data); // should be object
$.each(data['hasil'], function(key, val){
$.each(val, function(subkey, subval){
console.log(subkey);
console.log(subval);
// all values are assigned to the elements with the same id as their keys(as your code suggests)
$('#' + subkey).val('<value="' + subval + '">');
});
});
}

display the array values-ajax

I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery

Filter out data with AJAX

I retrireve data from my MySQL database into a simple table. Above this table I should have a text-input. On entering a keyword into this input, I want to cancel all showing data in the table and display data, found by %LIKE% operator, matching the keyword entered.Something similar does jQueryUi Autcomplete, FooTable and a couple of Yii extensions, but I wanna do it all from scratch. Any ideas on how to do it? Links?
My knowledge:
$.ajax({
url: 'ajax/test.html',
success: function(){
alert('Load was performed.');
}
});
What I am going to give you is not the complete code.
You want to do it yourself so here is only the logic.
In you index.php file
<input type="text" name="autocoplete" id="autocomplete"/>
<div id="result"></div>
<script type="text/javascript">
$(document).on('keyup', '#autocompelte', function(){
var text = $('#autocomplete').val();
$.post('process.php', {text:text}, function(resultData){
//Treat your resultData and convert into HTML for example
$('#result').html(myHTMLResult);
}, 'json'); //I want my result as JSON
});
</script>
process.php
if(true === isset($_GET['text']) && false === empty($_GET['text']))
{
//Do your query where you field is like %$_GET['text']% : example : SELECT * FROM mytable WHERE myfield like %$_GET['text']%
//Store all your result in an array
//Format this array into json to be easy to treat with json
//Send this json back to your index.php file.
echo json_encode($listResult);
}
#ThinkTank thank you very much for the help. It works just fine. Here is my final code:
$(document).ready(function() {
$('#input').keyup(function(eventObject){
//cancel all displaying data in the table if keyword exists
if($(this).val()) {
//$("td").hide();
$("td").remove();
//data hid, now send data to server
var orgValue = $(this).val();
$.ajax({
url: '/products/RetrieveData',
data: 'term='+orgValue,
success: function(data) {
var jsondata=$.parseJSON(data);
$.each(jsondata, function(i, d) {
var row='<tr>';
$.each(d, function(j, e) {
row+='<td>'+e+'</td>';
});
row+='</tr>';
$('#table tbody').append(row);
});
}
});
} else {
$("td").show();
}
});
} );
Just some ideas:
1. Once I find (filter out) what I need, I clear the input with backspace. How do I set the table to the initial state with the data?

JSON matching data and using data

I've only every used json to fetch data to use on pages or set as variables. But now I would like to search json for a matching name then fetch its views from the json
[{"id":1,"name":"Pale","description":"This is a description","url":"http://domain.com//1/pale","views":2212,"createdBy":{"name":"Bill Lumbergh","url":"http://domain.com"},"createdOn":"2013-10-24T22:54:34.183"},
Above is a little example and using the below code only console.logs the entire json which has about 20 id's
$.getJSON( "content.php", { name: 'Pale' } ,function(data){
console.log(data);
});
$.ajax({
url: 'content.php',
dataType: "json",
success: function (data) {
$.each(data, function(k,v){
if (v.name == theme){
console.log(v.views);
}
});
}
});
The Object you put in the code is the one you are passing to the Server, not receiving. {name:'Pale'} is being sent to the server. If you want the name from the JSON file, it's like:
$.getJSON('content.php', function(data){
console.log(data.name);
});
However, if my guess is correct try the following:
$.getJSON('content.php', function(data){
var ary = data.arrayThatHoldsYourObjects, store;
$.each(ary, function(i, v){
if(v.name === 'Pale'){
store = v.views;
}
});
});
store now holds v.views.

jquery ui autocomplete source from json file

I can incorporate jquery ui autocomplete with source from database. How, I am trying to get the source from a prepared json file, the content is like this:-
{"data":[{"id":"1","country_name_en":"USA","country_name_hk":"\u7f8e\u570b"},{"id":"2","country_name_en":"China","country_name_hk":"\u4e2d\u570b"},{"id":"3","country_name_en":"British","country_name_hk":"\u82f1\u570b"}]}
I tried to modify the jquery codes as follow:-
<script>
$( "#country" ).autocomplete({
source: function(request,response) {
$.getJSON('../../database/country.json',{id: data.id},function(data){
alert(data);
})
}
});
</script>
but I think I do not written the format correctly. How shall I improve the way to extract the data from the json file?
The autocomplete won't show anything until you tell it to do so by calling the response function passed to your source method with the allowed autocomplete values. So you should do something like this:
$( "#country" ).autocomplete({
source: function(request,response) {
$.getJSON('../../database/country.json',{id: data.id},function(data){
var choices = [];
for(var i=0;i<data.data.length;i++) {
choices.push(data.data[i].country_name_en);
}
response(choices);
})
}
});
Also just a tip, you're going to confuse yourself by naming everything "data".
Ajax can be used for this refer this article which list countries from geonames.org(contains huge list country,state,regions). This will help you in some way.
To get data from json try this..
$("#country").autocomplete({
source: function(request, response) {
$.getJSON('../../database/country.json', { id: data.id }, function(data) {
$.each(data, function(key, value) {
alert(value.country_name_en); // json data
});
});
}
});
The problem is, you need to call the autocomplete callback from the ajax success handler.
$(function() {
$("#country").autocomplete({
source : function(request, response) {
$.getJSON('country.json', {
id : 1
}, function(data) {
var list = $.map(data.data, function(item, index) {
return {
id : item.id,
label : item.country_name_en
};
});
response(list);
})
}
});
})
Demo: Plunker

Categories