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
Related
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);
});
I'm printing a <ul> of array $_SESSION['words'] in PHP.
// PHP print new words as links
echo '<ul id="wordlist">';
foreach($_SESSION['words'] as $word => $description) {
echo '<li id="wordlist">' . $word . '</li>';
}
The array is simple - words are stored as keys and the descriptions for words will be values, e.g.
array(5) { ["word1"]=> int(1) ["word2"]=> int(2) ["word3"]=> int(3) ["word4"]=> int(4) ["word5"]=> int(5) }
I plan to manipulate items in the array by selecting a $word and adding a $description and adding it to the array, so I'm thinking I'll use jQuery to do it.
My question is: if I create a JSON array from this PHP array, can I print it out in the same way and manipulate it? I encoded it with $myJSON = json_encode($_SESSION['words']); but I'm already stuck attempting to print out the keys/values from the JSON! Thanks...
You can use $.parseJSON:
var json = $.parseJSON('your json');
alert(json.word1);
alert(json.word2);
If your JSON data is available via a URL, you can use $.getJSON
You description indicates to me that you are not using JSON in any way, other than to use PHP's JSON encoding function. It sounds like you are encoding your PHP associative array into a JSON string and then writing that string into your HTML output. If this is the case, then your JSON is really a JavaScript object.
So let's assume your resulting markup is this:
<script>
// Using a global here, which is not good,
// but this is an example.
var myWordList = {"word1":1,"word2":2,"word3":3};
</script>
<ul id="wordlist">
<li id="word1">1</li>
<li id="word2">2</li>
<li id="word3">3</li>
</ul>
Notice that my id attribute values are unique. You used the same id attribute value multiple times; that is invalid markup. Also, I kept the markup in each list element simple for this example (just text).
So, given this markup, we could write the following JavaScript:
<script>
// Update our wordlist object with some descriptions
myWordList.word1 = {
"value": myWordList.word1,
"description": "This is word 1."
};
myWordList.word2 = {
"value": myWordList.word2,
"description": "This is word 2."
};
myWordList.word3 = {
"value": myWordList.word3,
"description": "This is word 3."
};
// Now lets update the unordered list with jQuery
for (var i = 1; i < 4; i += 1) {
$('#word' + i).html(myWordList['word' + i].description);
}
</script>
In this JavaScript, I first update the myWordList values by assigning a new object to each value. These new objects have two properties: a value property that is assigned the old myWordList.word# value, and a new description property that describes the word. Next, I update the unordered list by replacing the word values with the word descriptions.
Edit:
If you want to loop over the properties in the object, you can do this:
for (var key in myWordList) {
if (myWordList.hasOwnProperty(key)) {
console.dir(myWordList[key]);
}
}
if not used to $.each method, may also try old array loop:
$.ajax({
url: '',
dataType: 'json',
success: function(arrayData) {
var i,max=arrayData.length;
for(i=0;i<max;i++){
var rowItem = arrayData[i];
try{
console.log(rowItem.attr1);
}catch(ex){
alert(ex);///in case data is not complete
}
});
}
});
if you already have the JSON string , say strJson = '[{attr1:"hello"},{attr1:"world"}]';
var tmp = 'var data = '+strJson;
///so you got : var data = [{attr1:"hello"},{attr1:"world"}]
eval(tmp);/// execute the above line
alert(data.length + "first item:"+data[0].attr1);
You need to get that JSON via AJAX and the
$.ajax({
url: '',
dataType: 'json',
success: function(response) {
$.each(response, function(key, val) {
console.log(key); // word1, word2, word3...
console.log(val); // 1, 2, 3...
....
});
}
});
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);
})
}
i m grabbing image paths from MySQL via php and then json_encode and with response data i m using below code to display image but not working
My PHP Code
$imgurl=array();
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl = $row['imgurl'];
}
}
echo json_encode($imgurl);
else
{
echo "No results matching family \"$family\"";
}
The Code at my Jquery side
success: function( data ){
$('#pgwrapid').html(data);
}
the data is giving below output which are actually image paths
["images\/zara\/shoes\/thumbnail","images\/hermes\/shoes\/thumbnail","images\/hermes\/shoes\/thumbnail"]
now how to remove the backslashes and insert it in img src=""
Try Below :
success: function( data ){
$.each(data,function(index,val){
$('#pgwrapid').append("<img src='"+val+"' alt='Thumbnail'/>");
});
}
But please check first if you are getting value in val or not.
You have wrong quotes there. You need to use single quotes for alt='Thumbnail' or escape the double quotes you are already using alt=\"Thumbnail\"
try this code:
success: function( data ){
var evaluateddata = eval('('+data+')');
$.each(evaluateddata,function(index,val){
$('#pgwrapid').append("<img src="+val+" alt="Thumbnail"/>");
});
}
the data is treated as a string after the request, but when it comes json I love to use the hard coded iterative way in javascript (not really fund of using .each() api of jquery so I have a doubt on the above code though not sure if it should be val or should I still identify the variable to access such as val.<variablename>) like this:
success: function( data ){
var evaluateddata = eval('('+data+')');
for(val in evaluateddata)
{
$('#pgwrapid').append("<img src="+evaluateddata[val]+" alt="Thumbnail"/>");
}
}
this is the direct javascript approach to iterate on the json object but it depends on you which one is ideal for you (somehow it would be better if you post the original json string response from your application).
I see the code. how about if you try this code:
if(mysql_num_rows($result) > 0){
//Fetch rows
$output = array();
while($row = mysql_fetch_array($result)){
$output[] = $row['imgurl'];
}
echo json_encode($output);
}else{
echo "No results matching family \"$family\"";
}
your code is actually trying to output a separate json value for each imgurl definitely it won't work because the json value that your application will be returning would be evaluated as one and your code is printing several json values which may cause errors when your javascript code receives it.
I'm trying to use jQuery.post() function to retrieve some data. But
i get no output.
I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.
My scriptfile looks like this:
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.
jQuery.post("../functions.php", { storeID: "storeID" },
function(data){
alert(data.name); // To test if I get any output
}, "json");
});
});
My PHP file looks like this:
<?php
inlcude_once('dal.php');
//Get store data, and ouput it as JSON.
function getStoreInformation($storeID)
{
$storeID = "9";//$_GET["storeID"];
$sl = new storeLocator();
$result = $sl->getStoreData($storeID);
while ($row = mysql_fetch_assoc($result)) {
{
$arr[] = $row;
}
$storeData = json_encode($arr);
echo $storeData; //Output JSON data
}
?>
I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.
since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
I don't think I'm passing the storeID parameter correctly. What is the right way?
How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" }
Is the getNameAndTime the name of the function in test.php ?
I have gotten one step further.
I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.
My js script now looks like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data);
}, "text");
});
This results in an alert window which ouputs the store data as string in JSON format.
(because I have changed "json" to "text").
The JSON string looks like this:
[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten#brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]
Now, what I really want, is to ouput the data from JSON.
So I would change "text" to "json" and "alert(data)" to "alert(data.name)".
So now my js script will look like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data.name);
}, "json");
});
Unfortunately, the only output I get, is "Undefined".
And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".
So how do I output the name of teh store?
In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ?
(currently I have hardcoded the storeID, for testing)
Lose the quotes around "storeID":
Wrong:
jQuery.post("../functions.php", { storeID: "storeID" }
Right:
jQuery.post("../functions.php", { storeID: storeID }
bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.
However, a couple more notes:
It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
EDIT As far as your reply, if you break down what you are returning:
[
{
"id":"9",
"name":"Brandstad Byporten",
"street1":"Jernbanetorget",
"street2":null,
"zipcode":"0154",
"city":"Oslo",
"phone":"23362011",
"fax":"22178889",
"www":"http:\\/www.brandstad.no",
"email":"bs.byporten#brandstad.no",
"opening_hours":"Man-Fre 10-21, L",
"active":"pending"
}
]
This is actually an array (the square brackets) containing a single object (the curly braces).
So when you try doing:
alert(data.name);
This is not correct because the object resides as the first element of the array.
alert(data[0].name);
Should work as you expect.
Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]
so this would work.
wrong: alert(data.name);
right: alert(data[0].name);
Hope that helps.
D
Ok, thanks to Darryl, I found the answer.
So here is the functional code for anyone who is wondering about this:
javascript file
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML }, // this.cells[0].innerHTML is the content ofthe first cell in selected table row
function(data){
alert(data[0].name);
}, "json");
});
});
get_storeData.php
<?php
include_once('dal.php');
$storeID = $_POST['storeID']; //Get storeID from jQuery.post parameter
$sl = new storeLocator();
$result = $sl->getStoreData($storeID); //returns dataset from MySQL (SELECT * from MyTale)
while ($row = mysql_fetch_array($result))
{
$data[] = array(
"id"=>($row['id']) ,
"name"=>($row['name']));
}
$storeData = json_encode($data);
echo $storeData;
?>
Thanks for all your help guys!