Client-side JSON decode jQuery [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please view my other question here
I am trying to work out how to decode a JSON response from a PHP file.
The JSON is structured as follows:
[{
"id": 1,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/amazon-webstore-379672",
"price": " - "
}
}, {
"id": 2,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671",
"price": "\u00a3 50 "
}
}, {
"id": 3,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670",
"price": "\u00a3 50 "
}
}, {
"id": 4,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/1-to-2-developers-to-work-on-a-large-project-379669",
"price": " - "
}
}, {
"id": 5,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-would-like-someone-to-design-some-world-cup-t-shirts-for-379665",
"price": "\u00a3 50 "
}
}, {
"id": 6,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/graphic-design-of-3-x-sample-pages-for-a-website-379664",
"price": "\u00a3 200 "
}
}, {
"id": 7,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/youtube-channel-art-379663",
"price": "\u00a3 9 "
}
}, {
"id": 8,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pr-events-organisation-source-prizes-for-charity-raffle-379661",
"price": "\u00a3 100 "
}
}, {
"id": 9,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/wordpress-thesis-website-finessing-improve-main-opt-in-des-379659",
"price": "\u00a3 40 "
}
}, {
"id": 10,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-would-like-my-logo-redesigned-updated-379651",
"price": "\u00a3 10 "
}
}, {
"id": 11,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pattern-maker-pattern-cutter-379650",
"price": " - "
}
}, {
"id": 12,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/add-captcha-379652",
"price": "\u00a3 30 "
}
}, {
"id": 13,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/setup-salesforce-api-so-we-can-just-pull-data-via-rest-379638",
"price": "\u00a3 31 "
}
}, {
"id": 14,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/simple-map-illustration-379643",
"price": "\u00a3 25 "
}
}, {
"id": 15,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/time-lapse-video-for-indoor-construction-project-12-week-p-379637",
"price": "\u00a3 1.0k "
}
}, {
"id": 16,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-asterisk-vicidial-expert-to-help-support-us-379640",
"price": "\u00a3 15 "
}
}, {
"id": 17,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-freelancer-to-provide-help-setting-up-cytoscape-379641",
"price": "\u00a3 21 \/hr"
}
}, {
"id": 18,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/500-word-article-on-business-today-379632",
"price": "\u00a3 12 "
}
}, {
"id": 19,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/web-interface-app-design-379629",
"price": "\u00a3 20 \/hr"
}
}, {
"id": 20,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/distribute-leaflets-in-central-birmingham-379630",
"price": "\u00a3 7 \/hr"
}
}]
You can view the current AJAX call on my other question (Link at top of this post).
Could anyone shed some light on how I would decode the JSON array client-side?
I'd like to have a structure like this:
<div class="item">
<div class="title">JSON Title</div>
<div class="price">JSON Price</div>
</div>

Note : from your other question, it is not clear if you always expect a json answer, or if you can receive either of json, html, or xml.
If you always expect json :
$.ajax({ url: ..., data: ...,
dataType: 'json', // <- tell jQuery to expect json,
// and to build a js object from the answer
success : function(obj){
//obj is a regular js object, built from the received json
obj[i].info.title; // <- accessing this piece of data
}
});
If your data is sometimes json, sometimes something else :
success: function(data){
var obj
try {
obj = JSON.parse(data);
// if no exception is thrown, data was a valid json string,
// and obj is a regular js object
obj[i].info.title; // <- accessing this piece of data
} catch (e) {
// Maybe do something on error ?
};
}
You can then build a html string like hsuk suggested :
var html = '';
for(i=0; i < obj.length; i++) {
html += '<div class="item">';
html += '<div class="title">' + obj[i].info.title + '</div>';
html += '<div class="price">' + obj[i].info.price + '</div>';
html += '</div>';
}
alert.html(html).fadeIn();

