Split an array within an array (Mysql, PHP and Ajax) - php

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.

Related

Getting JSON data with AJAX and converting to array of strings

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.

JSON Stringify - PHP json_decode

I am new to JSON,ofr a project of my own I need to send array of objects to the server. Basically, I have a Question object, which has a couple of properties, like question, optionA, optionB etc. I have an array of Question objects.
example:
qArray = new Array();
qArray.push(new Question("where do you live?", "England", "ıtaly", "Usa");
I am adding a lot of questions objects to this array and in the end, I need to send this array to the server, like this:
$.post("backend-stuff/aj-save-test.php", { testName : $("#testName").val().toString(), 'questions' : JSON.stringify(qArray)}, function(result){
alert(result);
});
}
In PHP, I use this,
$questions = json_decode($_POST["questions"]);
$testName = $_POST["testName"];
Problem is that I cant read data, either I am sending it in the wrong way or whats wrong is on the php side.
Thank you for answers, I checked Google before sending the question, so please forgive me if this is so easy but for me its not so.
To convert stdClassObject to an array, check out get_object_vars().

Json_encode for .post?

can anyone explain the purpose of json_encode when doing a .post query.
This is what i often see in other's coding.
.post php script
...
...
echo json_encode($a);
I mean if i want to do a return from a .post script and returning an array via .post. Wouldn't i just need to do the following?
.post php script
...
...
$a = array("foo", "bar", "hallo", "world");
$string=implode(',',$a) in my php script
return $string;
javascript
$.post('$url',function(data){
data_arr=data.split(',');
//After which just get the values in the array
alert(data_arr[0]); //ALERTS 'foo'
alert(data_arr[1]); //ALERTS 'bar'
});
If anyone can just help by clearing this up for me and let me see the light for using json in this purpose, that would be great.
Perhaps its also due to my inept knowledge of JSON as well.
Would greatly appreciate it if anyone can advise me on why is it better to use JSON encode in this case and how am i suppose to use it via a .post request instead of just echoing out the string and split it later.
Thanks.
Using json_encode ensures that your data is always valid.
It doesn't really matter for simple data that you have control over, though imagine if someday you have a comma inside one of the values. With JSON encoded strings, you don't have to worry about an arbitrary separator token.
Also, with JSON you can easily encode Objects/Arrays without needing to reinvent the wheel.
First of all, in my opinion and practise, JSON syntax is fairly similar to Javascript objects and it's great when dealing with more complex data types that have to be sent/requested and parsed later on.
For example:
If you're doing a post request and you're serializing all the form fields which you validate server side (using PHP) you're most likely going to need to use key => value pairs like textbox_name => value. It's more logical to do it that way, than to select values by numeric indexes (what if the form layout changes?)
Example code using commas:
<?php
$array = array('Tom', 'Hanks', 'Football');
$string = join(',',$array);
echo $string; //it's obvious - the output is Tom,Hanks,Football
?>
The javascript that receives the string
$.post(url,{},function(data){
var values = data.split(',')
$("#name").text(values[0]);
$("#surname").text(values[1]);
$("#interests").text(values[2]);
});
So it makes sense right? But wouldn't it more sense to do this instead:
<?php
header('Content-type: application/json');
$array = array('name' => 'Tom', 'surname' => 'Hanks', 'interests' => 'Football');
echo json_encode($array);
?>
And the javascript:
$.post(url,{},function(data){
for(index in data) {
$("#"+index).text(data[index]);
}
//or
$("#name").text(data.name);
$("#surname").text(data.surname);
$("#interests").text(data.interests);
});
The same goes with parsing response data with Javascript. Having an object is more logical than having a CSV string.
Obviously it depends on the use case, but in general JSON gives you a logical structure of stringified Objects/Arrays which can be translated back into objects and arrays and looped through or manipulated in any way.
Also JSON is now a standard. Everyone uses it which means that it's not for no reason.
In other words - JSON data makes more sense.

Pass PHP Array to Javascript

