json object usage with ajax returned array - php

I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.

Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.

<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>

This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}

Related

How to access entry in the javascript object array

I assigned a JSON result from php to a javascript variable.
The result returned looks like below but it gives me undefined undefined
[{"a":"2","u":"jamesoduro","l":"Oduro","f":"James"},{"a":"5","u":"deary.grace","l":"Grace","f":"Dear"}]
I simple know this look like a javascript array with two objects.
I am trying to access the data inside the objects but to no avail.
Below is script:
PHP
<?php
//fetch online users
$array = array();
$sql = "SELECT id as a,username as u, lastname as l,firstname as f FROM users WHERE active =1 limit 2";
$q = mysqli_query($dbc_conn,$sql);
while($row = mysqli_fetch_assoc($q)){
$array[] = $row;
}
$json = json_encode($array);
echo $json;
?>
JQUERY
$(document).ready(function(){
//checking online users
setTimeout(function(){
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = response;
console.log(array[0].f +" "+ array[0].l);
}
});
},200);
});
Please what could be the problem?? Thank you
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = JSON.parse(response);
console.log(array[0].f +" "+ array[0].l);
}
});
You get a string from php , need turn the string into a json object .
You have to learn to debug your code to find what is going wrong I guess .
Try deserializing the response:
var array = JSON.parse(response);
EXPLANATION
The response you get from the ajax call is of type string, so you have to convert it to an object. That's what JSON.parse() method do: it parses the JSON string and creates the object that this string represent, following specific rules (The parsed string must be in a valid JSON format).
Keep your server side PHP script code neat and clean
Start PHP block from first character of first line.
Do not close php block if there is no output in HTML format.
Use ob_clean() function before echo output in is your are in developer mode and display error is enabled.
for example
ob_clean();
echo json_encode($array);
In client side, if you are getting JSON response in ajax, pass dataType:'json' in ajax option
$.ajax({
url:"testing.php",
type:"post",
dataType:"json",
success:function(response){
console.log(response[0].f +" "+ response[0].l);
}
});

PHP json_encode to Javascript undefined/null

I'm having an issue returning a JSON from PHP to Javascript. Below is my PHP to create the JSON:
$environment[] = array('id' => $env, 'adjacencies' => $hostnames);
foreach($hostnames as $hostname) {
$environment[] = array('id' => $hostname, 'name' => $hostname, 'data' => array());
}
return json_encode($environment);;
When I print the json_encode environment to a text file, it comes back as:
[{"id":"Dev","adjacencies":["tb23","tbwag","tbvg","tbut"]},{"id":"tb23","name":"tb23","data":[]},{"id":"tbwag","name":"tbwag","data":[]},{"id":"tbvg","name":"tbvg","data":[]},{"id":"tbut","name":"tbut","data":[]}]
It seems that this is printing out properly but when I return it to the Javascript its coming back as undefined/null. Below is the javascript with the ajax call:
var ajax = new AJAX();
var args = "id=" + $("#apps").val() + "&env=" + node.id + "&nocache=" + (new Date()).valueOf();
ajax.connect("POST", "http://" + window.location.hostname + "/project/graph/host", args, function(json) {
var output = '';
for (property in json) {
output += property + ': ' + json[property]+'; ';
}
alert(output);
});
I've obviously tried a lot of different things to get it to print out but haven't had any luck. In PHP, I've tried json_last_error and it came back as '0', which means that there isn't an issue with the JSON structure.
In the end, I'd like to use the following command in Javascript to continue building my graph:
var hostNodes = eval('(' + json + ')');
Any help is appreciated as to why I can't get this to come back!
Keep your PHP code in an unique file that receives one post parameters, then construct the json array if it set, and at the bottom you can do
echo json_encode($json);
flush();
I'm not a professional with pure javascript and I'm not familar with your approach, but you should consider using jQuery, at least I'm going to suggest one way to receive an json array so that you can easily work with it (you also make sure that the data is json):
$.ajax(
{
// Post select to url.
type : 'post',
url : 'myPHPAjaxHandler.php',
dataType : 'json',
data :
{
'select' : true
},
success : function(data)
{
// PHP has returned a json array.
var id, hostname;
for(var i = 0; i < data.length; i++)
{
id = data[i].id;
hostname = hostname[i].id;
// Construct a string or an object using the data.
}
},
complete : function(data)
{
// Optional.
}
});
Like I say, It's there for you to decide whether you pick it up or not. It can become handy for complex projects.
It looks like you're assuming that the data passed to the callback function will be your JSON already parsed into JS objects, but I don't see any indication that that would be the case; it's most likely the raw JSON data that must be parsed into JS objects using JSON.parse (NOT eval() - eval() is very dangerous, you should always prefer JSON.parse when working with true JSON data, as it will not permit XSS-style attacks as they are generally not "pure" JSON.)