This is how you do it. What you need is JSON.parse()
test.php
<?php
// Ajax-Server Request Handler
if (isset($_GET['loadData'])) {
exit(json_encode(array(
array(
'id' => 1,
'info' => array('title' => 'http://www.peopleperhour.com/job/amazon-webstore-379672', 'price' => ' - ')
),
array(
'id' => 2,
'info' => array('title' => 'http://www.peopleperhour.com/job/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671', 'price' => '\u00a3 50 ')
),
array(
'id' => 3,
'info' => array('title' => 'http://www.peopleperhour.com/job/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670', 'price' => '\u00a3 50 ')
)
)));
}
?>
<!-- Ajax-Client -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Make Ajax Request
$.get("test.php?loadData", function(data)
{
// Parse Data
var jsonResults = JSON.parse(data);
// Iterate Through Results
$.each(jsonResults, function(key, value)
{
// Display Data
$('.results').append(
'<div class="item" id="'+ value.info.id +'">'+
'<div class="title">'+ value.info.title +'</div>'+
'<div class="price">'+ value.info.price +'</div>'+
'</div>'
);
});
});
});
</script>
<!-- HTML Page - Display Result -->
<div class="results"></div>

Actually, the funny bit about JSON (JavaScript Object Notation) is that you can use it as is in Javascript.
Meaning, if your JSON string is {"foo": "bar"}, you can directly use it in Javascript like:
var myObject = {"foo": "bar"};
or
var myJSONString = '{"foo": "bar"}';
var myObject = eval(myJSONString);
But maybe you better go with JSON.Parse , as eval might be vulnerability if you are parsing User Data, that might not necessarily be in JSON format. (EG. Json data that is sent via HTTP, where the client could mess with ti.)

Related

JSON data displayed but table not drawn (using Datables - server side processing)

