My existing extJS code passes readData.php a param object
params: {
start: 0,
limit: 1000,
proc_nm: 'sel_bkng_srch',
srchStrng: '',
parms: [[dnStrng,1],[mtStrng,1],[dtFromStrng,1],[dtToStrng,1]],
connId: 'AW'
}
so it can call a stored procedure which I want to share with d3. After lots of attempts, latest is:
d3.json("php/readData.php")
.header("params", "params: {start: 0,limit: 1000,proc_nm: 'sel_bkng_srch',srchStrng: '',parms: [1,1],[2,1],[3,1],[4,1]],connId: 'AW'}")
.get(function(error, data) {
console.log('readData: ', error) ;
});
I do not have the syntax correct to pass the object with d3.json. Everything else is functional I think - php gets called, returns an empty success object (php code needs looking at here) which is picked up back in d3. tia.
Related
I have a forum project with Laravel 9, and I have made this helper function.
if(!function_exists('new_question')){
function new_question($c) {
$quelist = \DB::table('questions')->get();
$quecount = $quelist->count();
if($quecount > $c){
return 'A new question is added.. please refresh the page..';
}
}
}
So it gets the number of current questions like this:
{{ new_question($queCnt); }}
And then, it will check if the $quecount equals $queCnt or not. And if not, then print the statement A new question is added.. please refresh the page... Therefore the user will understand if any new question is added. But I need to run this helper function after some periods of time (for example, 10 seconds). However, I don't know how to call a function after a custom amount of time.
to run any function after a specific time, you have set the interval for example
// Call the new_question function every 10 seconds
setInterval(new_question, 10000);
// Use an AJAX request to call the new_question function on the
// server
function new_question(){
$.ajax({
url: '{{ url('/new_question') }}?c=10',
success: function(response) {
// Handle the response from the server
console.log(response);
}
});
}
</script>
// to receive get value update helper function
if(!function_exists('new_question')){
function new_question() {
// Get the value of the c parameter from the query string
$c = isset($_GET['c']) ? $_GET['c'] : 0;
// Your code here...
}
}
First, you have to figure out if the number of "content" has changed. Using Laravel, create a function that is accessible through a route, this function would return the number of posts, then, using javascript, you will call that function in an interval (example is 5 seconds) and if the number has changed since the last call, then there's new posts, so you should do some DOM manipulation to update your page to alert the user.
Your server side function would be simple, something like this:
function count_questions() {
$quelist = DB::table('questions')->get();
$quecount = $quelist->count();
$response = array('quecount' => $quecount);
echo json_encode($response);
}
Then, identify how to reach this function through your routing table, and use the below jquery functions:
var quecount = 0;
$(document).ready(function() {
setInterval(function() {
$.ajax({
// change this URL to your path to the laravel function
url: 'questions/count',
type: 'GET',
dataType: 'json',
success: function(response) {
// if queuecount is 0, then set its initial value to quecount
if(quecount == 0){
quecount = response.quecount;
}
if(response.quecount > quecount){
quecount = response.quecount;
new_question_found();
}
}
});
}, 5000);
});
function new_question_found(){
$("#new_questions").html("New questions found");
}
The solution that is coming to my mind is may be too advance or too complex.
This solution need
Laravel scheduler and queue (Jobs)
and web push notification (ex : one-signal)
To reduce the traffic in the back-end you can have job to run like every 10 seconds in the back-end (Laravel scheduler and Queue).
If the question count get increased. you can call a api in the push notification and you can say there is a new question added.
the above work-flow is not explained well but this is in very simple term.
For example:
on frontend side:
const check_new_questions = function() {
const message =
fetch('http://yourserver.com/new_questions_endpoint');
if (message) {
// show message
}
};
// call each 10 seconds.
setInterval(check_new_questions, 10000);
then on backend side:
create a route new_questions_endpoint which will call your function and return result as response.
But note, that receiving all the questions from the table each time could be expensive. Eloquent enables to make a count query without retrieving all the rows.
You can't have this behaviour happen without any form of javascript.
The main way you could do this is by setting an interval via front-end like others have said. If you have any familiarity with APIs and general HTTP protocol, I would recommend you make an API route that calls your helper function; I also recommend responding with an empty body, and using the http status code to determine whether a refresh is needed: 200 for success and no refresh, 205 for success and refresh needed.
So you simply set a fetch api call on timeout, don't even need to decode the body and just use the response status to determine whether you need to run location.reload().
To achieve your requirement as per the comment you need to create an ajax request to BE from FE to check the latest question and based on that response you need to do it.
setInterval(function()
{
$.ajax({
url: "{{url('/')}}/check/questions",
type: "POST",
dataType: "json",
data: {"action": "loadlatest", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
}, 10000);//time in milliseconds
the above js code will create an ajax request to Backend, below code will get the latest question 'id'.
$latest_id = DB::table('Questions')->select('id')->order_by('created_at', 'desc')->first();
so either check it in BE and return a corresponding response to FE or return the latest id to FE and check it there.
then show the prompt to refresh or show a toast and refresh after 5 sec
Why do you use function_exists() ? I don't think it's useful in this case.
The easiest way to do what you want is to use ajax and setInterval
Front side:
const check_new_questions = function() {
const data =
fetch('http://yourserver.com/new_questions_endpoint?c=current');
if (data) {
alert(your_message);
}
};
// call each 10 seconds.
setInterval(check_new_questions, 10000);
Back side:
function new_question() {
// Get the value of the c parameter from the query string
$c = isset($_GET['c']) ? $_GET['c'] : 0;
$quelist = \DB::table('questions')->get();
$quecount = $quelist->count();
return ($quecount > $c);
}
I suggest to use c as the last id and to not count questions but just to get the last question id. If they are different, one question or more was inserted.
Attention if you use this solution ( Ajax pulling ) you'll get two requests per 10 seconds per connected users. One for the ajax call and one for for the database call. If you have 10 users a day, it's ok but not if you have 10 thousands. A better but more complex approach is to use Mercure protocol or similar ( https://mercure.rocks/ ).
I use GAPI (Google Analytics PHP Interface) to retrieve report about my site.
When I save the GAPI response in php variable I get an error.
The error I get:
Call to a member function getUsers() on array
When I run the request like this, I get the error:
//Get Total users who visited the site
$total_visitors=$this->gapi->requestReportData($this->config->item('ga_profile_id'), array('day'), array('users'), array('-day'), '', date('2008-01-01'), date('Y-m-d'), 1, 10000);
$data['total_visitors'] = $total_visitors->getUsers();
When I run the request like this, it works fine:
//Get Total users who visited the site
$this->gapi->requestReportData($this->config->item('ga_profile_id'), array('day'), array('users'), array('-day'), '', date('2008-01-01'), date('Y-m-d'), 1, 10000);
$data['total_visitors'] = $this->gapi->getUsers();
Seems like requestReportData is returning an array and not $this meaning the instance of the object that would allow you to call further methods (Like getUsers()) or manipulate the object. So either check the data in the array returned by requestReportData or you can try this if you really need to use the getUsers() method:
$this->gapi->requestReportData($this->config->item('ga_profile_id'), array('day'), array('users'), array('-day'), '', date('2008-01-01'), date('Y-m-d'), 1, 10000);
$total_visitors = $this->gapi->getUsers();
$data['total_visitors'] = $total_visitors->getUsers();
I am having an issue with Leaflet Control Search, I am testing on C9.io, using Laravel 5.2, I am trying to search a L.geojson layer but all it comes up with is "Location not Found"
and the console gives error:
"Cannot read property 'call' of undefined"
I have a global variables that holds the map, L.geojson layers, and tiles.
var map, allcalls, mapquest;
mapquest = new L.TileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {
maxZoom: 18,
subdomains: ["otile1", "otile2", "otile3", "otile4"],
});
map = new L.Map('map', {
center: new L.LatLng(39.90973623453719, -93.69140625),
zoom: 3,
layers: [mapquest]
});
var promise = $.getJSON("leaflet_php/get_users.php");
promise.then(function(data) {
allcalls = L.geoJson(data, {
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.fn + '<br>' +feature.properties.gender + '<br>' + feature.properties.addr + '<br>'+ feature.properties.city );
}
});
map.fitBounds(allcalls.getBounds(), {
padding: [20, 20]
});
allcalls.addTo(map);
});
Then I start the L.control.search, and it shows on the map but when I search I get no results the loader gif never stops and I get console error "Cannot read property 'call' of undefined"
var controlSearch = new L.Control.Search({
layer: allcalls,
position:'topleft',
propertyName: 'city',
});
map.addControl( controlSearch );
I am generating the json using https://github.com/bmcbride/PHP-Database-GeoJSON. My Json has at least 1000 features, each feature has 30 properties. So this is an abbreviated version. This is a sample of the json I get:
{"type":"FeatureCollection","features":[{"type":"Feature","geometry": {"type":"Point","coordinates":[-80.191626,26.339826]},"properties":{"id":1,"fn":"SAMUEL","mi":null,"ln":"STANTON","name_pre":"MR","addr":"9 HONEYSUCKLE DR","apt":null,"city":"AMELIA","st":"OH","zip":45102,"z4":9722,"dpc":99,"fips_cty":25,"latitude":26.339826,"longitude":-80.191626,}},
Any help is greatly appreciated. Thanks in advance.
You should instantiate L.Control.Search within your Promise callback, or at least use the setLayer() method within that callback.
It looks like you have a classic asynchronous issue: you initiate an AJAX request (through jQuery's getJSON), which will assign the value of your allcalls variable once resolved.
In parallel, you instantiate your L.Control.Search and specify allcalls as the Layer Group to be searched in. However, at that time, the AJAX is still processing (i.e. not resolved), so allcalls is still unassigned (i.e. undefined).
Therefore your Search Control knows nothing about the L.geoJson layer group that is built later on in the AJAX resolution.
I finally got my API output ready with some great help of SO-members answering all my questions. Thank you by the way.
But I wonder about one thing in my output. When I call the URL to receive the API content I get something like this:
[
{
"data": [
{
"incidentReference": "R-20150405-887f93",
"latitude": 48.259698,
"longitude": 11.434679,
"archived": false
},
(...)
]
}
]
I read the book "Build APIs you won't hate" and it is a great resource for a lot of stuff. But I don't think, the output I see is right. I mean, the namespacing is something I would like to have. But shouldn't it look like this?
{
"data": [
{
"incidentReference": "R-20150405-887f93",
"latitude": 48.259698,
"longitude": 11.434679,
"archived": false
},
(...)
]
}
So shouldn't the whole thing be JSON only? in my case it is return additionally within an Array. The functions doing the job are these:
public function index()
{
$incidents = Incident::all();
if( ! $incidents) {
return Response::json([
'error' => [
'message' => 'There are no incidents in the database.',
'code' => 100
]
], 404);
} else {
return $this->respond([
$this->respondWithCollection($incidents, new IncidentTransformer)
]);
}
}
public function respond($data, $headers = []) {
return Response::json($data, $this->getStatusCode(), $headers);
}
protected function respondWithCollection($collection, $callback) {
$resource = new Collection($collection, $callback);
$rootScope = $this->fractal->createData($resource);
return $rootScope->toArray();
}
So yes, the respondWithCollection returns an array, but this is handled within the respond function which states return Response::json So I would expect a json output when calling the resource.
Is this ok?
The next structure
{"data" : [{}, {}]}
is good when you have an extra fields, such as total count of items, number of page, etc:
{"data" : [{}, {}], "page":1, "total": 100}
Otherwise, it is really good to use simple structure:
[{"incidentReference": "R-20150405-887f93", ...}, {...}]
I'd recommend you to avoid any deep-nested structures.
RESTful responses should be as simple as possible : Output pure json data only. Therefore, limit and offset should not be included in the server response since this client already knows that information. And if you format the response, you will have to interface all device / plateform / system that wants to interact with your resful service.
Server should return extra information that client doesn't know though, such as total elements when querying a part of a collection. But I would use header for that. That way, server still returns simple json array, wich can be handled not only by your client but lots of other devices / platforms / apps.
My opinion : Output only pure json and use header for extra info, like this example :
api/incidents/index.php :
// sanitize $_GET array, then output
$total = $incidents->getTotal();
$output = json_encode($incidents->fetch($GET['LIMIT'], $_GET['OFFEST'])); // pure example, I don't know how your framework works
// output
header('HTTP/1.1 200 OK');
header('Content-Type: application/json');
header('Collection-Total: '.$total);
header('Content-Length: ' . strlen($output));
echo $output;
For example, a web app using jquery accessing this ressource would look like this :
var limit = 10;
var offset = 200;
$.ajax({
type: 'GET',
url:'http://mywebsite.com/api/incidents/',
data: {
'LIMIT': limit,
'OFFSET': offset
},
success: function(data, textStatus, request){
console.log('Incidents received...');
console.log(data);
console.log('There is ' + request.xhr.getResponseHeader('Collection-Total') + ' incidents in total');
},
});
I would avoid nested structures, like Roman said. RESTful ressources need to have their own identifier (URI). It must return an object (item) or array of objects (collection of items), like this :
api/incidents // returns an array of objects
api/incident/[id] // returns a unique object (incident), using incident id in the URI
api/incidentreference/[id] // return an unique object (incident reference), usign incident reference id in URI
This approach also leads to interesting cache possibilities since all elements (item or collections) have their own identifier (URI). Web protocols / platforms / devices may cache all server results and optimize your entire app automatically if you work with URIs.
I would also recommend that your service return a 200 OK responses even if there is no elements to output. 404 says that the ressource is not found. The ressource is found, but contains no elements now. It may contains elements later. A 404 HTTP code may be handled differently by some device / broswers / platform. I am possibily wrong with that, but my REST services always return 200 OK / empty json arrays and I never has problems. Accessing a ressource (url) that doesn't exists will return 404 though.
I'm trying to get geolocation from tweets.
For my tests, I posted new tweets geo-referenced but when I got the json of them, the element 'geo' is null. Why? What's wrong with them?
I don't want to search by range and geolocation: I want to search some tweets indexed by a particular hashtag and then retrieve 'geo' json element.
I tried to search other tweets (not mine) and sometimes I got 'geo' element as a full object, with coordinates array.
So, what can I do to have 'geo' element not null?
I did 4 posts geo-referenced: my tweets
The location is: 44.694704,10.528611
Edit: Added geocode param
This is what I've done server-side (pure php):
$conn = new OAuth (CONSUMER_KEY, CONSUMER_SECRET);
$conn->setToken (ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$conn->fetch (API_URL, array ('q' => '#testhashtagandgeo', 'geocode' => '44.694704,10.528611,4km'));
echo $conn->getLastResponse ();
I used PHP OAuth base and each constant is defined correctly, so it works good.
Client-side (ExtJS):
Ext.onReady (function () {
Ext.Ajax.request ({
url: 'proxy.php' ,
disableCaching: false ,
success: function (xhr) {
var js = Ext.JSON.decode (xhr.responseText);
Ext.each (js.results, function (tweet) {
if (tweet.geo !== null) {
console.log ('lat = ' + tweet.geo.coordinates[0] + ' - lng = ' + tweet.geo.coordinates[1]);
}
});
console.log (js);
} ,
failure: function (xhr) {
console.log ('something\'s wrong!');
}
});
});
Thanks in advance.
Wilk
You need to read the documentation
Location data is only included if the query includes the geocode parameter, and the user Tweeted with Geo information.
So, you need to add something like this to your query
&geocode=37.781157,-122.398720,25mi
Or whichever location you want.