json_encode creating malformed JSON data?

I have a codeigniter application returns some data from my database to a view. I'm trying to send it back as json data.
The problem is that the data that is returned it malformed.
it looks like this:
({'2.5':"Admin1", '2.10':"Admin2"})
When I test this on jsonlint.com, it shows that this is not valid json.
the '2.5' should be in double quotes, not single quotes.
What I don't understand is that I'm calling json_encode on my data before I pass it to the view. My code in my controller looks like this:
public function getbuildings()
{
$buildings = array();
$branchID = $this->uri->segment(3);
$buildingforbranch = array();
$_locations = $this->racktables_model->get_locations();
//print_r($_locations);
foreach ($_locations as $location)
{
if ((isset($location['L2FullID'])) && (!array_key_exists($location['L2FullID'],$buildings))) {
$buildings[$location['L2FullID']] = $location['L2Location'];
}
}
foreach ($buildings as $key => $value)
{
$pattern = "/(".$branchID."\.\d)/i";
if (preg_match($pattern,$key))
{
$buildingforbranch[(string)$key] = $value;
}
}
header ('Content-Type: application/json; charset=UTF-8');
echo json_encode($buildingforbranch);
}
As you can see from the code, I've even tried casting $key explicitly to a string data type. But that doesn't seem to change anything. Any suggestions?
Thanks.
EDIT 1
When I do a var dump on $buildingforbranch right before the header / json_encode() calls, I get the following results:
array(3) {
["2.5"]=>
string(7) "Admin 2"
["2.10"]=>
string(7) "Admin 1"
["2.11"]=>
string(3) "SB4"
}
It looks good here ... but when I do a console.log() and pass in the data from the controller, the browser shows the incorrectly formed json data.
EDIT 2
Here's what i'm trying to accomplish. I need to dynamically create a combo box when a user clicks on a control on my page. If the ajax call results in an empty array, I don't want to display the combo. Otherwise, I try to populate the combo box with the results of the ajax call. Everything is working, except for the part where I'm attempting to check the length of the json data. My app always displays a combo box regardless of what is sent back.
Here's the code:
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
console.log("getbuildings ajax call successfull");
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
//console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
console.log(JSONdata);
if (JSONdata.length != 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
} //end inner for
$('#l2locations').html(htmlstring);
}//end outer for
}
else {
//alert('i think undefined');
$('#l2locations').html('');
}
}//success
});//end ajax
If I call the page that is returning the json data directly, i get [] as the result for an empty array.
[] is actually defines an array with a single element in your particular case. But as I see you are using jQuery ajax with dataType: "json", this means that the returned value is already an object, you don't need to parse it one more time, so just remove []:
var JSONdata=returnDataFromController; // instead of var JSONdata=[returnDataFromController];
As stated in your other question, you need to handle the JSON as JSON.
Basic overview is:
returnDataFromController will be a string, use JSON.parse() or jQuery's parseJson() to convert it to a JSON object
Rewrite your loop that generates the options to iterate over a JSON object, instead of an array. Note that jquery.each() can handle both arrays and objects will handle This appears to be the part that you're missing . . .
The real key here is keeping datatypes straight. You're getting a string back, that contains JSON data. There's no easy way to convert that to an array, so read it in as JSON. Since it's now a JSON object, you have to treat it as a JSON object, not an array.
Check the jQuery Utilities category for other JSON related items.
Use firebug on firefox to see what is shown in "response" tab on "net" tab
This code
<?php
echo json_encode(array(
"2.5" => "Admin 2",
"2.10" => "Admin 1",
"2.11" => "SB4"
));
produces this output {"2.5":"Admin 2","2.10":"Admin 1","2.11":"SB4"} on my server (php5.3) and on this fiddle example
http://www.phpfiddle.org/main/code/xqy-ize

