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>
Related
I'm working on an app where I get a json via an ajax call. This json contains objects where you get a certain status code per extension (1 = online, 2, is ringing, 3 = busy)
How can I ensure that the value that I get back is converted to the text (preferably with a different color of the )
So when I get a 1 back I want it to show Online, and with a 2 Ring etc
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
// console.log(JSON.parse(data.responseText));
// console.log(JSON.parse(data.responseJSON));
console.log(data['entry']);
var event_data = '';
$.each(data.entry, function(index, value){
/* console.log(data['entry']);*/
event_data += '<tr>';
event_data += '<td>'+value.extension+'</td>';
event_data += '<td>'+value.status+'</td>';
<!--event_data += '<td>'+value.registration+'</td>';-->
event_data += '</tr>';
});
$("#list_table_json").append(event_data);
},
error: function(d){
/*console.log("error");*/
alert("404. Please wait until the File is Loaded.");
}
});
Thanks in advance!
I have change the code
function get_blf() {
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.status;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
}
});
}
}
and add the css, but now i can't get any values back. but now i can't get any values back. (sorry I'm fairly new to javascript)
Please use the DOM API
One way of getting colors would be to use CSS classes for the status:
// js
...
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.extension;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
...
// css
.status-1 {
color: green;
}
.status-2 {
color: red;
}
.status-3 {
color: orange;
}
I finally got the script working. I am now trying to build in a polling, however I see that the ajax call is executed again and the array is fetched. However, the table is not refreshed but a new table is added, does anyone know a solution for this?
code I'm using now for the repoll is
function repoll(poll_request, poll_interval, param=null) {
if (poll_interval != 0) {
if (window.timeoutPool) {
window.timeoutPool.push(setTimeout(function() { poll_request(param); }, poll_interval));
}
else {
setTimeout(function() { poll_request(param); }, poll_interval);
}
}
else {
log_msg('Poll cancelled.');
}
}
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdNr);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
repoll(get_blf, poll_interval_blf);
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 am using codeigniter 3 and I am new for codeigniter. I want to ask that which method is more suitable to pass data from view to controller, using jquery or <form action="controller/method">
I am trying to pass data using jquery but it does not giving any response and no error will be shown. Jquery code is given:
function registration()
{
var txtemail = document.getElementById("email").value;
$.post("<?php echo site_url('Home/registration'); ?>", {checkEmail: txtemail, action: "registerUser"},
function(data) {
var result = data + "";
if (result.lastIndexOf("Success") > -1) {
} else {
var txtUser = document.getElementById("username").value;
var txtContact = document.getElementById("contact").value;
var txtEmail = document.getElementById("email").value;
var txtpincode = document.getElementById("pincode").value;
var txtCity = document.getElementById('city').value;
var txtState = document.getElementById('state').value;
var txtCountry = document.getElementById("country").value;
var txtPackage = document.getElementById("package").value;
var registerMstData = new Array();
registerMstData[0] = txtUser;
registerMstData[1] = txtContact;
registerMstData[2] = txtEmail;
registerMstData[3] = txtpincode;
registerMstData[4] = txtCity;
registerMstData[5] = txtState;
registerMstData[6] = txtCountry;
registerMstData[7] = txtPackage;
$.post("<?php echo site_url('Home/registration') ?>", {pageData: registerMstData, action: "save"},
function(data) {
var result = data + "";
window.alert(result);
})
.fail(function(req, status, err) {
console.error('Error : ' + err + " status : " + status + " request " + req.toString());
alert('Error : ' + err + " status : " + status + " request " + req.toString());
});
}
});
}
What I am doing wrong I don't understand? Please help.
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload.
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
It all depends on how you want it to be
Update
For ajax, you can use
$.ajax({
url: 'your url',
data: {
format: 'json'
},
error: function(err) {
// handle error here
},
data: yourData
success: function(data) {
// handle success here
},
type: 'POST'
});
I want to save my ViewModel to my SQL server. The standard knockout ko.toJSON(viewModel) keeps giving me an undefined error, so after some digging i found this Question, but still keeps giving me undefined.
Here is the code for my viewmodel, this is just a currency conversion table that gets the Conversion Rate between 2 currencies.
//ko Event Handler for datepicker.js
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options).on("changeDate", function (ev) {
var observable = valueAccessor();
observable(ev.date);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).datepicker("setValue", value);
}
};
//Currency Model Definition
var currency = function (data) {
var self = this;
self.DateCreated = ko.observable(formatJsonDate(data.DateCreated));
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(data.ConversionRate);
//Yhoo Finance API
ko.computed(function () {
var from = self.CurrencyFrom(),
to = self.CurrencyTo();
if (!from || !to) {
self.ConversionRate("N/A");
return;
}
getRate(from, to).done(function (YahooData) {
console.log("got yahoo data for [" + from + "," + to + "]: ", YahooData);
self.ConversionRate(YahooData.query.results.row.rate);
});
});
}
var NewDate = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + new Date().getDate();
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push({
DateCreated: NewDate,
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
});
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function () {
$.ajax({
url: "#",
contentType: 'application/json',
data: ko.mapping.toJSON(CurrencyModel),
type: "POST",
dataType: 'json',
success: function (data) {
//I get undefined....
alert(ko.mapping.toJSON(CurrencyModel));
},
error: function (data) { alert("error" + data); }
});
}
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
data: '{}',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
// callback(Result);
var MappedCurrencies =
$.map(Result.d,
function (item) {
getRate(item.CurrencyFrom, item.CurrencyTo);
return new currency(item);
}
);
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
function formatJsonDate(jsonDate) {
var FormatDate = new Date(parseInt(jsonDate.substr(6)));
var Output = FormatDate.getFullYear() + '-' + ("0" + (FormatDate.getMonth() + 1)).slice(-2) + '-' + FormatDate.getDate();
return (Output);
};
function getRate(from, to) {
return $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=?");
}
function callback(data) {
if (viewModel) {
// model was initialized, update it
ko.mapping.fromJS(data, viewModel);
} else {
// or initialize and bind
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
}
}
$('#Date').datepicker();
$(document).ready(function () {
var VM = new CurrencyModel();
ko.applyBindings(VM);
})
data: ko.mapping.toJSON(CurrencyModel)
You are trying to JSONify the definition not the actual instance
Isn't the method that you want to use:
ko.toJSON
rather than off the mapping object?
I have the following script which is able to access a jsonp feed and get data from it:
$(document).ready(function() {
get_jsonp_feed();
function get_jsonp_feed() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20html%20WHERE%20url%3D%22http%3A%2F%2Fnews.bbc.co.uk%2Fweather%2Fforecast%2F4276%3Fsearch%3Dgerrards%2520cross%26itemsPerPage%3D10%26region%3Dworld%26area%3DGerrards%2520Cross%22%20and%20xpath%20%3D%20'%2F%2Ftable%2Ftbody%2Ftr'&format=json&diagnostics=true&callback=cbfunc",
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var itemList = data.query;
alert(itemList.count);
/*
var buildHTML = [];
for (var i = 0; i < 5; i++) {
buildHTML.push('<div class="container">' + itemList[i].title + '<br /><span class="dateandtime">' + itemList[i].pubDate + '</span></div>');
}
$('.portlet-content').empty().append(buildHTML.join('<hr />'))
*/
}
});
}
});
That gives me 5 which is right. I now want to get data which is more embedded in the jsonp, but I have having difficulty. For example, I want to get:
data.query.results.tr.td.div.abbr.title
How would I go about getting that?
Here is a jsfiddle of it returning 5:
http://jsfiddle.net/B6hRG/1/
Here is some fixed code to get JSONP instead of XML:
$(document).ready(function() {
get_jsonp_feed();
function get_jsonp_feed() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%20%3D%20'http%3A%2F%2Fnews.bbc.co.uk%2Fweather%2Fforecast%2F4276%3F%26search%3Dgerrards%2520cross%26itemsPerPage%3D10%26region%3Dworld%26area%3DGerrards%2520Cross'%20and%20xpath%20%3D%20'%2F%2Ftbody%2Ftr'&format=json&callback=?",
type: 'GET',
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var itemList = data.query;
alert(itemList.count);
/*
var buildHTML = [];
for (var i = 0; i < 5; i++) {
buildHTML.push('<div class="container">' + itemList[i].title + '<br /><span class="dateandtime">' + itemList[i].pubDate + '</span></div>');
}
$('.portlet-content').empty().append(buildHTML.join('<hr />'))
*/
}
});
}
});
To get data like data.query.results.tr.td.div.abbr.title you'd have to either use a for loop on the data.query.results.tr.td object, and any others with siblings, or use XML and get the raw html, put it into a document fragment and use jQuery on that.