how to write site_url link in json - json

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>'+

Related

Parsing JSON Bing Search API using JQuery

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);
}
});

Database mapping in Leaflet with (JSON, AJAX)

I get this JSON from DeviceNewController
public function index(Request $request)
{
$device_new = Device_new::with(['device']);
return Device_new::all()->toJson();
}
And when I wrote AJAX in view blade, it show me data from DB in console.
<script>
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
console.log(newdev.responseText);
};
newdev.send();
</script>
But I need to pass it in Leaflet script and write all data on map (coordinates, markers, device info)
When I set all in one script, there is no data in console, I can not fix it.
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
var coordinates = newdev.responseText;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
};
};
newdev.send();
Did i make a mistake somewhere, is this correct???
You miss understood Ajax. Ajax is a function from JQuery, a JS library.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
You have to add the JQuery library to your source, then you can create a Ajax call.
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({url: "/devices_new", success: function(result){
//result = JSON.parse(result); // If your result is not a json Object.
var coordinates = result;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
}
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
I make it on this way, and its working.
<script>
$(document).ready(function() {
$.ajax({
/* the route pointing to the post function */
url: '/device_new',
type: 'GET',
data: {
message: $(".getinfo").val()
},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function(data) {
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
</script>

Using JSON response in CFIF

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).

How to properly append json result to a select option

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));
}

jQuery - google chrome won't get updated textarea value

I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.
I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>