stay connected with twilio call on page refresh - php

i need help to stay connected with the call during conversation. i have used the following code given on twilio Doc.
PHP Part is here
$token = new Services_Twilio_Capability(TW_ID, TW_TOKEN);
$token->allowClientIncoming($_SESSION['emp_id']);
JS Part:
Twilio.Device.setup("<?php echo $token->generateToken();?>");
$("#call").click(function() {
params = { "tocall" : $('#tocall').val()};
connection = Twilio.Device.connect(params);
});
$("#hangup").click(function() {
Twilio.Device.disconnectAll();
});
Twilio.Device.ready(function (device) {
$('#status').text('Ready');
console.log(Twilio.Device.status());
});
Twilio.Device.incoming(function (conn) {
startCall(conn);
});
on the page load the the Twilio.Device.ready() function make the user login the receive the calls, but the the user refresh the page the call went disconnected, or if user trying to do something like updating the information of client during the conversation getting the call disconnected. Hope you understand.
But now don't have any idea that how to rid this issue. One option i have to use the hash value on the url something like #status.
Please help me to give any alternate solution or modifying this code..

You can use the session for this...
store the token value in the session.
$_SESSION['token']=$your_token;
access like this
<?php echo $_SESSION['token'];?>

There are a few different options you could take.
Store the call state on the server, via a POST request to your server when the call connects. Then when the client refreshes the page, push an incoming (the existing) call to the client.
Use HTML5 localStorage or similar to store the call state on the client. Your JS should check for existence of a call in localStorage when the page loads. If a call exists in this DB, then connect to the same endpoints as before.

Related

Twilio: Receive multiple incoming calls on the same Twilio number in the browser at the same time

I have implemented Twilio Client for the in-browser calls using PHP/Laravel and Twilio Client JS SDK. The implementation is working fine I can make the call from the browser and can even receive a call in the browser.
Now, I want to show calls coming in, at the same time while I'm in call with some another customer in the browser and then I can handle them whether I want to accept that call or not If I answer that then the in-progress customer should go on hold and I can talk with another customer, exactly the same way we do it in our cellphones.
The scenario is this, I'm in call with some customer on the line, Now at the same point of time another customer is calling on the same Twilio number, So, now I should get the notification/popup to answer that call, reject, and hold, etc.
So if anybody can help me with proper code/example it would be really appreciated.
P.S: I went through the concept of Enqueue in Twilio but couldn't understand how to implement it.
Thanks in advance.
As from the official docs Twilio.Device.incoming get call when you receive an incoming call, as callback you get a connection, call conn.accept() method to start audio streaming, Add a global variable to check if already call is already ongoing
var isOngoing = false; // Global variable
Twilio.Device.incoming(function(conn) {
console.log('Incoming connection from ' + conn.parameters.From);
// accept the incoming connection only if you are not on another call.
if(!isOngoing) {
isOngoing = true;
conn.accept();
} else {
// Add you other implementation for displaying your popup or a message box.
conn.reject();
}
});
/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
isOngoing = false
});
On terminating call now you need to reset isOngoing variable to false so that you can receive another call.

How to check remote server for status

I'm looking for something.
The problem is that I want to make my app do more locally and less remote.
It needs to put a parameter in every request (or websession id)
I tried the following
$.getJSON('http://*******************.com/loginapi.php?uuid=0x1a2b3c4e', function(jd) {
var reg = jd.usrreg;
var uuid = jd.usrpin;
var usrid = jd.usrid;
});
});
That does nothing, on the server side I don't even see a request to that page.
document.write(uuid) does not give anything back, when I go in my browser to the requested page I see the following:
{"usrreg":"0","usrpin":"0x1a2b3c4e","usrid":"0"}
I also tried with form data, so when I press login it sends a request to the server, but I should still get something back like usrreg=0 or 1, because it means the person is not registered, or usrreg=2 for wrong user/pass.
How can I read the value that I get when I open the page?
Cross Domain Request with Ajax are fobidden cause of Same Origin Policy: http://en.wikipedia.org/wiki/Same_origin_policy
So what are you alternatives?
Learn to use AJAX with JSONP - will only work if the other side provides it
Write a PHP bridge running locally that provides the remote data for you
Use postMessage: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

