Does $.getJSON reorder data? - javascript

JS:
$.getJSON('services/get_locations.php', {region: $("#oblast").val()}, function(data) {
console.log(data);
});
PHP:
$result = json_encode($raw['data']);
echo $result;
exit;
Result from var_dump($result) is:
{
"10971":"\u0433\u0440. \u0412\u0418\u0414\u0418\u041d",
"179":"\u0441. \u0410\u041a\u0410\u0426\u0418\u0415\u0412\u041e",
"919":"\u0441. \u0410\u041d\u0422\u0418\u041c\u041e\u0412\u041e"
}
As you can see, first ID is 10971.
However, the result of console.log(data) is:
{179: "с. АКАЦИЕВО", 919: "с. АНТИМОВО", 10971: "гр. ВИДИН"}
Why is data being reordered?

Javascript objects with numeric keys will always get ordered in ascending order of the numeric key values
If order is important change structure to an array something like [{id:179, value: "...."}] or [[10971,"wrd"],[179,"xyz"]]
Example with no ajax. Note the log order is different than the constructed order (ascending key values)
const data = {
"10971":"\u0433\u0440. \u0412\u0418\u0414\u0418\u041d",
"179":"\u0441. \u0410\u041a\u0410\u0426\u0418\u0415\u0412\u041e",
"919":"\u0441. \u0410\u041d\u0422\u0418\u041c\u041e\u0412\u041e"
}
console.log(data);
console.log('Keys:', Object.keys(data))

Related

Why my script ignoring empty array result?

I have a script that basically check if there is a result from a query:
$.post('<?php echo site_url('xxx/yyy'); ?>',{data:no},function(result){
if(!result){
alert("No Data");
}
else{
alert("Data retrieved");
}
});
Why my IF alert Data retrieved when I get empty JSON array. I tried to do alert(result) with different data (the data which result is empty and result is true), but both data is alerting Data retrieved.
This is my model:
$this->db->select('*',FALSE);
$this->db->from('t_penomoran tp');
$this->db->join('t_penomoran_detail t_pd', 'tp.nomor = t_pd.nomor');
$this->db->where('tp.nomor',$nomor);
$query = $this->db->get();
return $query->result_array();
note:
For some reason when I do alert(result.length) with data that has no value, the result is 2. But when I do alert(result) with data that has no value the result is []
Empty array is a truthy value, meaning in your if statement, it will evaluate to true and that is why you see the alert(). To fix it, use the length property:
if(!result.length) alert('no data')
You can check like this
if(jQuery.isEmptyObject(result))
{
alert('no data')
}
First of all parse your result like this
var res = result.responseJSON;
Then alert what you get if empty then it will be null. so you can filter that out

JQuery unable to parse JSON string created by json_encode

I am currently in a bind, JQuery is unable to parse the following json strings
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
The above strings when parse through JSON.parse create the following arror:
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 112 of the JSON data
The PHP code which creates the string above is this:
public function getCustomerSuggestions($name){
$customers = $this->model->where('name','LIKE','%'.$name.'%')->show();
if(count($customers)>=1){
foreach($customers as $customer){
$list[] = ['value' => ucfirst($customer->name),'data' => $customer->id];
}
}
else{
$list[] = ['value' => 'No Customers Found', 'data'=> NULL];
}
$full_list['query'] = 'Unit';
$full_list['suggestions'] = $list;
return json_encode($full_list);
}
As you can see I am using the function json_encode to create the JSOn string so there should be no issue but it still doesnt work.
Edit
The json is sent using an autocomplete tool called DevBridge Autocomplete which takes the JSON strings and creates a suggestion list. The code I am using is
$('input[name=\"customer\"]').devbridgeAutocomplete({
serviceUrl: '".SITE_PATH."/ajax/admin/quotes/getcustomer',
minChars: 1,
onSearchStart: function (query){
var searchinput = $(this).val();
$('.autocomplete-suggestions').html('Searching: '+searchinput);
},
onSelect: function(suggestion){
var selection = $(this).val(suggestion.value);
$('input[name=\"customerid\"]').val(suggestion.data);
$.get('".SITE_PATH."/ajax/admin/quotes/getcustomerdetails',{id: suggestion.data},
function(response){
var obj = $.parseJSON(response);
$.each(obj, function(key, value){
$('#'+key).val(value);
});
});
}
});
It seems you have two JSON objects after each other. That's simply invalid. There can only be a single value at the root of a JSON "document". If you want to send down multiple objects, you need to put them in an array.
It seems getCustomerSuggestions is called multiple times and the return value of each call is returned to the client. Instead, the method should return an array, the caller should collect the return values in an array and JSON encode that array.
Well, your JSON string is NOT valid.
It should be,
[
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
,
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
]
But as Felix Kling said, check your PHP code.

How to Build a jQuery array and move to the php, then use it on a PHP Function?

$(".divclass").each(function() {
Build An Array with all .divclass ID (
});
~~~~> POST with AJAX for page.php
PHP gets the array and then use the function with each result of #divclassID
require "phpfunction.php";
$array = array received from AJAX;
for each #divclassID => $key {
getFunction($key)
}
After, rebuild a json array and print this;
Text explication:
1º) For each .divclass, Build an array with all $(this).attr("ID"); (with ID of each .divclass)
2º) Send the array to page.php;
3º) page.php receives the array and use the phpfunction with each element ID Listed in array;
Please, It's possible?
Create one page for client-side and write some jQ Code in your page:
$(function(){
var ids = [];
$(".divclass").each(function() {
ids.push($(this).attr('id')); // Push into JS array
});
$.post('page.php',{ids:ids},function(){
alert('Horay, the data sent');
});
});
page.php:
<?php
require "phpfunction.php";
$ids = $_POST['ids']; // The $ids contains array of ID as you expected
?>
is simple alright ? Do you ?