I am using Yajra's DataTables server side processing. I can see the JSON data but the table is not being populated.
I managed to get DataTables working with client side processing, but as I will eventually have > 50,000 rows of data, I decided to try and implement server side processing by downloading Yajra's DataTables for Laravel 5.8.
When I call my route, I see the data in a JSON format, but I am not seeing the table at all. It says "draw: 0", so I guess there is an issue with drawing the table?
I have tried various solutions mentioned on stack overflow and the official DataTables website, however none seem to work for me. E.g.
- DataTables json is not processed (in Laravel)
- jQuery Datatables - Table not populated for Ajax response
- https://datatables.net/forums/discussion/45444/populate-table-body-with-ajax
The JSON data that I see when I call my route is as follows:
{
"draw": 0,
"recordsTotal": 3,
"recordsFiltered": 3,
"data": [
{
"id": "1",
"customerNr": "98764",
"orderNr": "23478",
"pallet_id": "66788",
"status_id": "2",
"created_by": "Sara",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-09 07:23:20"
},
{
"id": "2",
"customerNr": "99999",
"orderNr": "22222",
"pallet_id": "22335",
"status_id": "1",
"created_by": "Sophie",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-04 08:26:28"
},
{
"id": "3",
"customerNr": "54657",
"orderNr": "89856",
"pallet_id": "11228",
"status_id": "1",
"created_by": "Markus",
"created_at": "08 Jul 2019",
"updated_at": "2019-07-08 06:59:42"
},
],
"input": []
}
Here are the relevant files from my Laravel project:
web.php:
Route::get('returned-shipment', ['uses'=>'ReturnedShipmentController#index', 'as'=>'returned-shipment.index']);
ReturnedShipmentController:
public function index(
{
return DataTables::of(ReturnedShipment::all())->make();
}
index.blade.php:
<div class="row">
<div id="tbl" class="col-sm-12">
<table id="overview" class="cell-border display">
<thead class="tbl-top">
<tr>
<th>Retourennummer</th>
<th>Auftragsnummer</th>
<th>Datum</th>
<th>Zustand</th>
</tr>
</thead>
<tfoot class="tbl-bottom">
<tr>
<th>Retourennummer</th>
<th>Auftragsnummer</th>
<th>Datum</th>
<th>Zustand</th>
</tr>
</tfoot>
</table>
</div>
</div>
<script>
$(document).ready(function () {
var startingStatus = 'angelegt';
var table = $('#overview').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('returned-shipment.index') }}",
"columns": [
{data: 'id'},
{data: 'orderNr'},
{data: 'created_at'},
{data: 'status_id'}
],
"search": {
"search": "angelegt"
},
"dom": "<'row'<'col-sm-4'l><'col-sm-8'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
"paging": true,
"info": true,
"searching": true,
"autoWidth": true,
"language": {
"paginate": {
"previous": "Vorherige Seite",
"next": "Nächste Seite"
},
"search": "Suche:",
"info": "Zeige _START_ - _END_ von insgesamt _TOTAL_ Einträgen",
"lengthMenu": 'Einträge pro Seite' + '<br>' +
'<select class="custom-select mr-sm-2" id="inlineFormCustomSelect">' +
'<option selected value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'<option value="-1">Alle</option>' +
'</select>'
},
initComplete: function () {
/**
* Drop-down filter is created for the 4th column "status" in the header and populates it with
* the different status values
*/
this.api().columns([3]).every(function () {
var column = this;
var select = $('<select><option value="">alle</option></select>')
.appendTo($(column.header()))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
/**
* When clicking on drop-down next to status, the sorting function is not activated
*/
$(select).click(function (e) {
e.stopPropagation();
});
/**
* Once an option in the drop-down next to status has been selected, you can read the text in
* the drop-down
*/
column.data().unique().sort().each(function (d, j) {
if (startingStatus === d) {
select.append('<option SELECTED value="' + d + '">' + d + '</option>')
} else {
select.append('<option value="' + d + '">' + d + '</option>')
}
});
/**
* When drop-down is clicked on, search field is cleared. Otherwise search field must be
* manually cleared before using the drop-down.
*/
$(select).on('click', function () {
table.search(" ").draw();
});
});
}
});
});
</script>
I am expecting to see the table being populated with the data.
If I need to provide any more code or explain something further, please don't hesitate to ask. I am quite new to Laravel and DataTables, so I would greatly appreciate your help.
Thanks in advance! :)
I have checked your current code and checked your JSON. Your JSON file seems to be invalid.
{
"draw": 0,
"recordsTotal": 3,
"recordsFiltered": 3,
"data": [
{
"id": "1",
"customerNr": "98764",
"orderNr": "23478",
"pallet_id": "66788",
"status_id": "2",
"created_by": "Sara",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-09 07:23:20"
},
{
"id": "2",
"customerNr": "99999",
"orderNr": "22222",
"pallet_id": "22335",
"status_id": "1",
"created_by": "Sophie",
"created_at": "04 Jul 2019",
"updated_at": "2019-07-04 08:26:28"
},
{
"id": "3",
"customerNr": "54657",
"orderNr": "89856",
"pallet_id": "11228",
"status_id": "1",
"created_by": "Markus",
"created_at": "08 Jul 2019",
"updated_at": "2019-07-08 06:59:42"
}
],
"input": []
}
This is the correct format. The comma after the last object in your data array needs to be removed. Can you confirm this solves your issue? I got datatables working without this comma.

Get JSON response from API using PHP, format the JSON data into HTML using Javascript

