Display JSON result in table Laravel 5.8 - json

I want to display the JSON results to my HTML table in Laravel 5.8.
The result returned from the controller is as follows.
[[{"logged_on":"2019-06-24 00:00:00"},{"logged_on":"2019-06-21 00:00:00"}]]
My Ajax success function is as follows:
$.ajax({
url: url,
type: "get",
data: {user_id:user_id},
contentType: "application/json",dataType: "json",
success: function(data){ // What to do if we succeed
if(data){
alert(data);
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].logged_on){
txt += "<tr><td>"+data[i].logged_on;
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
else{
alert("fails");
}
}
});
Below is my controller function
$user_id = $requests->input('user_id');
$data = UserLogins::select('logged_on')->where('user_id',$user_id)->get()->toArray();
return response()->json(array($data));
But I am not getting the result in my table.

$user_id = $requests->input('user_id');
$data = UserLogins::select('logged_on')->where('user_id',$user_id)->get()->toArray();
return response()->json($data); // remove array() because $data return array

Related

How change display value/color td based on JSON

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

How to save to database by using ajax

I have a code which is works fine, but the data cannot save to the database. I want to insert cost, currency_rate, profit_rate and pprice to database through Ajax. Here are the code of javascript and update.php, I have tried to modify the code to save in my Mysql server, but it didn't success. Can someone help with this?
javascript
$(".profitRate").change(function() {
var myArray = [];
//find closest table->next table
var elem = $(this).closest('table').next('table');
var action = elem.find('tr').data('action');
console.log(action)
var profitRate = Number($("#profitRate").val());
//looping
elem.find('tr').each(function() {
//get cost
var cost = $(this).find('input[name=cost]').val();
//get curency rate
var currecy_rate = $(this).find('select[name=currency_rate]').val();
//calculate profit
var profit_total = Math.round(cost * profitRate * currecy_rate)
$(this).find('input[name=pprice]').val(profit_total)
//add to json object
auto_array = {};
auto_array["cost"] = cost;
auto_array["currecy_rate"] = currecy_rate;
auto_array["pprice"] = profit_total;
myArray.push(auto_array) //push to array
});
console.log(myArray)
form_data = elem.find('tr').data('action');
$.ajax({
data: {
action: action,
form_data: form_data,
},
url: 'update.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
}
}
});
})
update.php
<?php
if ($_POST['action'] == 'update_price') {
parse_str($_POST['form_data'], $my_form_data);
$id = $my_form_data['id'];
$cost = $my_form_data['cost'];
$profit_rate = $my_form_data['profit_rate'];
$currency_rate = $my_form_data['currency_rate'];
$pprice = $my_form_data['pprice'];
$sql = $query = $finalquery = $sqlresult = '';
if ($cost){
$sql.="cost='$cost',";
}
if ($profit_rate){
$sql.="profit_rate='$profit_rate',";
}
if ($currency_rate){
$sql.="currency_rate='$currency_rate',";
}
if ($pprice){
$sql.="pprice='$pprice',";
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where id=$id";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
}

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>

Wordpress custom JSON feed with multiple categories

Good morning to all.
It is possible to have a custom JSON feed with the last 10 posts from all categories with 10 or more posts published?
I'm doing that with a loop over all categories with 10 or more posts published using the JSON API plugin for wordpress by dphiffer
So if I have 14 categories I will do 140 requests and overload the server.
I'm searching for a way to do that with 1 or 2 requests. Like first request to get the categories indexes with 10 or more posts and the second request with all the data.
Thanks
Here is the code i've developed so far:
<script type="text/javascript">
var slug = 'news'; // Main categorie
var maxLength = 10; // Total of articles per categorie
var wpurl = 'http://wpurl.com'; // WP URL
var loadedValue, loadedTotal;
var categories = new Array();
var newsData = new Array();
//Get main categorie index by slug
$.ajax({
url: wpurl+'/?json=get_category_index',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
if(cat.slug == slug) {
get_all_categories(cat.id);
}
}
},
error: function(data){
console.log(data);
}
});
//Get all sub-categories from an categorie slug
function get_all_categories(cat_index) {
$.ajax({
url: wpurl+'/?json=get_category_index&parent='+cat_index,
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
//Check if categorie have 10 (maxLength) or more posts. If so push it to array (categories)
if(cat.post_count >= maxLength) {
categories.push({
'index': cat.id,
'title': cat.title
});
}
}
},
error: function(data){
console.log(data);
}
}).done(function() {
//Set loading
var totalItem = categories.length*maxLength;
var actualItem = 0;
var loaded = 0;
for(var i=1; i<=categories.length; i++){
prepareCategory(categories[i-1].index, maxLength, i);
function prepareCategory(categorieIndex, maxLenght, count) {
var content;
$.ajax({
url: wpurl+'/api/get_category_posts?category_id='+categorieIndex+'&count='+maxLenght+'&status=publish',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (e = 0; e < data.posts.length; e++) {
//Loading percent
actualItem++;
loaded = (actualItem/totalItem)*100;
document.getElementById('loadingBox').innerHTML = 'Loading: '+Math.round(loaded)+'%';
//Post data
var post = data.posts[e];
var title = post.title;
var thumb = post.thumbnail_images.appthumb.url || 'content/images/noimage.png';
var newContent = '<div class="new"><img src="'+thumb+'" width="320" height="164"><div class="new_description">'+title+'</div></div>';
var newId = 'cat'+count+'new'+(e+1);
newsData.push({
'id': newId,
'content':newContent
});
}
},
error: function(data){
console.log(data);
}
});
}
}
});
};
function loaded() {
if (window.localStorage.length != 0)
{
localStorage.clear();
setGlobalStorageAndRedirect();
} else {
setGlobalStorageAndRedirect();
}
function setGlobalStorageAndRedirect() {
localStorage.setItem('postPerCat', maxLength);
localStorage.setItem('catNumbs', categories.length);
localStorage.setItem('wpurl', wpurl);
localStorage.setItem('categoriesArray', JSON.stringify(categories));
localStorage.setItem('newsData', JSON.stringify(newsData));
window.location="main.html";
}
}
</script>

