Real time notification using angularjs php mysql - php

I would like to implement a real time notification like facebook on my website using angular, php and mysql. Is there any reference links or tutorials anyone can help me out with?
Also, is there any other tools by which I can implement the same on my website?

Try to use Socket.io, it will help you to implement notification , chat or any real time application.

You can use these things to make such functionalities.
PHP JSON Based API
PHP Socket Based JSON API
Socket IO based API
All these API can easily be parsed by AngularJS or jQuery
For PHP, How to make an API
<?php
//Set header for Javascript to recognize it as the JSON output
header('Content-Type:application/json;');
//I am using GET parameters, but POST can also be used and can make amazing APIs
switch($_GET['action']){
case "addlike":
//SQL Query passed to add a like as facebook
//Set the output array to provide json Output, here's the example
$output['status'] = 200;
$output['message'] = 'Like Added';
break;
case "addcomment":
break;
}
echo json_encode($output);
To use above code, the URL would be:
http://yourserve/youfile.php/?action=addlike
And the Output would be
{
"status":200,
"message":"Like Added"
}
How to use it in jQuery
/** For Example you have like button with class="btnlike" **/
$('.btnlike').on('click',function(){
$.get('http://yourserve/youfile.php',{action:'addlike'},function(data){
if(data['status'] == 200){ alert('You Liked the Post'); }
});
});
How to use in AngularJS
app.controller('myCtrl',function($scope,$http){
$scope.message = '';
$scope.addlike = function(){
$http.get('http://yourserve/youfile.php',{action:"addlike"}).success(function(data){
if(data['status']==200){ $scope.messages = 'You liked the post'; }
});
};
});

Related

Securing a PHP Web service (SOAP)

I have a PHP web service that actually helps the CMS to carry out some updations to the database. I've been trying to search for a solution on Internet but haven't got my answer yet.
Is there any way to check if the user making request to the webservice is authorized to do so i.e. check the user session?
Here is my dummy service (services.php)
<?php
function GetMyUserName($i)
{
return "admin101";
}
$server = new SoapServer(null,array('uri' => ROOT."includes/services.php"));
$server->addFunction('GetMyUserName');
$server->handle();
?>
Here is the JavaScript (jQuery) for consuming the service [uses a SOAP envelop]
function GetMyUName() {
var req1 = "";
req1 += '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">\n';
req1 += '<soap:Body xmlns:m="includes/services.php">\n';
req1 += "<m:GetMyUserName>\n";
req1 += "</m:GetMyUserName>\n";
req1 += "</soap:Body>\n";
req1 += "</soap:Envelope>";
$.ajax({
url: "includes/services.php",
type: "POST",
data: req1,
cache: false
}).done(function (data) {
$("#UsernameTb").html($(data).find("return").text());
});
}
Is there any thing like the one we have in ASP's WCF to allow Sessions in the webservice.
I am using UserCake for authentication if this info is somewhat helpful.
Overview
Frankly UserCake looks like it was written almost a decade ago. Just look at login.php from UserCake, it calls die() uses header("Location: account.php") to redirect the client and echos HTML.
None of these things lend themselves to a service paradigm. Most importantly UserCake's reliance on redirects will make it practically impossible to leverage behind a SOAP or REST interface without substantial modifications. Just look at the securePage function...
//Check if a user has access to a page
function securePage($uri){
// earlier code omitted for readability here...
elseif(!isUserLoggedIn())
{
header("Location: login.php");
return false;
}
// ...
}
Services typically don't redirect. They return formatted response payloads (eg JSON or XML) and may use HTTP codes to indicate what the result of the service inquiry was. There are exceptions like OAuth, but that's entirely unrelated to the problem at hand.
I'd recommend selecting a proper framework, Code Igniter if you want something simple, Symfony if you want something robust. Both are fully capable of supporting pure HTML pages, API requests and authentication / authorization. But if it must be UserCake...
Beating UserCake into submission
A quick search tells us Javascript must follow the redirect. The client would need to determine if the response is HTML or JSON, then handle accordingly. Code lifted from this answer and this one illustrates how this might be done with jQuery.
$.ajax({
type: "POST",
url: "services.php",
data: {action: 'someSecuredAction', data: 'some data for the command'},
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
// If data looks like HTML, this is some page from UserCake
// likely served by a redirect, just display it
var newDoc = document.open("text/html", "replace");
newDoc.write(response);
newDoc.close();
}
if (ct.indexOf('json') > -1) {
// If data looks like JSON we have a
// successful 'service' response from the server
}
}
});
In theory the browser will pass along any relevant cookies with the request, so the session should be available on the server. Feel free to correct me on this, but from reading around it sounds like the session cookie will be passed over the AJAX request.
Then your example 'service' (services.php) file could become something like this (the switch is just some contrived thing to give you an idea how to access the data from the request)
// If this ends up redirecting,
// the client should just pass it on through
securePage($_SERVER['PHP_SELF']);
switch($_POST['action']) {
case 'someSecuredAction':
// Again, if this redirects the client should be able to cope...
$loggedInUser->checkPermission(['someSecuredAction']);
// Do secured stuff here
$aResponse = someSecureAction($_POST['data']);
break;
}
// Now be nice enough to return the response as JSON
// like we might expect from an actual service
header('Content-Type: application/json;');
echo json_encode($aResponse);