I'm very new to coding.
I'm using PHP to get a JSON response from an API. The JSON response consists of Titles and URLs to pages on the web. The sample JSON response is at the bottom of the page.
How do I write each item in this JSON data using PHP to my HTML page in the body tag? I want to create HTML "a" tags with the text being the JSON name value and the href being the JSON url value for each item.
Where does the JSON data end up after I get it from the API using PHP, and then how do I access it and format it with PHP? I'm using PHP to keep my API access key server side so the client can't see it. Here is my code:
<?php
$accessKey = "12345678";
$endpoint = '*Imaginary API endpoint*';
$term = 'hi';
function APIResponse ($url, $key, $query) {
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query), false, $context);
$headers = array();
foreach ($http_response_header as $k => $v) {
$h = explode(":", $v, 2);
if (isset($h[1]))
if (preg_match("/^APIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
$headers[trim($h[0])] = trim($h[1]);
}
return array($headers, $result);
}
if (strlen($accessKey) == 8) {
print "Searching the Web for: " . $term . "\n";
list($headers, $json) = APIResponse($endpoint, $accessKey, $term);
print "\nRelevant Headers:\n\n";
foreach ($headers as $k => $v) {
print $k . ": " . $v . "\n";
}
print "\nJSON Response:\n\n";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
} else {
print("Invalid API subscription key!\n");
print("Please paste yours into the source code.\n");
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- This is the result I'm looking for -->
<?php echo JSON:webPages:value:id ?>
</body>
</html>
JSON Response:
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "hi"
},
"webPages": {
"webSearchUrl": "https:\/\/imaginaryapi.com\/search?q=hi",
"totalEstimatedMatches": 65700000,
"value": [
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.0",
"name": "Hi | Define Hi at Dictionary.com",
"url": "https:\/\/www.dictionary.com\/browse\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.dictionary.com\/browse\/hi",
"snippet": "After you insisted, you write that, \u201cno one from the crew would meet my eyes or say hi.\u201d",
"dateLastCrawled": "2018-10-09T15:57:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.1",
"name": "Fors\u00ed\u00f0a | H\u00e1sk\u00f3li \u00cdslands",
"url": "https:\/\/www.hi.is\/",
"about": [
{
"name": "University of Iceland"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.hi.is",
"snippet": "Opi\u00f0 fyrir ums\u00f3knir um innritun \u00ed H\u00e1sk\u00f3la \u00cdslands \u00e1 vormisseri 2019 - Takmarka\u00f0ur hluti n\u00e1mslei\u00f0a \u00ed bo\u00f0i. Ums\u00f3knarfrestur \u00ed framhaldsn\u00e1m til 15. okt\u00f3ber og grunnn\u00e1m til 30. n\u00f3vember",
"deepLinks": [
{
"name": "Vefp\u00f3stur",
"url": "https:\/\/www.hi.is\/haskolinn\/vefpostur"
},
{
"name": "Leit A\u00f0 Starfsf\u00f3lki",
"url": "https:\/\/www.hi.is\/starfsmannaleit"
},
{
"name": "S\u00e6kja Um N\u00e1m",
"url": "https:\/\/ugla.hi.is\/umsoknir\/index.php"
},
{
"name": "Endurmenntun H\u00ed",
"url": "https:\/\/www.hi.is\/nam\/endurmenntun_hi"
},
{
"name": "Stundat\u00f6flur",
"url": "https:\/\/www.hi.is\/laeknadeild\/stundatoflur"
},
{
"name": "Fr\u00e9ttir",
"url": "https:\/\/www.hi.is\/frettir"
}
],
"dateLastCrawled": "2018-10-10T18:35:00.0000000Z",
"language": "is",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.2",
"name": "Hi | Definition of Hi by Merriam-Webster",
"url": "https:\/\/www.merriam-webster.com\/dictionary\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.merriam-webster.com\/dictionary\/hi",
"snippet": "These example sentences are selected automatically from various online news sources to reflect current usage of the word 'hi.' Views expressed in the examples do not represent the opinion of Merriam-Webster or its editors.",
"dateLastCrawled": "2018-10-10T10:35:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.3",
"name": "HI - Wikipedia",
"url": "https:\/\/en.wikipedia.org\/wiki\/HI",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/en.wikipedia.org\/wiki\/HI",
"snippet": "Hi (or Hello) is a frequent act of greeting or welcoming someone.HI or Hi may also refer to:",
"dateLastCrawled": "2018-10-10T15:53:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.4",
"name": "Hi (#hi) | Twitter",
"url": "https:\/\/twitter.com\/hi",
"thumbnailUrl": "https:\/\/www.bing.com\/th?id=OIP.PqKuxRwx55VE6E--5HFwKQAAAA&pid=Api",
"about": [
{
"name": "Hi"
},
{
"name": "Hi"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/twitter.com\/hi",
"snippet": "The latest Tweets from Hi (#hi). BYEBYE Hi en daarmee ook dit account. We zijn nog wel in de lucht, maar niet actief. Voor servicevragen kun je terecht bij #KPNwebcare. Doei!. Den Haag, Zuid-Holland",
"dateLastCrawled": "2018-10-05T00:19:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.5",
"name": "H\u00ef Ibiza - Brand-New Club in Ibiza, Spain",
"url": "https:\/\/www.hiibiza.com\/en",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.hiibiza.com\/en",
"snippet": "H\u00ef Ibiza is the brand new club by Ushua\u00efa Entertainment located in the heart of Ibiza clubland, Playa d'en Bossa. The club will stay true to the open-minded spirit of Ibiza, bringing together music lovers to dance, discover and experience the magic of the White Isle.",
"dateLastCrawled": "2018-10-09T13:58:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.6",
"name": "Danielle Bregoli is BHAD BHABIE \u201cHi Bich \/ Whachu Know ...",
"url": "https:\/\/www.youtube.com\/watch?v=1NyMSWqIJDQ",
"about": [
{
"name": "YouTube"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.youtube.com\/watch?v=1NyMSWqIJDQ",
"snippet": "\ud83d\udea8STREAM \"Hi Bich\" \ufe0f https:\/\/Atlantic.lnk.to\/hibich \ud83d\udda4\ud83d\udc80\ud83c\udfa4\ud83d\udd25 new songs - \u24f5 video HI BICH & WHACHU KNOW by BHAD BHABIE aka Danielle Bregoli\ud83d\udda4\ud83d\udc45\ud83d\udc34\ud83c\udfc1 produced by Ronn...",
"dateLastCrawled": "2018-10-08T04:50:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.7",
"name": "Hi - Capture. Write. Publish",
"url": "http:\/\/hitotoki.org\/",
"isFamilyFriendly": true,
"displayUrl": "hitotoki.org",
"snippet": "pancakes, Hi Meta, writing Full stack writing (and publishing): Welcome to Hi by Craig Mod. Tokyo \u2014 We\u2019d like to welcome you to Hi: A community of writers, journalists, journalers, illustrators, photographers, travelers, poets, and musicians exploring the world, and sharing those explorations throug...",
"dateLastCrawled": "2018-10-10T20:13:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.8",
"name": "Hi - definition of hi by The Free Dictionary",
"url": "https:\/\/www.thefreedictionary.com\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.thefreedictionary.com\/hi",
"snippet": "2. HI - a state in the United States in the central Pacific on the Hawaiian Islands",
"dateLastCrawled": "2018-10-09T09:35:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.9",
"name": "Hi, Hi, Hi - Wikipedia",
"url": "https:\/\/en.wikipedia.org\/wiki\/Hi,_Hi,_Hi",
"about": [
{
"name": "Hi, Hi, Hi"
},
{
"name": "Hi, Hi, Hi"
},
{
"name": "Hi, Hi, Hi"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/en.wikipedia.org\/wiki\/Hi,_Hi,_Hi",
"snippet": "\"Hi, Hi, Hi\" is a song written by Paul and Linda McCartney and performed by Wings. It was released as a double A-side single with \"C Moon\" in 1972.The song was recorded around the same time as \"C Moon\", in November 1972.",
"snippetAttribution": {
"license": {
"name": "CC-BY-SA",
"url": "http:\/\/creativecommons.org\/licenses\/by-sa\/3.0\/"
},
"licenseNotice": "Text under CC-BY-SA license"
},
"dateLastCrawled": "2018-10-10T20:41:00.0000000Z",
"language": "en",
"isNavigational": false
}
],
"someResultsRemoved": true
},
"rankingResponse": {
"mainline": {
"items": [
{
"answerType": "WebPages",
"resultIndex": 0,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.0"
}
},
{
"answerType": "WebPages",
"resultIndex": 1,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.1"
}
},
{
"answerType": "WebPages",
"resultIndex": 2,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.2"
}
},
{
"answerType": "WebPages",
"resultIndex": 3,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.3"
}
},
{
"answerType": "WebPages",
"resultIndex": 4,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.4"
}
},
{
"answerType": "WebPages",
"resultIndex": 5,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.5"
}
},
{
"answerType": "WebPages",
"resultIndex": 6,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.6"
}
},
{
"answerType": "WebPages",
"resultIndex": 7,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.7"
}
},
{
"answerType": "WebPages",
"resultIndex": 8,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.8"
}
},
{
"answerType": "WebPages",
"resultIndex": 9,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.9"
}
},
{
"answerType": "RelatedSearches",
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#RelatedSearches"
}
}
]
}
}
}
To print the data, you can use:
$result = json_decode ( $json, true);
foreach ( $result["webPages"]["value"] as $data)
{
echo "" . $data["name"] . "\n";
}
I like to use json_decode() method returning array instead of object, using true as second parameter, but you can also use it as object if you prefer.
Try this in the javascript section...
document.body.onload = addLink;
function addLink () {
// FIRST method : Embedding php in javascripts
<?php foreach(json_encode($json)->webPages->value as $value) { ?>
// Create a new markup
var newContent = $('<?php echo $value->id ?>');
// And add the text node to your div by it's class / id
$('.link').appendChild(newContent);
<?php } ?>
//////////////
// ...OR... //
//////////////
// SECOND method : Pass php variable (in this case it's JSON object) into javascripts
var json = <? echo json_encode($json)->webPages->value ?>;
json.forEach(function(value){
// Create a new markup
var newContent = $('' + value.id + '');
// And add the text node to your div by it's class / id
$('.link').appendChild(newContent);
});
}
Hopefully it works, because I'm not a daily php coder.

