json_encode and getJSON - php

I am using PHP at server side to get json formatted output as below. At client side I use jQuery to display the results but it displays null. Please let me know where I went wrong. Any help is appreciated.
PHP
while ($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
Output
[
{
"a_name": "affles",
"bname": "bua",
"c_number": "10101010",
"dateandtime": "2013-11-30 17:50:04"
},
{
"a_name": "affles",
"bname": "bua",
"c_number": "10101010",
"dateandtime": "2013-11-30 17:50:04"
},
{
"a_name": "anan",
"bname": "nesh",
"c_number": "2017439441",
"dateandtime": "2013-12-04 17:50:04"
}
]
Client side
$.getJSON("http://apip.com/results.php", function (data) {
$.each(data, function (index, value) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
Client side code using JSONP: I modified client side to use JSONP but still it returns null. An help is appreciatd
<script>
(function() {
var flickerAPI = "http://apip.com/results.php?jsoncallback=?";
$.getJSON( flickerAPI,
(function( data ) {
$.each( data.items, function( index, value ) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
})();
</script>

As you can see from this fiddle, it is working fine. What I do suspect is going wrong is that you're using http://apip.com/results.php and you might be fooling jQuery into thinking you're doing a cross-domain request (which you might be doing), which is generally prohibited by browsers unless you use JSONP. If you own http://apip.com/, use
$.getJSON("/results.php", function (data) {
$.each(data, function (index, value) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});

Related

Return array/object to jquery script from AJAX

Hello all and thanks in advance,
Short story, I am using a plugin to dynamically populate select options and am trying to do it via an ajax call but am struggling with getting the data into the select as the select gets created before the ajax can finish.
First, I have a plugin that sets up different selects. The options input can accept an array or object and creates the <option> html for the select. The createModal code is also setup to process a function supplied for the options input. Example below;
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
let dueDate = {};
for (let i = 1; i < 32; i++) {
dueDate[i] = i;
}
return dueDate;
}
}
});
What I am trying to do is provide an object to the options input via AJAX. I have a plugin called postFind which coordinates the ajax call. Items such as database, collection, etc. are passed to the ajax call. Functions that should be executed post the ajax call are pass through using the onSuccess option.
(function ($) {
$.extend({
postFind: function () {
var options = $.extend(true, {
onSuccess: function () {}
}, arguments[0] || {});
options.data['action'] = 'find';
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof options.onSuccess === 'function') {
options.onSuccess.call(this, obj);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
}
});
}(jQuery));
The plugin works fine as when I look at the output it is the data I expect. Below is an example of the initial attempt.
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
$.postFind({
data: {
database: 'dashboard',
collections: {
accountTypes: {
where: {status: true}
}
}
},
onSuccess: function (options) {
let dataArray = {};
$.each(options, function (key, val) {
dataArray[val._id.$oid] = val.type;
});
return dataArray;
}
})
}
}
});
In differnt iterations of attempting things I have been able to get the data back to the options but still not as a in the select.
After doing some poking around it looks like the createModal script in executing and creating the select before the AJAX call can return options. In looking at things it appears I need some sort of promise of sorts that returns the options but (1) I am not sure what that looks like and (2) I am not sure where the promise goes (in the plugin, in the createModal, etc.)
Any help you can provide would be great!
Update: Small mistake when posted, need to pass the results back to the original call: options.onSuccess.call(this, obj);
I believe to use variables inside your success callback they have to be defined properties inside your ajax call. Then to access the properties use this inside the callback. Like:
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
myOptions: options,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof this.myOptions.onSuccess === 'function') {
this.myOptions.onSuccess.call(this);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
It's not clear to me where the problem is without access to a functional example. I would start with a simplified version of what you want to do that demonstrates the proper functionality. My guess is the callbacks aren't setup exactly correctly; I would want to see the network call stack before making a more definitive statement. A few well-placed console.log() statements would probably give you a better idea of how the code is executing.
I wrote and tested the following code that removes most of the complexity from your snippets. It works by populating the select element on page load.
The HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select data-src='test.php' data-id='id' data-name='name'></select>
</body>
</html>
<html>
<script>
$('select[data-src]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-src'),
data: {'v0': 'Alligator', 'v1': 'Crocodile'}
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val (option[$select.attr('data-id')])
.text(option[$select.attr('data-name')]);
$select.append($option);
});
});
});
</script>
And the PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
echo json_encode([
[ 'id' => 0, 'name' => 'Test User 0' ],
[ 'id' => 3, 'name' => $_GET['v0'] ],
[ 'id' => 4, 'name' => $_GET['v1'] ]
]);
Here's a fiddle that also demonstrates the behavior.