Send data to website through widget on blog

I am looking to create a widget/plugin that can send across a simple variable when clicked. The idea is that when this widget is added to a blog, and clicked by one of its readers, it sends a message across to my domain (for example, www.example.com) with the url of the blog in question (Which can then be used to increment a count or something, for example).
I'm very new to widgets/plugins, so I am not entirely sure if this is possible. I am not looking to be spoonfed with code, just a few pointers in the right direction would be of immense help.
Forgive me, I am yet to try anything as I am unsure of where to start. Please let me know if I need to give any more information, if my tags are incorrect, or if my question is unclear!
Most distributable widget would have following aspects :
Widget Script (Controlled by you) and included by end user in their site.
Something like <script src="http://example.com/yourAwesomeScript.php"></script> where example.com is your site or cdn.
Widget Container (Embedded by the end user) to tell the script where to inject the widget code. If your widget is not position container dependent (for eg. fixed/absolute elements) this can be skipped.
You can use Javascript library such as jQuery to make your life easier to code in Javascript.
I have below very basic widget to subscribe. I am using PHP to output Javascript this will allow your widget to send dynamic data. You can also pass params to your script like
http://example.com/yourAwesomeScript.php?user_key=1234564789
end-user.html
Head
<script src="http://example.com/yourAwesomeScript.php"></script>
Body
<div id="widgetCont"></div>
yourAwesomeScript.php
<?php
if($_POST){
if($_POST['email']){
$new_subscribed = true ; //check and add to database and return if subscribed
if($new_subscribed){
echo "You have successfully subscribed";
}else{
echo "You are already subscribed";
}
}
}else{
?>
$(document).ready(function(){
$input = $('<input/>').prop("type","text").prop("id","widget_email");
$submit = $('<input/>').prop("type","button").prop("value","Subscribe").prop("id","submit_email");
$('#widgetCont').html($input,$submit);
$('#widgetCont #submit_email').click(function(){
$.ajax({
url : "http://example.com/yourAwesomeScript.php",
method : "post",
data : {email:$("#widget_email").val()},
success :function(data){
alert(data);
}
})
});
});
<?php
}
?>
I hope this helps.
In PHP you can use cURL to activate code on another domain. You can set GET or POST variables in cURL that will be sent to that page. These can then be manipulated in PHP via the $_GET and the $_POST arrays.
example of cURL:
http://php.net/manual/en/curl.examples-basic.php
You should try to set up a HTTP service on your domain and then create a widget which perform POST requests against your HTTP service.
A good function for this would be cURL in PHP.
Client URL Library
Here is a small guide of how to use cURL
cURL guide

Adding a database to jquery mobile site