comparing json submitted array and sql returned array and printing difference in text file

I am submitting a javascript array to another php page via ajax which runs a query and returns another array. Then i would like to compare these two arrays and print the difference in a text file. The code give below is creating a text file with no data in it.
Here is the code
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = '[';
values+=valueSelected+",";
for ($i=3;$i<row;$i++)
{
var dv="selectcity"+$i;
var dv1=document.getElementById(dv).value;
var sl="street"+$i;
var sl1=document.getElementById(sl).value;
var po="building"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values+=''+concat+',';
}
values = values.substring(0,values.length-1);
values += ']';
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: {data: values} ,
success: function(){
alert("Success!")
}
});
the value sent to the get_buildings.php is
[newyork::roosevelt st,springfieldevergreen terraceno42,quahogspooner streetno43]
Php code get_buildings.php:-
$a1='newyork::roosevelt st';
$sl= explode("::",$a1);
$a=$sl[1];
$connection_buildings= mysqli_connect('localhost', 'xxxx', 'xxxx', 'DETAILS') or die ('Cannot connect to db');
$sql_query_3 = "select buildings from $a";
$result_query_3=mysqli_query($connection_buildings,$sql_query_3) or die ("check it");
$options=array();
while ($row = $result_query_3->fetch_assoc())
{
$name = $row['buildings'];
$val=$a.$sl[0].$name;
array_push($options,$val);
}
$result = array_diff($_POST['data'], $options);
$fp = fopen("textfile.txt", "w");
fwrite($fp, $result);
fclose($fp);
mysqli_close($connection_buildings);