Display JSON Data in HTML using Laravel 4

Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"

jQuery $.post Callback Function (data) is Undefined

I submit a form using jQuery to a php file on my server.
Everything works... (the php file gets the right post variables, makes a database entry etc.)
But on the response, sometimes 'data' goes wacky.
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
if ( data.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
}, "json");
});
php script returns (on success)
$response['status'] = 1;
$response['message'] = 'worked';
echo json_encode($response);
exit();
I'm getting a whole lot of crap, and not enough awesome sauce.
Does anyone have an idea why sometimes 'data.status' is undefined, and sometimes it isn't?
Try it like this>
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
var obj = jQuery.parseJSON(data);
if ( obj.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
});
});
How does exit() behave with regards to output buffering? Does it flush the output buffer?
try this one:
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize())
.success(function(){
alert('awesome sauce');
}).error(function(){
alert('crap');
});
});

jQuery AJAX Request Doesn't Work on Page Load, However, It Does Work from Debug Console

Turning off asynchronous requests in jQuery fixed the issue.
I have the following Javascript & AJAX request (using jQuery) in my page:
"use strict";
var hsArea, counter, hotspots, count;
counter = 4;
count = 0;
hotspots = {};
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
});
}
function displayHotspot(type, id, number) {
$.ajax({
url: '/alpha/engine/hotspots/gethotspot.php',
dataType: 'json',
data: {'type' : type, 'id' : id},
success: function(json) {
console.log(json);
var hotspot, extract;
extract = json.content;
extract = extract.replace(/<(?:.|\n)*?>/gm, '');
extract = extract.substring(0, 97);
extract = extract + "...";
json.content = extract;
hotspot = document.createElement("div");
hsArea.append(hotspot);
hotspot.setAttribute('class','hotspot');
hotspot.setAttribute('id','hotspot' + number);
$(hotspot).css('position', 'absolute');
$(hotspot).css('top', number * 100 + 100);
$(hotspot).css('left', number * 100 + 110);
hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
}
function listHotspots() {
for(count = 0; count < counter; count++) {
(function(count) {
displayHotspot('scribble',hotspots[count], count);
count = count + 1;
})(count);
}
}
function loadHotspots() {
fetchHotspotList();
listHotspots();
}
$(document).ready(function() {
hsArea = $("#hotspotArea");
fetchHotspotList();
listHotspots();
});
(Sorry the formatting is a bit off!) - Now, the $(document).ready() function assigns the hsArea variable as it should, however, a combination of fetchHotspotList() and listHotspots() returns:
Uncaught TypeError: Cannot call method 'replace' of null
However, if in the Google Chrome Javascript console, I run:
loadHotspots();
it fetches the data from the AJAX request and displays it properly on the page. At first I thought the problem was that I Wasn't using the $(document).ready() handler, but adding it hasn't fixed it. Neither has using an onload handler inside of the body tag.
Any help would be greatly appreciated.
Regards,
Ben.
It's probably due to the fact that your listHotSpots function is called before fetchHotSpots returns (since it's an async call).
You're better off chaining the execution of listHotSpots to the completion of fetchHotSpots, like so:
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
listHotSpots();
});
}
You may be better off modifying listHotSpots to take the json data returned from your AJAX call. Hope this helps!

JSON returned as individual string and not objects

I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!

Categories