How to properly loop through JSON response

Im trying to populate a combobox with data from database.
When I access mystream.php?theLocation=NewYork
I get this JSON response
RESULT
{"result":
[{"theID":"36"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork"},
{"theID":"37"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork"},
{"theID":"40"},{"theStream":"0817-31334"},{"theLabel":"dsfg ghjg"},{"theLocation":"NewYork"}]}
Applying the answer from this post
loop through JSON result with jQuery
I came up with this JSON
$.getJSON(
'mystream.php',
'theLocation=NewYork',
function(result){
$('#cmbNewYork').empty();
$.each(result, function(i, item){
$('#cmbNewYork').append('<option value=' +item.theStream+ '>'+item.theLabel+'</option>');
alert(item.theStream);
});
}
);
My resulting combo box only contains undefined.
How to properly loop thru JSON response?
Thanks
EDIT (ADDED)
mystream.php
$sql = "SELECT * FROM Streams WHERE theLocation='$loc'";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('theID'=>$row['theID']),
array('theStream'=>$row['theStream']),
array('theLabel'=>$row['theLabel']),
array('theLocation'=>$row['theLocation'])
);
}
echo json_encode(array('result'=>$result));
Two issues:
The primary issue that your JSON format is very strange: It's an array of objects each of which has one name/value pair:
{"result": [
{"theID":"36"},
{"theStream":"0817-05131"},
{"theLabel":"hgjbn"},
{"theLocation":"NewYork"},
{"theID":"37"},
{"theStream":"0817-05131"},
{"theLabel":"hgjbn"},
{"theLocation":"NewYork"},
{"theID":"40"},
{"theStream":"0817-31334"},
{"theLabel":"dsfg ghjg"},
{"theLocation":"NewYork"}
]}
That's 12 separate objects.
You should have objects with all of those properties together:
{
"result": [
{
"theID": "36",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
{
"theID": "37",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
{
"theID": "40",
"theStream": "0817-31334",
"theLabel": "dsfg ghjg",
"theLocation": "NewYork"
}
]
}
That's three objects, each with four properties.
Re your edit to the question, you can do that like this:
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'theID'=>$row['theID'],
'theStream'=>$row['theStream'],
'theLabel'=>$row['theLabel'],
'theLocation'=>$row['theLocation']
)
);
}
Note how that's creating one array per loop, rather than four.
The second issue is that you probably need result.result, rather than just result, on this line:
$.each(result.result, function(i, item){
// ----------^^^^^^^
...since result is your overall anonymous result, which has a single property, result, which has your array.
If you fix those, your loop should start working.
You don't have to do the result.result thing if you don't want to. Instead, you could have your JSON define an array instead of an object with a single property referring to the array:
[
{
"theID": "36",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
(and so on)
]
You haven't shown the PHP code creating $result, so I can't show you how to do that, but A) You don't need to, the result.result thing is fine, and B) If you want to, I'm sure you can figure it out.

How to Access Array response of AJAX

This is my AJAX call response which is in array format
[1,2,3,4,5,6]
success: function(outputfromserver) {
$.each(outputfromserver, function(index, el)
{
});
How can we access outputfromserver all values ??
Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on
It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().
Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.
$.ajax({
url: 'test.json', // returns "[1,2,3,4,5,6]"
dataType: 'json', // jQuery will parse the response as JSON
success: function (outputfromserver) {
// outputfromserver is an array in this case
// just access it like one
alert(outputfromserver[0]); // alert the 0th value
// let's iterate through the returned values
// for loops are good for that, $.each() is fine too
// but unnecessary here
for (var i = 0; i < outputfromserver.length; i++) {
// outputfromserver[i] can be used to get each value
}
}
});
Now, if you insist on using $.each, the following will work for the success option.
success: function (outputfromserver) {
$.each(outputfromserver, function(index, el) {
// index is your 0-based array index
// el is your value
// for example
alert("element at " + index + ": " + el); // will alert each value
});
}
Feel free to ask any questions!
The array is a valid JSON string, you need to parse it using JSON parser.
success: function(outputfromserver) {
var data = JSON.parse(outputfromserver);
$.each(data, function(index, el) {
// Do your stuff
});
},
...
You can use JS objects like arrays
For example this way:
// Loop through all values in outputfromserver
for (var index in outputfromserver) {
// Show value in alert dialog:
alert( outputfromserver[index] );
}
This way you can get values at first dimension of array,
above for..loop will get values like this:
// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index:
// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.
If you are using multidimensional stuff
then you can add nested for (...) loops or make recursive function to loop through all and every value.
Multidimensional will be something like this:
// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];
Update, JSON object:
If you server returns JSON encoded string you can convert it to javascript object this way:
try {
// Try to convert JSON string with jQuery:
serveroutputobject = $.parseJSON(outputfromserver);
} catch (e) {
// Conversion failed, result is not JSON encoded string
serveroutputobject = null;
}
// Check if object converted successfully:
if ( serveroutputobject !== null ) {
// Loop through all values in outputfromserver
for (var index in serveroutputobject) {
// Append value inside <div id="results">:
$('#results').append( serveroutputobject[index] + "<br/>" );
}
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it.
else {
$('#results').html( outputfromserver );
}
More information here
$.ajax({
type : "POST",
dataType: "json",
url : url,
data:dataString,
success: function(return_data,textStatus) {
temperature.innerText=return_data.temp;
// OR
**temperature.innerText=return_data['temp'];**
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;
}
});

Categories

Resources