php parse a Json file [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
i'm using this API called "pollDaddy",
using php to retrieve json responses ..I've come across a little hiccup..
How do you get the total of each answer?
My json data:
{
"pdResponse": {
"partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301",
"userCode": "123456-FErKS5yu15scpSGmvip4JA==",
"demands": {
"demand": {
"result": {
"answers": {
"answer": [{
"text": "Yes",
"id": "23123124",
"total": "1074",
"percent": "89.13"
}, {
"text": "No",
"id": "23123125",
"total": "131",
"percent": "10.87"
}]
}, "id": "690432265"
}, "id": "GetPollResults"
}
}
}
}
First we have to decode the json data. so we use json_decode. Then we select the right element and loop through it to get all the anwers
$data = '{ "pdResponse": { "partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301", "userCode": "123456-FErKS5yu15scpSGmvip4JA==", "demands": { "demand": { "result": { "answers": { "answer": [{ "text": "Yes", "id": "23123124", "total": "1074", "percent": "89.13" }, { "text": "No", "id": "23123125", "total": "131", "percent": "10.87" }] }, "id": "690432265" }, "id": "GetPollResults" } } } }';
$response = json_decode($data);
$answers = $response->pdResponse->demands->demand->result->answers->answer;
foreach($answers as $a)
{
echo $a->total;
}

Autocomplete Json response format with zf2

I used JQuery-Autocomplete with Zend framework 2
the Response from the server must be JSON formatted following JavaScript object :
[
{ value: 'Afghan afghani', data: 'AFN' },
{ value: 'Albanian lek', data: 'ALL' },
{ value: 'Algerian dinar', data: 'DZD' },
{ value: 'European euro', data: 'EUR' },
{ value: 'Angolan kwanza', data: 'AOA' },
{ value: 'East Caribbean dollar', data: 'XCD' },
]
This is my ajax Action
public function autocompleteAction()
{
$Keyword = "c";
$product = $this->getProduitsTable()->getProduitComplete($Keyword);
foreach ($product as $item) {
$row['value'] = htmlentities(stripslashes($item->PROD_DESIGNATION));
$row['id'] = (int)$item->PROD_ID;
$row_set[] = $row;//build an array
}
$result = new JsonModel ($row_set);
return $result;
}
I get this results
{
"0": {
"value": "BIc",
"data": 3
},
"1": {
"value": "Eastpak Valise \u0026agrave; roulettes, 78 L, Multicolore- Stripe In",
"data": 4
},
"2": {
"value": "Rainex Rock\u0027s 100 Sous-chemises",
"data": 5
},
"3": {
"value": "Roller correcteur rechargeable - Pritt - 4,2mm",
"data": 6
},
"4": {
"value": "10 Craies de couleur - Elami - Assortiment",
"data": 7
},
"5": {
"value": "Cartouche jet d\u0027encre Office Depot Compatible HP",
"data": 11
},
"6": {
"value": "Cartouche jet d\u0027encre HP C4837A 11 Magenta",
"data": 12
},
"7": {
"value": "Moniteur LCD HP 23cw 58.4 cm (23\u0026quot;)",
"data": 13
},
"8": {
"value": "Unit\u0026eacute; centrale Lenovo 90BJ003TFR",
"data": 14
},
"9": {
"value": "Ensemble PC ASUS UC K31ADE-FR008T + Ecran VS228DE 54.6 cm (21.5\u0026quot;)",
"data": 15
},
"10": {
"value": "Ordinateur portable ASUS Premium R511LJ 39.6 cm (15.6\u0026quot;) 6 Go Windows 8.1 64 Bits",
"data": 16
},
"modulenamespace": "Docs"
}
and this error in :
SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
How do I get Rails to generate JSON in the correct format ?
Thank you very much
Thank you Vikash Kumar :) the Problem was in js file
$(function(){
// setup autocomplete function pulling from currencies[] arra
$('#PROD_DESIGNATION').autocomplete({
//// Url:baseUrl+"/ajax/autocomplete", <--- The problem was here
serviceUrl:baseUrl+"/ajax/autocomplete",
onSelect: function (suggestion) {
///
}
});
});