I'm pretty new to using jquery and jquery mobile, but I was wondering if there was a simple way (or tutorial preferably) to tie a database (remote and local) to a jquery mobile site (preferably not using php).
You can use HTML5 localStorage via JavaScript, here is an explanation and some links to tutorials: http://www.html5rocks.com/en/features/storage
...there are now several technologies allowing the app to save data on
the client device...
If you want to interact with your server then you're going to need to use a server-side scripting language. It's fairly easy to use AJAX to communicate with your server:
JS--
//run the following code whenever a new pseudo-page is created
$(document).delegate('[data-role="page"]', 'pagecreate', function () {
//cache this page for later use (inside the AJAX function)
var $this = $(this);
//make an AJAX call to your PHP script
$.getJSON('path_to/server/script.php', function (response) {
//create a variable to hold the parsed output from the server
var output = [];
//if the PHP script returned a success
if (response.status == 'success') {
//iterate through the response rows
for (var key in response.items) {
//add each response row to the output variable
output.push('<li>' + response.items[key] + '</li>');
}
//if the PHP script returned an error
} else {
//output an error message
output.push('<li>No Data Found</li>');
}
//append the output to the `data-role="content"` div on this page as a listview and trigger the `create` event on its parent to style the listview
$this.children('[data-role="content"]').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create');
});
});
PHP--
<?php
//include your database connection code
include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELCT * FROM fake_table WHERE fake_col='fake value'", $db) or trigger_error(mysql_error());
//create an output array
$output = array();
//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {
//iterate through the results of your query
while ($row = mysql_fetch_assoc($query)) {
//add the results of your query to the output variable
$output[] = $row;
}
//send your output to the browser encoded in the JSON format
echo json_encode(array('status' => 'success', 'items' => $output));
} else {
//if no records were found in the database then output an error message encoded in the JSON format
echo json_encode(array('status' => 'error', 'items' => $output));
}
?>
You can also send data to your PHP script and have it added to a database.
Here are some documentation pages for functions used above:
jQuery .getJSON(): http://api.jquery.com/jquery.getjson
PHP json_encode(): http://www.php.net/json_encode
use http://westcoastlogic.com/lawnchair/ It offers many ways of storage and you can actually put all the adapters (options of how to store) in order so that it will pick up the first one which is available on the browser.
Also it using JSON format no matter whether u want to use localstorage or sqlite, so u'll only have to deal with JSON data.
If you want a database there is widespread support for SQLLite inside the mobile browser in the form of Web SQL Databases, which is currently supported in most android and iPhone devices.
To see a working example check the following link:
http://desalasworks.com/html5-databases-on-iphone/
Note that the SQL language available in SQLLite is more limited than (what I assume is) your MySQL database. You can create/drop tables, select, insert and update, but some of the more advanced operations will be missing.

Using javascript to get php/mysql values

i am thinking of building an android app in appcellerators titanium application, and i have a question, the website which the app is for is built using php/mysql, and what i am wondering is, as titanium works using javascript, html and css only, is there a way i can pull the data dynamically from my database using javascript?
if this has already been posted I'm sorry i searched and couldnt find it :S
With PHP, take your database response array and encode it like this:
<?php
json_encode($db_array);
?>
More information:
http://php.net/manual/en/function.json-encode.php
Note that you'll need PHP 5.2 or above in order to have the built in JSON functions for PHP.
In Titanium, you want to open a XHR (or network handler) to grab the data:
var xhr = Ti.Network.createHTTPClient();
var.onload = function()
{
try
{
data = JSON.parse(this.responseText);
}
catch (excp)
{
alert('JSON parse failed');
}
// you should handle your network async, meaning you should handle any renders or any post elements here. if you make it sync, you'll cause all other handlers and functions to work improperly (like click events, etc).
}
xhr.open("GET", "your url here");
xhr.send();
You can access the the data array by simply calling data[0].some_col;
Try reading tutorial about using SQLite databases in Titanium applications
I'm sorry it's for iPhone, but in basics the principle is the same
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite/
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-part-2/
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-%E2%80%93-part-3/
using is like this:
var db = Ti.Database.install('../products.sqlite','products');
var rows = db.execute('SELECT DISTINCT category FROM products');
Documentation:
http://developer.appcelerator.com/apidoc/mobile/1.3/Titanium.Database-module
The best way would be to use JSON using json_encode if you were accessing the database from the website. If you were trying to use a local database then use sqlite.
You need to build an webservice on your website, and pull the data in with Titanium.Network.HTTPClient
You can see it here: http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.Network.HTTPClient-object
An example would be:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
var data = this.responseText; //response is here
// do your thing within this scope, or call a function/event from here
}
var url = 'http://www.google.nl';
xhr.open("GET", url); // or "POST"
xhr.send();
Note that the data variable is not accessable outside the scope, even if it is a global. Call your function from within the scope
In the app you could either use SQLite, or don't store the data. Whatever suits your application best

