I am pulling in some JSON data that will vary... for instance:
Data returned could be:
[{"userID":"2779","UserFullName":" Absolute Pro-Formance"},{"userID":"2780","UserFullName":" AR Fabrication"},{"userID":"2781","UserFullName":" Banda Lucas Design Group"}]
or:
[{"orderID":"112958","OrderName":"Order ID: 112958"},{"orderID":"112957","OrderName":"Order ID: 112957"},{"orderID":"112956","OrderName":"Order ID: 112956"}]
What I am attempting to do is process this JSON to build a <select> list.
// Load in a drop-down as JSON
function LoadDropDown($url, $where, $id, $selectName){
var $loading = '<div class="pageLoader" style="margin:0 auto !important;padding:0 !important;"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>';
var $t = Math.round(new Date().getTime() / 1000);
var $container = jQuery($where);
var options = {
url: $url + '?_=' + $t,
cache: false,
type: 'POST',
beforeSend: function(){
$container.html($loading);
},
success: function(data, status, jqXhr){
$html = '<select class="form-control" id="'+$selectName+'" name="'+$selectName+'">';
$html += '<option value="0">- Select an Option -</option>';
for(var i = 0; i < data.length-1; ++i) {
var item = data[i];
console.log(item.userID);
}
$html += '</select>';
$container.html('<pre>' + data + '</pre>');
},
complete: function(jqXhr, status){},
error: function(jqXhr, status, error){
$container.slideDown('fast').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><i class="fa fa-exclamation-triangle fa-4x pull-left"></i><p><strong>Danger Will Robinson!</strong><br />There was an issue pulling in this page. Our support team has been notified, please check back later.</p></div>');
}
};
jQuery.ajax(options);
}
The issue I am having is... #1 console.log(item.userID); always shows undefined, and #2 how can I effecitvely dynamically build the options? The returned JSON will ALWAYS contain 2 items per row and id, and a name
UPDATE
for(var $key in data){
var $val = data[$key];
for($j in $val){
console.log('name:' + $j + ' = ' + $val[$j]);
}
}
Is showing me what I need in Firefox Console... But 1 item per line, for each (for example the 1st JSON) name:userID = 1234 next line name:UserFullName = TheName
How can I get them so I can build my <options>?
With:
for(var k in data) {
console.log(k, data[k]);
}
I am returned:
2955 Object { orderID="8508", OrderName="Order ID: 8508"}
and
2955 Object { userID="1355", UserFulleName="Me Myself And I"}
You don't need to use such messy code. Also in your Ajax setup dataType:"json"
success:function() {
var listB=$('#yourdropdownId');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option>', {
value: item.userID,
text: item.UserFullName
}, '<option/>'))
});
}
Also the $.getJson instead of ajax if you only want retrieve json from server
$.getJSON('#Url.Action(" "," ")',
{ "youparametername": yourdata}, function (data) {
$.each(data, function (index, item) {
})
});
inside the options object, make sure to use the
dataType: 'json'
Or in the success handler you can use
JSON.parse(data)
Cured: Changed my loop to cycle through each item in the returned JSON, got their keys, etc...
var $dl = data.length;
for(var $i = 0; $i < $dl - 1; ++$i) {
var $keys = Object.keys(data[$i]);
$html += '<option value="' + data[$i][$keys[0]] + '">' + data[$i][$keys[1]] + '</option>';
}
Related
I'm selecting values from my db in mysql and comparing them with values from JSON. I'm receiving the right results but since I'm using append the results shows up one by one, which looks like animation I would like to get them all at once and show some kind of loading icon while the loop is running, I've tried few different ways but nothing worked.
<?php $sql= "select a_id,b_id,res_a,res_b from betts_gr where u_id='".$u_id[0]."'";
$user_bets = mysqli_query($conn,$sql);
while($user_bets1 = mysqli_fetch_array($user_bets)){
?>
<script>
$(document).ready(function() {
var a_id = "<?php echo $user_bets1[0]?>";
.....
var car = [];
$.getJSON('http://api.football-api.com/2.0/matches?
comp_id = 1204 & from_date = '+today+' & to_date = '+plusmonth+' & Authorization ',
function(data) {
var html = "";
console.log(data);
$.each(data, function(index, value) {
var teama = value.localteam_name;
var teamb = value.visitorteam_name;
.......
function add(name, point) {
car.push({
teamb: teamb,
teama: teama,
form: form,
data: data,
teama_id: teama_id,
teamb_id: teamb_id,
a_res: a_res,
b_res: b_res
});
}
add(teama, teamb, data, form, teama_id, teamb_id, a_res, b_res);
});
for (var n = 0; n < car.length; n++) {
if (car[n].teama_id == a_id && car[n].teamb_id == b_id) {
html += "<tr><td><input type='hidden' name='aid" + n + "'
value = '"+car[n].teama_id+"' > < input type = 'hidden'
name = 'bid"+n+"'
value = '"+car[n].teamb_id+"' > " +
car[n].data +
"</td><td> " + car[n].teama + "</td><td>" + car[n].a_res + "-" +
car[n].b_res + "</td><td> " +
car[n].teamb + '</td><td> you predicted ->' + pred_resa + ' - ' + pred_resb +
'</tr>';
}
}
$(".message").append(html);
});
});
</script>
<?php } ?>
the example for using the Array.map and the template literals instead of the for loop and the plain string concat:
const isTargetTeam = item => item.teama_id == a_id && item.teamb_id == b_id;
const html = car.slice(0) // copy the array car
.filter(isTargetTeam)
.map((item, index) =>
`<tr>
<td>
<input type='hidden' name='aid${index}' value='${item.teama_id}'>
<input type='hidden' name='bid${index}' value='${item.teamb_id}'>
${item.data}
</td>
<td>
${item.a_res}-${item.b_res}
</td>
<td>
${item.teamb}
</td>
<td> you predicted -> ${pred_resa} - ${pred_resb}
</tr>`
).join('')
You should not mix PHP and Javascript like that. Currently this will result in X document.ready functions with X getJSON requests.
If you want to do the API requests from the local client, you should do ONE javascript function where you pass in the selected user_bets as an array. There are different possibilities to determine if all loadings have been finished: either counting up and checking after every callback if the max number is reached, or using Promises and Promise.all().
<script>
var user_bets = <?php echo json_encode($user_bets);?>;
$(document).ready(function () {
Promise.all(user_bets.map(function (id) {
return fetchFromApi(id);
})).then(function(array){
var html = "";
for(var i = 0; i < array.length; i++){
html += processData(array[i]);
}
$(".message").append(html);
});
});
function fetchFromApi(user_id) {
return new Promise(function (resolve, reject) {
$.getJSON()
.done(function (data) {
resolve(data);
})
.fail(function (error) {
reject(error);
});
});
}
function processData(data){
var html = '';
// do your html processing of a single api call here
return html;
}
</script>
Alternatively you can use CURL to do the API requests server-side already.
Thanks for advise I just realize I should get data with one request. I've passed the whole array to js and since I'm not sure how promise.all is working I did two for loops nested and is working fine, the only thing I still can't figure out how to check if the loops are finished so I could add loading icon while loop is running.
function add(name, point) {
car.push({ teamb : teamb, teama : teama, form:form, data:data, teama_id:teama_id,
teamb_id:teamb_id, a_res:a_res, b_res:b_res});
}
add(teama,teamb,data,form,teama_id,teamb_id,a_res,b_res);
});
for(var n=0;n<car.length;n++){
var taba = [<?php echo json_encode($at1)?>];
var tchild = taba[0];
for(var u=0;u<tchild.length;u++){
if(car[n].teama_id == tchild[u].localteam_id
&& car[n].teamb_id == tchild[u].visitorteam_id){
html += "<tr><td><input type='hidden' name='aid"+n+"'
value='"+car[n].teama_id+"'>
<input type='hidden' name='bid"+n+"'
value='"+car[n].teamb_id+"'>"
+car[n].data
+"</td><td> "+car[n].teama + "</td><td>"+ car[n].a_res
+ "-"+ car[n].b_res + "</td><td> "
+ car[n].teamb + '</td><td> you predicted -
>'+tchild[u].localteam_score +' - '+tchild[u].visitorteam_score +
'</td></tr>';
}
}
}
$(".message").append(html);
i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');
I have the following jquery funcion that's supposed to get a value from a text field:
My Php Code
function asset_status() {
$query = $this->db->query("SELECT count(job_card_no) as job_card_no,number,asset.type,asset.status,asset.id as asset_id FROM asset inner join assgnd_rsces on assgnd_rsces.name = asset.id inner join job_card on job_card.id = assgnd_rsces.job_card_id");
$result = $query->result_array();
echo json_encode($result);
}
ajax request
asset_status_list = '';
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>operations/asset_status",
dataType: "JSON",
success: function (response) {
console.log(response); // it gives following
//job_card_no "2" number "1" status "Active" type "Toilet"
for (i = 0; i < response.length; i++) {
asset_status_list = '<tr><td >' + response[i].job_card_no + '</td><td >' + response[i].number + '</td><td>' + response[i].type + '</td><td ><input type="hidden" name="view_more_id" class="view_more_id' + response[i].id + '" id="view_more_id" value="' + response[i].id + '"/><button id="view_more_link" class="view_more_link' + response[i].id + '"><i class="glyphicon glyphicon-zoom-in "></i>View More</button></td></tr>';
$('#asset_status_tr').append(asset_status_list);
$("#asset_status_tr").on("click", ".view_more_link" + response[i].id, function () {
var asset_id = $(".view_more_id"+response[i].id).val();
alert(asset_id);
});
}
$('#asset_table_status').DataTable({});
},
error: function (response) {
}
});
However when I try it using the above function, I get the following error on click of the button.
TypeError: response[i] is undefined
var asset_id = $(".view_more_id"+response[i].id).val();
How do I solve the above error ?
Yes, you are not getting 'json' from file that's why its length is 0 and its shown you 'undefined'.Please make sure that.
I have code which return loop from php to ajax via json_encode()
Let me know what I want to do.
there is one table call SMTP. Assume that it has 3 value and I want to fetch that 3 value from table, store in array () and Display it to HTML via AJAX in table format.
So I'm confused where I place my loop, in AJAX or PHP ?
Here is my code.
PHP
$result=mysql_query("select * from ".$db.".smtp WHERE id = '$user' ");
if($result === FALSE) {
die(mysql_error());
}
while($data = mysql_fetch_row($result))
{
$array = array($data[2],$data[3]);
}
echo json_encode($array);
JS
$(document).ready(function() {
GolbalURL = $.session.get('URL');
$.ajax({
type: "GET",
url: GolbalURL+"smtp.php",
dataType: "html",
success: function(response){
$("#divsmtp").html(response);
}
});
});
HTML
<div id = "divsmtp"></div>
This code return only last value. inarray like ["data2","data3"]
My Longest way to do
success: function(response){
resultObj = eval (response);
var i = Object.keys(resultObj).length;
i /=2;
//$("#divsmtp").html(i);
var content = "<table>"
for(j=0; j<i; j++){
k = j+1;
if (j % 2 === 0)
{
alert("j="+j+" k="+k );
content += '<tr><td>' + resultObj[j] + resultObj[k] + '</td></tr>';
}
else
{
k = k+1;
var m = j+1;
alert("m="+m+" k="+k );
content += '<tr><td>' + resultObj[m] + resultObj[k] + '</td></tr>';
}
}
content += "</table>"
$('#divsmtp').append(content);
}
Because you are always overwrite the $array variable with an array.
Use: $array[] = array($data[2], $data[3]);
Use json decoding at jquery end
EDIT Small way
$.each($.parseJSON(response), function( index, value ) {
//Loop using key value LIKE: index => value
});
//Old
success: function(response){
var jsonDecoded = $.parseJSON(response);
console.log(jsonDecoded );
$.each(jsonDecoded, function( index, value ) {
//Loop using key value LIKE: index => value
});
$("#divsmtp").html(response);
}
Create the array on the PHP side like this -
$array = array();
while($data = mysql_fetch_row($result))
{
array_push($array, $data);
}
echo json_encode($array);
I have two tables A & B
TableA // (People)
UserID Name
10 Dan
20 Jane
30 Shelley
TableB // (Pics)
PicID UserID
100 10
200 10
300 20
I want to take everything from Table A and load it into an array and then add arrays for the images within the array but am unsure how to do this:
Currently for Table A I think:
$query = "select * from TableA";
$result = $mysqli->query($query) or die(mysqli_error($mysqli));
while ($row = $result->fetch_array()){
$array[] = $row;
// do another select here to get pics and add data to array multiDimensionally
}
echo json_encode($array);
Then I'm reading it like:
$.ajax({
url: apiURL,
dataType: 'json',
success: onLoadData
});
function onLoadData(data) {
// Create HTML for the images.
var html = '';
var i = 0, length = data.length, image;
for (; i < length; i++) {
image = data[i];
html += '<div class="holder">';
html += '<div class="name">' + image.Name + '</div>;
// do another loop here to show images for each person
html += '</div>';
}
Is this the best way to do it and if so, how would I add to the array and then read from it?
If I am not wrong then this can be done in another way-
Mysql :
$query = "select * from TableA join TableB on TableA.UserID=TableB.UserId order by TableA.UserID asc";
And the Jquery part:
$.ajax({
url: apiURL,
dataType: 'json',
success: function(data)
{
$.each( data, function( key, value ) {
//alert( key + ": " + value ); //do what ever you want
});
}
});