Am trying to pass an array of values from PHP function to Javascript. Not sure if I am doing it correctly.
PHP:
function toggleLayers(){
for($i=0;$i<$group_layer_row;$i++){
$toggleArray=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray;
}
}
JS:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
for(var i=0;i < myArray.length; i++){
if($myArray.getVisibility()==true){
$myArray.getVisibility(false);
}
else{
$myArray.getVisibility(true);
}
}
SQL (for reference):
$con = mssql_connect("myServer", "myUsername", myPassword");
$sql = "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$rs_group_layer = mssql_query ($sql, $con);
$group_layer_row = mssql_num_rows($rs_group_layer);
I have been looking at some other similar questions, and the answers are either vague and/or there are a few thousand of them.
Would appreciate any help, also please try to explain as if you were writing a book called "Idiot's Guide to Passing PHP Arrays to JS"
Thanks for your help.
Edit:
Sorry, my question was very vague. Here's what I'm trying to do:
1.PHP Function gets all records from table into array(in this case they are map layers)
2.Javascript receives PHP array and loops through adding if clause to toggle layers.
Hope this makes it clearer.
It's simpler than you think.
Change this line:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
To just:
var myArray = <?php echo htmlspecialchars(json_encode($toggleArray), ENT_NOQUOTES); ?>;
json_encode produces a json string. Echoing the string into a javascript context is the equivalent of a javascript literal. The htmlspecialchars is just for the necessary html escaping and is not unique to echoing json.
NOTE however that you can only json_encode a php object or array, not any scalar types like ints or strings. This is a limitation of JSON itself. In your toggleLayers() function, you are returning a string, not an array.
A thing that would be very useful to understand:
You sumply can't "pass an array of values from PHP function to Javascript".
But rather you have to create the javascript code using PHP just like you are creating HTML.
Thus, 3 simple step to solve any problem with PHP -> client transfers:
Create a pure client-side code you wish. Make it work. Save it somewhere.
Create a PHP code to produce that client-side code.
Compare the codes. If doesn't match - correct the PHP code. Repeat until done.

json multidimensional array and jquery?

I create this output with PHP:
foreach ($bk as $blink) {
$out["url"][] = $blink->url;
$out["anchor"][] = $blink->anchor;
}
$json = Zend_Json::encode($out);
echo ($json);
I want to receive and process the output with a $.ajax call.
Could you point me to a nice tutorial about multidimensional arrays with javascript/jquery or help me loop* through the json results? I got a bit confused with it.
I am trying to put those on a table, so I will be using <td>url-i</td><td>anchor-i</td> . This part, I figured out how. To put the correct values on url-i and anchor-i is the problem.
I would imagine the JSON output for that will be something like:
{'url': ['url1', 'url2', ... ],
'anchor': ['anchor1', 'anchor2', ... ]}
If that is the case, then they will be of equal length (and importantly equal indexes) and you can loop through one of the two using jQuery.each().
$.getJSON('jsonapp.php', function(data) {
$.each(data.url, function(index, url) {
var anchor = data.anchor[index];
$('#mytable').append('<tr><td>' + url + '</td><td>' + anchor +'</td></tr>');
});
});
I've not run that code, so it might have a few flaws, but that's the gist of it.
PHP can try to cast objects into arrays by itself, and for simple stuff, it usually works fine.
As for multidimensional arrays, Javascript isn't too different from most other higher-level programming/scripting languages when it comes to arrays. Really, any tutorial online on multidimensional arrays will do just fine. A multidimensional array is simply an array of arrays.
When you receive the string client-side, you just want to parse it. jQuery has its own method, but you can use JSON.parse. Afterwards, based on how you've set up your arrays, you'd want to do something like this.
<? $count = count($json_parsed['url']); for($i = 1; $i < $count; $i++) : ?>
<td><?=$json_parsed['url'][$i];?></td>
<td><?=$json_parsed['anchor'][$i];?></td>
<? endfor; ?>
This may be philosophically not the best way to do it though. If you have a whole bunch of objects and you want to make a table out of them, the best way would be to create an array of those objects as represented by associative arrays (sort of like hash tables in other programming languages). PHP natively tries to convert objects into associative arrays. I wouldn't be surprised if Zend_Json::encode does it automatically. If it does, you might want to pull simply:
echo Zend_Json::encode($bk);
If not, let me know, and we'll talk about how to do that.
You could have a look on any template frameworks, but for this exact case it seams useful to check one of those two: pure by beebole or jquery pure html templates.
Doing it by yourself might be tempting but why to reinvent the well - I know from my experience, that frameworks are about 2 times faster, then self made code.

Categories