ExtJS: How to store a user's login information only once?

I'm using Ext.Ajax.request() to hit a PHP page that gives me some user specific info as a part of a login process. Basically I want to store some variables (cookie, session information, etc) in ExtJS. I created a model with the needed fields and a store to keep it. Even though the authentication is done only once I want to ensure that on a given time there is only one copy of the user's info. I want to use that info to hit PHP again without having to authenticate again (cookies).
Here's how I fetch it and store it:
Ext.Ajax.request({
url: 'api/get.php',
params: {
user : usr,
pass : pass
},
success: function(response)
{
var text = response.responseText;
var jtext = Ext.JSON.decode(text);
var login = jtext.loginData;
model.set('username', login.username);
model.set('cookie', login.cookie);
model.set('password', login.password); // doing this feels soo wrong!
store.insert(0, model);
store.sync();
console.log(store.getCount());
}
});
What is the better way of doing it? Since I'm using an external (to the PHP) service currently I only check if the user/pass is correct and if it is, I pass it from the client-side to the PHP functions that do whatever they have to do with the external service, authenticating each time with them. Alternatively I can pass the cookie each time to the PHP that in turn passes it down. I can also map JS<->PHP cookies to PHP<->service cookies and that would be even better.
Cheers!
Ext.util.Cookies.set('myObj',Ext.encode(obj))
Use something like this and when you want to use it
id = (Ext.decode(Ext.util.Cookies.get('myObj'))).id

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

Displaying POST Data with jQuery?

I'm using a flash webcam to take a picture. It works great and spits back a URL via POST.
I'm coding in PHP and would like to display this POST data once it is recieved, the problem is that I dont re-load the page.
I've looked around and I'm not sure to dynamically load this array of data.
Where should I be looking? jQuery?
Ah, Figured it out. The Flash thing I have has a built in callback function, so I just have to append the data from there!
jQuery is not able to read any sort of request data other than that which appears in the URL (GET). You will need to use PHP (or some other server-side language) to handle the response created by the FLash application.
Due to the fact that you're using Flash for the process you are at somewhat of a disadvantage because unless the Flash application has some sort of JavaScript "PhotoUploaded" event notification, your page won't be notified that Flash has just submitted a picture to your server which needs to be retrieved and inserted. If you can modify the Flash application to make an external JavaScript event then you can proceed as Frankie has described in his answer; otherwise, if modifying the Flash application is not an option, then another solution would be to have your page send a request to the server every so often (5-10 seconds or so maybe), to check if there is a photo for it to display yet.
The simplest way to setup polling with your server in this fashion would be to make sure that each photo upload from Flash has a unique, pre-determined identifier that your page knows at initial load. You would then simply ping your server every few seconds with an AJAX request and pass it that unique identifier in order to find the right image should one exist.
Basic example:
function GetPhoto() {
$.get('/getphoto.php?ID=1541XJ55A6', function(response) {
if(response.ImageUrl !== "") {
$(".profile-image").attr("src", response.ImageUrl);
if(getPhotoTimer !== undefined) {
clearInterval(getPhotoTimer);
}
}
});
}
$(document).ready(function() {
var getPhotoTimer = setInterval("GetPhoto()", 10000); // every 10 seconds
});
Flash calls javascript each time it spits back the URL.
Javascript contacts server (php) and gets content
Javascript injects content onto page
Like this (flex code):
// attach a function to the completeHandler
private function completeHandler(evt:Event):void {
javascriptComplete();
}
// declare the function that will call the javascript function
private function javascriptComplete():void {
var javascriptFunction:String = "galeryUploadComplete("+Application.application.parameters.opt+")";
ExternalInterface.call(javascriptFunction);
}

Categories