Javascript delete JSON elements

I have this JSON string in a PHP page:
{
"elements": [{
"type": "pie",
"alpha": 0.3,
"animate": [{
"type": "fade"
}, {
"type": "bounce",
"distance": 5
}],
"start-angle": 0,
"tip": "#val# de #total# #percent#",
"colours": ["#d01f3c", "#356aa0", "#C79810"],
"values": [{
"value": 1,
"label": "procesador amd sempron 140"
}, {
"value": 1,
"label": "procesador sempron le130"
}, {
"value": 1,
"label": "procesador amd a4-3300 x2"
}, {
"value": 1,
"label": "procesador intel celeron g530"
}]
}],
"title": {
"text": "Procesadores, Reinicio",
"style": "color: #356aa0; font-size: 20px"
},
"bg_colour": "#FFFFFF",
"x_axis": null
}
I call it like this:
$.getJSON("restart_proce.php", function(json)
{
console.log(json);
I need to transform it to this:
[{\"value\": 1, \"label\": \"procesador amd sempron 140\" }, { \"value\": 1, \"label\": \"procesador sempron le130\" }, { \"value\": 1, \"label\": \"procesador amd a4-3300 x2\" }, { \"value\": 1, \"label\": \"procesador intel celeron g530\" } ]
I'm trying to delete elements like this:
delete json.elements[3];
but it doesn't delete anything. How can I make it work?
Removing an item from an Array:
There are several ways. The splice method is the most versatile:
data.items.splice(3, 1); // Removes three items starting with the 2nd,
splice modifies the original array, and returns an array of the items you removed.
Try this:
json.elements.splice(3, 1);
See: Array.splice
Just modify the values directly before console.log(json)
json= json.elements[0].values
Or in the restart_proce.php php page just echo
echo json_encode($data['elements'][0]['values']); // if associative array is used.
Try this:
var data = {"result":[
{"FirstName":"Test1","LastName":"User","Email":"test#test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
{"FirstName":"user","LastName":"user","Email":"u#u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
{"FirstName":"Ropbert","LastName":"Jones","Email":"Robert#gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
{"FirstName":"hitesh","LastName":"prajapti","Email":"hitesh.prajapati#phptalent.com","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
]
}
alert(data.result);
delete data.result[3];
alert(data.result);
working JSFiddle
or You can use splice to remove elements from an array.

Categories