Is it possible to use response.DATA[i][j] in a CFIF statement.
chkUsernameUnique = function(theUsername){
$.ajax({
type: "GET",
url: "/book.cfc",
data: {method: "testFunction", datum: $('#date').val(), returnFormat: "JSON"},
dataType: "json",
success: function(response) {
var str = '<table><tr>';
var i;
var j;
//loop over each column name for headers
for (i = 0; i < response.COLUMNS.length; i++) {
str += '<th>' + response.COLUMNS[i] + '</th>';
}
str += '</tr>';
//loop over each row
for (i = 0; i < response.DATA.length; i++) {
str += '<tr>';
//loop over each column
for (j = 0; j < response.DATA[i].length; j++) {
str += '<td>' + response.DATA[i][j] + '</td>';
}
str += '</tr>';
}
str += '</table>';
$('#debugDiv').html(str);
},
error: function(ErrorMsg) {
console.log('Error');
}
});
}
What I want to do is something like:
<cfif response.DATA[i][j] is 3> str += '<td>test</td>';</cfif>
This returns the following error message: variable [RESPONSE] doesn't exists.
The response variable is the server response for your AJAX request and you are working with it on clientside. Thus you are still in the realm of JavaScript:
if (response.DATA[i][j] == 3) { str += '<td>test</td>'; }
ColdFusion (i.e. <cfif>) is executed on serverside, thus cannot be used to evaluate data during runtime (after the browser requested an URI).
Related
I'm trying to fetch data from JSON response in a datatable and it works fine. My next step is to add a pagination for all rows. Since I'm using Laravel I've earlier used Laravels built-in system:
{{ $var->links() }}
Now since I'm receiving the response from a POST request to filter out dates, I'm struggling with filtering amount of rows per page. I've tried to Google around without and couln't find a good answer.
I'm a beginner in JavaScript and some support would really help!
This is my code ATM:
$("#date").ready(function() {
$("#date").on('change', function() {
var date = $("#date").find(':selected').val();
var token = $("input[name='_token']").val();
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
fetch_data(page);
});
$.ajax({
url: "{{ route('mydata') }}",
type: "POST",
data: {
'date': date,
'_token': token
},
dataType: "json",
success: function(data) {
console.log(data);
function status() {
if (data[i].status = 1) {
return '<td class="px-4 py-4"><span class="bg-yellow-500 font-semibold text-white p-2 rounded">Active</span></td>';
}
if (data[i].status = 2) {
return '<td class="px-4 py-4"><span class="bg-blue-500 font-semibold text-white p-2 rounded">Closed</td>';
}
}
function formatDate(date) {
var date = new Date(date);
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth() + 1)
.toString(); // getMonth() is zero-based
var dd = date.getDate().toString();
var h = date.getHours().toString();
var h = ("0" + h).slice(-2);
var m = date.getMinutes().toString();
return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd :
"0" + dd[0]) + ' ' + h + ':' + m;
}
function remaining_days(start, end) {
var start = new Date(start);
var end = new Date(end);
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const s = Date.UTC(start.getFullYear(), start.getMonth(), start
.getDate());
const e = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
if (end - start < 0) {
return '<span class="text-red-800 font-bold">Late</span>';
} else {
return Math.floor((e - s) / _MS_PER_DAY) + ' Days left';
}
}
var output = '';
for (var i = 0; i < data.length; i++) {
output += '<tr class="bg-gray-100 text-center">';
output += '<td class="px-4 py-4">New</td>';
output += '<td class="px-4 py-4">' + formatDate(data[i].updated_at) +
'</td>';
output += '<td class="px-4 py-4">' + data[i].title + '</td>';
output += '<td class="px-4 py-4">' + data[i].get_admin.first_name +
' ' + data[i]
.get_admin.last_name + '</td>';
output += '<td class="px-4 py-4">#' + data[i].id + '</td>';
output += '<td class="px-4 py-4">' + remaining_days(data[i].created_at,
data[i].end_date) +
'</td>';
output += status();
output += '</tr>';
}
$('#myticketstable').html(output);
},
error: function(xhr) {
if (xhr.status == 422) {
const errors = JSON.parse(xhr.responseText);
console.log(errors);
$.each(xhr.responseJSON.errors, function(i, error) {
console.log('something went wrong');
});
}
}
});
}).trigger('change');});
Best regards
I am trying to parse Bing Search API Version 7 JSON using the following code, but not sure what I am doing wrong. Would like to parse "name" and "url", my code is below.
Bing JSON Results are at the following URL -> http://52.15.219.114/bing2.php?q=freebsd&s=10&p=0&m=en-us
var e = escape($('#book').val());
var pg = 10;
var limit = 0;
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:pg, p:limit },
success: function(data) {
len = data.webPages.value.length
for (i=0; i<len; i++ ){
results += "<p><a href='" + data.webPages.value[i].url + "'>" + data.webPages.value[i].name + "</a>: " + data.webPages.value[i].snippet + "</p>";
}
$("#bookout").html(results);
},
error: function() {
// console.log(data);
}
});
Below is a fix for parsing the Bing Search JSON API.
var e = escape($('#book').val());
var pg = 10;
var limit = 0;
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:pg, p:limit },
success: function(data) {
var obj = JSON.parse(data)
var ocean = obj.webPages.value; //client prop is an array
for(var i = 0; i < ocean.length; i++){
//alert(ocean[i].name);
//FORMAT RESULTS
var ocean_format = '<div><div>' + '' + ocean[i].name + '</div><div>' + ocean[i].snippet + '</div><div class="text-secondary">' + ocean[i].displayUrl + '</div></div>';
$("#bookout").append(ocean_format);
}//END SEARCH RESULTS
},
error: function() {
// console.log(data);
}
});
I want to create a site_url codeigniter link to call the controller in json, how to write correctly?
really need help.
function tampil_data_customer(){
$.ajax({
type : 'ajax',
url : '<?php echo base_url()?>index.php/selling_process/all_customer',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var j=1;
for(i=0; i< data.length; i++){
html += '<tr>'+
'<td>'+j+++'</td>'+
'<td><a href="<?php site_url('selling_process/view/'); ?>"'+data[i].id_customer+'>'+data[i].name_customer+'</a></td>'+
'<td>'+data[i].name_customer_type+'</td>'+
'<td>'+data[i].name_sector+'</td>'+
'<td>'+data[i].name_user+'</td>'+
'<td></td>'+
'<td>'+data[i].name_status+'</td>'+
'<td>'+data[i].update_date+'</td>'+
'<td></td>'+
'<td></td>'+
'</tr>';
}
$('.show_data').html(html);
}
});
}
this part is not working
'<td><a href="<?php site_url('selling_process/view/'); ?>"'+data[i].id_customer+'>'+data[i].name_customer+'</a></td>'+
I think the best way to do that would be using JavaScript. You can get the base URL of your site then append the required URL to it.
To get the base url in JS,
function getBaseUrl() {
var pathparts = location.pathname.split('/');
if (location.host == 'localhost' || location.host == '127.0.0.1' || location.host == '::1') {
var url = location.origin + '/' + pathparts[1].trim('/') + '/'; // http://localhost/myproject/
}else{
var url = location.origin + '/';
}
return url;
}
After that, you can use this function to get the base URL in your HTML/JS file like this,
function tampil_data_customer(){
$.ajax({
type : 'ajax',
url : '<?php echo base_url()?>index.php/selling_process/all_customer',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var j=1;
for(i=0; i< data.length; i++){
html += '<tr>'+
'<td>'+j+++'</td>'+
`<td><a href=${getBaseUrl() + 'selling_process/view/'}`+data[i].id_customer+'>'+data[i].name_customer+'</a></td>'+
'<td>'+data[i].name_customer_type+'</td>'+
'<td>'+data[i].name_sector+'</td>'+
'<td>'+data[i].name_user+'</td>'+
'<td></td>'+
'<td>'+data[i].name_status+'</td>'+
'<td>'+data[i].update_date+'</td>'+
'<td></td>'+
'<td></td>'+
'</tr>';
}
$('.show_data').html(html);
}
});
}
'<td>'+data[i].name_customer+'</td>'+
I am using below anchor tag,in using json object.How to write it using html helper method.
success: function (data) {
var str = "";
for (i = 0; i < data.length; i++) {
str += "<a href=/Home/GetArtistRelatedData?str=" + data[i].ArtistName + " target='_blank' style='color:gold;'>" + data[i].ArtistName + "</a><br/>";
}
$("#mm").append(str);
}
How to properly append json result to a select option,
sample json data
Ajax code:
$.ajax({
url: 'sessions.php',
type: 'post',
datatype: 'json',
data: { from: $('#datepicker_from').val().trim(), to: $('#datepicker_to').val().trim() },
sucess: function(data){
var toAppend = '';
//if(typeof data === 'object'){
for(var i=0;i<data.length;i++){
toAppend += '<option>'+data[i]['id']+'</option>';
}
//}
$('#sessions').append(toAppend);
}
});
html code:
<p>Sessions:
<select id="sessions"></select>
I already set to my php file
header("Content-Type: application/json");
Use $.each to iterate through your JSON array that you receive from ajax call.
Note:- the spelling of success, you have written sucess.
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.id+'</option>';
});
$('#sessions').append(toAppend);
}
You can do append to the DOM directly inside the each loop but it is always better to concatenate with string and then adding to the DOM later. This is a cheaper operation since you are accessing DOM only once in this case. This might not work in some complex scenarios though.
success: function(data) {
var options = "";
for (var i = 0; i < data.length; i++) {
options += "<option>" + data[i].id + "</option>";
}
$("#sessions").html(options);
}
If your response is in multidimensional array then try as follows
success: function(data) {
var options = '';
for (var i = 0; i < data.length; i++) {
for (var j = 0; j< data[i].length; j++){
options += '<option value="' + data[i][j].product_id + '">' + data[i][j].name + '</option>';
}
}
$("#products").html(options);
}
I hope this will help you to append
for(i=0; i<data.length; i++) {
$('#sessions').append("<option value="+data[i].id+"/option>");
}
Let You receive json data in parameter data
var obj = JSON.parse(data);
for(i=0; i<data.length; i++) {
$('#sessions').append("<option value="+obj[i].id+">"+obj[i].name+"</option>");
}
Please try the below code this may help you.
these code i used in spring boot MVC
JSON Data
[{"name":"Afghanistan","code":"af"},
{"name":"Albania","code":"al"},
{"name":"Algeria","code":"dz"}]
JQuery Code
var jsonData = '${restData}';
var obj = JSON.parse(jsonData);
for (i in obj) {
$('#selectList').append(new Option(obj[i].name, obj[i].code));
}