Pass array from php back to javascript and loop over it

Hi I'm working on passing back an array from php to javascript. I learned online that I should use json_encode on the array when passing it back but now that i have it in the ajax i'm unsure how i can loop over it because doing things like response[0] gives me [ and response[1] gives me " although when writing the entire thing to the document using innerHTML i can see it looks like an array but using a for loop gives me each letter like i stated above with the response[0] equaling [ rather than the first entry. What am i doing wrong? Any help is greatly appreciated!
PHP
<?PHP
$link = mysql_connect('localhost', 'root', 'root');
mysql_select_db("Colleges");
$result = mysql_query("SELECT * FROM `Colleges` ORDER BY School");
$schools = array();
while ($row = mysql_fetch_array($result)) {
array_push($schools, $row['School']);
}
mysql_close();
die(json_encode($schools));
?>
Ajax
<script type="text/javascript">
function schools(){
$.ajax({
url: "Schools.php",
type: "POST",
success: function (response) {
//Loop over response
}
});
}
</script>
You should decode your JSON response (which is a string actually) to be able to work with it as with an object:
var respObj = JSON.parse(response);
The other way around is noticing jQuery that JSON will be supplied by the server (with either dataType: 'json' ajax parameter or Content-Type: application/json response header).
In the object you pass to the ajax method, you should try to add dataType: 'json' in order to specify that the result is json, or you could specify it in your php script calling header('Content-type: application/json'); before the call to die();
Doing so will result in your response being the object you expect instead of a string.
Finally, you could leave it as is, and call in your success callback response = $.parseJSON(response); which will take the response string and turn it into an object, see http://api.jquery.com/jQuery.parseJSON/
Use Following if it helps
res=jQuery.parseJSON(response);
for(i=0;i<res.length;i++)
{
alert(res[i].propertyname);
}
here property name implies to the keys on json .In your case it can be 'School' or just a number i or value can also be just res[i]
Javascript
for ( variable in response ) {
alert(results[variable]);
}
JQuery
$.each(response, function(ind, val){
alert("index:" + ind + ". value:" + val);
});

Parsing PHP/JSON data in Javascript

I'm trying to communicate AJAX, JSON to PHP and then PHP returns some data and I'm trying to parse it with Javascrpt.
From the php, server I return,
echo json_encode($data);
// it outputs ["123","something","and more something"]
and then in client-side,
success : function(data){
//I want the data as following
// data[0] = 123
// data[1] = something
// data[3] = and more something
}
But, it gives as;
data[0] = [
data[1] = "
data[2] = 1
It is reading each character but I want strings from the array, not individual characters. What is happening here? Thanks in advance, I am new to Javascript and JSON, AJAX.
JSON.parse(data) should do the trick.
Set the dataType property of the ajax call to json. Then jQuery will automatically convert your response to object representation.
$.ajax({
url : ...,
data : ...,
dataType : "json",
success : function(json) {
console.log(json);
}
});
Another option is to set headers in PHP so that JQuery understand that you send a JSON object.
header("Content-Type: application/json");
echo json_encode($data);
Check this one... Should Work
success : function(data){
var result = data;
result=result.replace("[","");
result=result.replace("]","");
var arr = new Array();
arr=result.split(",")
alert(arr[0]); //123
alert(arr[1]); //something
alert(arr[2]); //......
}
You did not shown function in which you parse data. But you shoud use
JSON.parse
and if broser does not support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js
dataArray = JSON.parse(dataFomXHR);
I'm not sure if this is what you want but why don't you want php to return it in this format:
{'item1':'123','item2':'something','item3':'and more something'}
Well to achieve this, you'll need to make sure the array you json_encode() is associative.
It should be in the form below
array("item1"=>123,"item2"=>"something","item3"=>"more something");
You could even go ahead to do a stripslashes() in the event that some of the values in the array could be URLs
You could then do a JSON.parse() on the JSON string and access the values
Hop this helps!

Categories