I'm trying to get my data into an array of strings so that I can use it as a dataset for jquery autocomplete. What I'm getting now is an array of objects, which I don't think will work.
Jquery on my main page:
$.get("get_schools.php", function(data) {
var results = jQuery.parseJSON(data);
alert(results);
});
This results in data in the format of:
[object Object],[object Object],[object Object]
On get_schools.php:
I query a database and the return the results to an array called $displaynames. Then:
echo json_encode($displaynames);
Which looks like:
[{"DisplayName":"XXXX Street Middle School"},{"DisplayName":"XXXXX Schools"},{"DisplayName":"XXXX Elementary School"}
UPDATE:
this question has been flagged as a possible duplicate, but the other question pertains to getting a property of an object. i wasn't attempting to get a property of an object. i was attempting to convert an object array to an array of strings. i needed the property names as well as the values in the result. the other question only returns the values.
$.get("get_schools.php", function(data) {
var results = jQuery.parseJSON(data).map(function (item) {
return item.DisplayName;
});
alert(results);
});
results will be an array of strings
["XXXX Street Middle School", "XXXXX Schools", "XXXX Elementary School"]
It will depend on what your putting the objects into. The objects you've been given are just fine, but in order to access the values inside them you will need to access them via the DisplayName property.
$.each(results, function(i,e) {
console.log(e.DisplayName);
})
This would log XXX Street Middle School, XXXX Schools, etc.
To circumvent this behavior, do not shove the values into a named part of the array.
I assume you want the result to look similar to:
["XXX Street", "xxxxx school", "xxxx", ... ]
So in your php code, you want to do something like this:
$json = array();
foreach($school in $schools) {
array_push($json, $school->displayName); //obviously this is unique to your application and not this verbatim
}
echo json_encode($json);
Basically, you want a list, not an associative array. Now, if you had more information you needed to display about a single school you would want an associative array. But given your usage desires, I believe this is closer to what you need.
As an aside, if you use the $.getJSON() function in jQuery (as opposed to $.get), you can avoid using the call to jQuery.parseJSON() and will just get a json object in your success function.
Related
I am receiving some JSON from PHP like this (previewed in Firefox tools):
1:Object
0:Object
1:Object
2:Object
3:Object
Name: "SomeName"
I now want to iterate through the objects, but not the Name key. It seems if I do an $.each it includes the key/value pair. How can I avoid it? Also why can I choose a numerical value for the first Object (I have it "1") but not assign a value to it? I wish it could look like this for example
1:SomeNameIGaveIt
0:Object
1:Object
2:Object
3:Object
That would make my Name k/v pair obsolete.
JSON
{"1": {"Name":"SomeName", "0":{"data":"data"}. "1":{"data":"data"}}}
In JavaScript, a String is a "subclass" of Object. Lucky for you, there's the typeof operator;
in the Chrome console
var a = "foo" //makes a String
var b = {} //makes an empty Object
typeof a
"string"
typeof b
"object"
Using this, you can check to ensure something is not a string before doing an operation on it.
Other option: instead of iterating using the json $.each call, you could just iterate over it via a JavaScript for-loop. If you know the number of elements inside your SomeNameIGaveIt object is fixed, you could use a fixed number of iterations and then use the array indexing operator (SomeNameIGaveIt[index]), or use a for-in loop (for (var i in array){...})
If you use a for-in loop, you can check if the index is a number using typeof as mentioned above. Any of these approaches is going to yield pretty similar results, so pick whatever suits you best.
I have a database with 5 columns and multiple rows. I'm using PHP to fetch the data and echo it as JSON as an array. The way it echoes it is the data in each row is an array and the rows themselves are an array (array within an array).
Now I bring the data in using Ajax and want to split the array within an array. I can only split down the rows so far. How would I split further?
Here's the PHP:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
//==== PUT DATA INTO ARRAY
$array = array();
while ($row = mysql_fetch_row($result)) {
$array[] = $row;
}
//==== ECHO AS JSON
echo json_encode($array);
Here's the Ajax:
$.ajax({
url: 'assets/php/results.php',
data: "",
dataType: 'json',
success: function(data){
//==== FETCH DATA FIELDS
var row1 = data[0];
var row2 = data[1];
//==== UPDATE HTML WITH DATA
$('#r-col span.row1').html(row1);
$('#r-col span.row2').html(row2);
}
});
To answer your question, let me give you a few tips on how you can achieve this in shorter steps.
First off, try using msqli_ functions instead of msql_ (in php) it has a better handling of security among other improvements, and are also the functions w3schools recommend using.
There is a function called mysqli_fetch_array() that will do exactly what you are doing with your for loop in a single command.
And to answer your question on the json, you should take a look at what a json really looks like:
var data = {"menu": {
"id": "file",
"value": "File123",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Json objects are not arrays, they are objects. That means I can access the information like this:
data.menu.id //Which is equal to "file"<br>
or
data[0][0] //which is also equal to "file"<br>
or a combination
data[0].value //is equal to "File123"
A great way to understand the way this objects work is by using the interactive console in Chrome. It has a pretty easy to understand printing of objects. I would also advice you to read some about object oriented programming on javascript.
In a nutshell: Json objects are not arrays, but you can sort through them easily by appending . or []
A small note: Try to avoid using Select * in your statements, they take a lot of resources, just call the fields you need by name.
Also, msql_ functions are a bit deprecated right now, try using msqli_ functions instead, they have several upgrades in the security side, you can check w3schools.com for examples.
Finally, there is a function in php called msqli_fetch_array that does exactly what you're trying to do with your for loop, it will convert your query output to an array.
Happy Coding.
I have a <select> element that I need to populate with values I get from an Ajax call. I am debating whether to have the Ajax return a proper JSON object of keys/values or just have it echo out a bunch of <option> elements. The options need to be displayed in an alphabetical order in the select.
I feel like using a JSON object is the proper way of doing it. But when that object is returned, I have to go through the process of sorting the JSON object by name instead of value. For example:
My PHP returns the following JSON Object response:
{"21":"Bandana","18":"Baseball","19":"Cowboy","20":"Trucker"}
That is the proper order that I want the items to be displayed in the <select> element. But when the Ajax callback gets the JSON Object, it's sorted by key instead of value:
{"18":"Baseball","19":"Cowboy","20":"Trucker","21":"Bandana"}
So iterating through this JSON object and appending <option>'s to the <select> will result in the values not being alphabetical. So now, I have to go through the process of sorting this before using it.
Alternatively, if I just throw out the JSON object altogether and just had my PHP do this:
foreach ( $array as $key => $value )
echo "<option value='$key'>$value</option>";
Now, back in my Ajax callback all I have to do is append the output to my <select> and I'm good to go. Everything is sorted and it works perfectly.
So in the end, I feel like JSON is the proper way to do it, but you have to jump through several more hoops to get to the goal. Are there easy JSON Object tricks I'm unaware of? Why would I ever use a JSON Object in this situation if I have to reformat the data in the callback?
Use a JSON array instead of an object.
[{"key": "21", "value":"Bandana"},{"key":"18", "value":"Baseball"},{"key": "19", "value":"Cowboy"},{"key":"20","value":"Trucker"}]
Property names of an object aren't maintained in any particular order. That is, when you iterate through the property names of an object with a JavaScript for ... in loop, the order is not defined. The runtime system can give you the names in any order; I don't think it's necessarily even repeatable.
I would prefer json with array of arrays. First element as key and second as value.
[[21,"Bandana"],[18,"Baseball],[19,"Cowboy"],[20,"Trucker"]]
I am implementing Backbone.js, and I am just trying to understand how the sync function works.
To keep it very simple, here is the model.
var Item = Backbone.Model.extend({
defaults: {
name: "Goo"
},
url: "commlink.php"
});
and then
Backbone.sync("create", item);
This is my commlink.php
$item=json_decode($_POST);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");
I see a new row show up in my DB, however, the field "name" is blank.
I tried both item.save() and the above method...both ended up with the same blank cell but a new entry.
This is the error in chrome in network/content:
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in ...XXX...
This is in the request payload:
{"name":"Goo"}
$rawJSONString = file_get_contents('php://input');
$item = json_decode($wrapperString);
//$item->name is the data you want
$item = json_decode(file_get_contents('php://input'), true);
print_R($item);
Found this is more helpful
https://coderwall.com/p/vwvy_a
SECURITY NOTE: as pointed out in the comment this is not the way you should ACTUALLY insert the user provided content into your database, this is simply to show you how to get access to the array information as JSON, you should use prepared statements, a framework database adapter, or some other appropriate solution for escaping the user provided content before sticking it into the database.
You're trying to run an array ($_POST) through a function (json_decode) that only accepts a string. The solution in this specific example would be to do this:
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '{$_POST['name']}')");
This would work because you're accessing $_POST as the associative array that it is.
However what I think you actually want to do is first convert the $_POST array to json, then decode it so you can use it the way you wanted to (accessing it as an object, which the json_decode returns):
$item=json_encode($_POST);
$item=json_decode($item);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");
For reference:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
I am trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array. I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:
The PHP code:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
The jQuery code:
$.post("dbFile.php", str, function(theResponse){
alert('the response: ' + theResponse);
var obj = $.parseJSON(theResponse);
alert(obj.a);
I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:
$arr[$i] = mysqlresults ... $i++;
So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?
Use the array access syntax:
alert(obj[42]);
You can use:
alert(obj['a']);
See this question for more info.