What is a good RPC model for building a AJAX web app using PHP & JS?

I'm new to writing AJAX applications. I plan on using jQuery on the client side while PHP on the server side. I want to use something like XML-RPC to simplify my effort in calling server-side code. Ideally, I wouldn't care whether the transport layer uses XML or JSON or a format more optimized for the wire.
If I was writing a console app I'd use some tool to generate function stubs which I would then implement on the RPC server while the client would natively call into those stubs. This provides a clean separation. Is there something similar available in the AJAX world?
While on this topic, how would I proceed with session management? I would want it to be as transparent as possible. For example, if I try to hit an RPC end-point which needs a valid session, it should reject the request if the client doesn't pass a valid session cookie.
This would really ease my application development. I'd then have to simply handle the frontend using native JS functions. While on the backend, I can simply implement the RPC functions.
BTW I dont wish to use Google Web Toolkit. My app wont be extremely heavy on AJAX.
This is my typical solution, so YMMV.
For the PHP end, I break my various remote functions into individual files (e.g. 'add_user.php', 'login.php', 'do_something.php'), each of which sets response data into a pre-defined array named 'response', and include the files dynamically based on the action requested, such as:
switch ($_POST['action']) {
case 'addUser':
require 'add_user.php';
break;
case 'login':
require 'login.php';
break;
// ... snip ...
default:
$response['result'] = 'badaction';
break;
}
echo json_encode($response);
Each individual file is designed to parse an HTTP POST request, do something with it, and return a JSON response (this gives both sides a fairly simple time parsing results, since PHP will automatically prepare the POST values for you, and jQuery can automatically convert a JSON response into an object, though I recommend picking up the JSON2 library from json.org so you don't have to worry about eval() issues), and they look something like this:
<?php
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
die; // prevent the file from being accessed directly
}
// the do {} while(0); block allows us to set the response and then short-circuit
// execution without using a big ugly nest of if/else statements or a function
do {
if (!isset($_POST['something'],$_POST['parameter'],$_POST['whatever'])) {
$response['result'] = 'badinfo';
continue;
}
// ... snip ...
} while(0);
Given jQuery's fairly simple AJAX request methods, the JS shouldn't be too hard to figure out. One nice thing about this method is that, should you need the response to be in some other format (XML, URLEncoded, etc), it's a snap; personally, I add a 'format' parameter to the request and parse it like so:
// EXPLICIT FORMAT
$format = strtolower(isset($_REQUEST['format']) ? $_REQUEST['format'] : null);
// IMPLICIT FORMAT
if (!$format) {
if (isset($_SERVER) && is_array($_SERVER) && array_key_exists('HTTP_ACCEPT',$_SERVER)) {
$accept = $_SERVER['HTTP_ACCEPT'];
if (stripos($accept, 'application/json') !== false || stripos($accept, 'text/javascript') !== false) {
$format = 'json';
}
}
if (!$format) {
$format = 'url';
}
}
switch ($format) {
case 'json':
echo json_encode($response);
break;
case 'url':
default:
echo http_build_query($response);
break;
}
Hope this helps, reply in comments with any questions and I will hopefully shed some more light on the situation.
I wouldn't use XML-RPC. There's no need. Send either HTTP query parameters (GET or POST) to the server or possibly a JSON object and get JSON or HTML in response. PHP has methods for encoding and decoding JSON: json_encode() and json_decode().
for example phpxmlrpc
together with standard session stuff

Categories