I am using the Twilio API for making calls/texting. A user initiates a call on a Single Page Application (with PHP/Symfony 5). I would like to display the status of the call in real time (in progress, finished, ect... via StatusCallbackEvent) as well as the digits once the call is finished.
The application works as follows:
The user initiates a call on the app (with a onClick event)
AJAX request to my controller
The controller makes the call
the API returns StatusCallBack data on another URL linked to another controller
How can I retrieve the data from the API in my AJAX request to display the result to the user ? Knowing that this is a Single Page App...
CallbackStatus goes here:
/**
* #Route("/back/", name="app_back")
*/
public function back (Request $request) : Response
{
// some stuff...
$voiceResponse = new VoiceResponse ();
$response = new Response (
$voiceResponse->asXML(),
Response::HTTP_OK,
['content-type' => 'application/xml']
);
return $response;
}
I want to transfer it here:
$.post({
url : "/makecall/",
data: {
"people" : idPeople
},
dataType : 'json',
success: function (data) {
// Display data here :(
}
});
I hope to have been clear. Thank you for your attention.
Related
I am doing Google Oauth login using Google Api's in Laravel 5.0. I get the data of currently logged in user's email,id_token and now I want to send these data to the controller(SigninController) for calling our own api and get the response back to the front end (signin.blade.php) via an Ajax query . But My Ajax query is not working. I am attaching the codes here .
My Signin.blade.php file's ajax looks like(I have included csrf header) :
$.ajax({
url: '/signin/oauth',
type:"POST",
data: data,
headers: { 'X-CSRF-Token' : token},
success:function(data){
console.log(data);
if(data){
console.log("Success nowwww for ajax expected data!");
// window.location.href = '{{url("/home")}}';
}
else{
console.log("Success ajax ! But not expected data!");
// window.location.href = '{{url("/signup")}}';
}
},error:function(){
alert("error!! ajax failure !!!!");
}
});
My routes.php looks like :
Route::post('/signin/oauth', [
'uses' => 'SigninController#signinProcessOauth',
'as' => 'post_signin_oauth',
]);
In my SigninController's signinProcessOauth function normal "Request for Form" is working but "Request->ajax()" maybe not working . It looks like :
.
.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
.
.
public function signinProcessOauth(Request $request)
{
$getData = $request->ajax();
if ($getData) {
$authCode = $request['authCode'];
$idToken = $request['idToken'];
$userEmail = $request['userEmail'];
// call the api here and send the above data to the server and process the response like saving the cookie etc
return $authCode; // return according to the response,this will return in ajax success function,right now it is authcode just for testing purpose
}
return "error";
}
Everytime I run the code, I get "error!! ajax failure !!!!" response i.e. ajax's failure function is called . I can't figure it out Where the problem is? Or Is there any other way to to send the datam from view to controller and get back the response to the frontend ?
Thank you for reading such long post patiently . :) :)
Change your url as follow:
url: '{!! route('post_signin_oauth') !!}'
Hope this will work.
In your method $request is not an array, its an object. So you need to use -> to access properties.
I am using a jQuery library called MockAjax which allows you to mock/test real AJAX calls.
In my application I can use my live app version of an AJAX request and MockAjax will intercept the AJAX request and respond with a Mock response!
I am also using another library called M<ockJson which is similar but instead allows you to generate a Mock JSON response.
Using both libraries together, my Application makes an AJAX request. MockAjax catches the AJAX request and then MockJson generates and returns a random JSON response.
In my past projects this has worked great with no issues until today...
Now that my application is working pretty good, I decided it;s time to restructure the JavaScript into a more structured version. (putting DOM events, tasks, etc into sections of code).
This is where my problem began....
In my new code,
my App makes an AJAX request.
MockAjax catches the AJAX request.
MockJson is called to get the JSON response
ERRORS this is where it all goes wrong...
At this last step, it should pass the JSON response back to the original AJAX calls Success function. It simply does not!
I get no errors or anything in the console. I set up a simple alert() in my AJAX calls success() function and it does not make it that far to even trigger the alert!
I am not sure if there is some sort of scope issue or what the problem could be. When my app was flat, all variables and functions in the glbal root level with no structure to the app at all...it all worked. As soon as I moved everything into Objects, etc....it all works except this 1 issue of not returning the MockAjax response back to the Real Ajax response!
I removed 95% of the app code and re-built it with just the very minimal to run this example problem. The demo of the problem is here... http://jsbin.com/vugeki/1/edit?js
App flow:
projectTaskModal.init(); is ran on page load
This fires off projectTaskModal.mockAjax.init(); which sets up the MockAjax and MockJson code
Then projectTaskModal.task.openTaskModal(projectTaskModal.cache.taskId); is ran which executes the AJAX request
AJAX POST Request is sent to /gettaskevents
MockAjax catches the request sent to /gettaskevents
MockAjax then calls MockJson to generate the JSON response. projectTaskModal.mockAjax.generateTaskEventsJson(); calls that function and I have it printing the JSON respionse into the console so I can see that it is generating it!
In my MockAjax code, var taskevents holds the JSON response and then set it to this... this.responseText = taskevents; ``this.responseTextI believe is what is supposed to be returned to the Applications originalAJAX` call. It seems that this is where the problem might be! It does not seem to be returning the response back to the original AJAX code that requested it in the first place!
Could this be some sort of scope issue?
var projectTaskModal = {
cache: {
taskId: 1,
projectId: '12345',
},
init: function() {
projectTaskModal.mockAjax.init();
//console.log(projectTaskModal.mockAjax.init.generateTaskEventsJson());
projectTaskModal.task.openTaskModal(projectTaskModal.cache.taskId);
},
task: {
openTaskModal: function(taskId) {
// Load Task Events/Comments Panel from AJAX Request
projectTaskModal.task.loadTaskEventsPanel(taskId);
},
/**
* Load Task Events/Comments from backend Database JSON
* #param {string} jsonServerEndpoint URL for AJAX to Request
* #return {string} Generated HTML of all Task Events built from JSON
*/
loadTaskEventsPanel: function(taskId) {
// Request Task Events and Comments using AJAX Request to Server
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/gettaskevents',
data: {
action: 'load-task-events',
task_id: projectTaskModal.cache.taskId
},
success: function(data) {
alert('TESTING AJAX SUCCESS CALLBACK WAS CALLED!');
console.log('function loadTaskEventsPanel(taskId) DATA: ');
console.log(data);
// Parse JSON data
var taskEventsJson = data;
var task_events = taskEventsJson.task_events;
// Loop over each Task Event record returned
$.each(task_events, function(i, event) {
console.log('commentID: ' + event.commentId);
console.log('create_at DateTime: ' + event.created_at);
});
}
});
},
},
mockAjax: {
init: function(){
// Adding the #EVENT_TYPE keyword for MockJSON Template Usage
$.mockJSON.data.EVENT_TYPE = [
'Comment Created',
'Task Status Changed',
'Task Completed'
];
// Mock AJAX response for AJAX request to /gettaskevents
$.mockjax({
url: '/gettaskevents',
contentType: 'text/json',
responseTime: 2900, // Simulate a network latency of 750ms
response: function(settings) {
console.log('mockJax POST to /gettaskevents :');
//console.log(settings);
//DEBUG('Get Task Events JSON', settings.data);
if(settings.data.value == 'err') {
alert('MockAjax Error');
this.status = 500;
this.responseText = 'Validation error!';
} else {
alert('MockAjax Success');
//var taskevents = generateTaskEventsJson();
var taskevents = projectTaskModal.mockAjax.generateTaskEventsJson();
this.responseText = taskevents;
console.log(taskevents);
}
}
});
},
// Generate Mock JSON Response to load fake Task Evewnt/Comments JSON for Mock AJAX request
//var generateTaskEventsJson = function () {
generateTaskEventsJson: function() {
var mockTaskJson = $.mockJSON.generateFromTemplate({
"task_events|10-14" : [{
"commentId|+1" : 100000000,
"projectId|+1" : 100000000,
"taskId|+1" : 100000000,
"userId|+1" : 100000000,
"created_at" : "#DATE_YYYY-#DATE_MM-#DATE_DD",
"event_type" : "#EVENT_TYPE",
"userName" : "#MALE_FIRST_NAME #LAST_NAME",
"description" : "#LOREM_IPSUM #LOREM_IPSUM"
}]
});
//DEBUG('Generate Mock Task Events JSON', mockTaskJson.task_events);
//console.log(mockTaskJson.task_events);
//return mockTaskJson.task_events;
return mockTaskJson;
}
},
};
$(function() {
projectTaskModal.init();
});
Your JSBin example shows that you are using a very old version of Mockjax (1.5.0-pre). The latest is 1.6.2, released quite recently (I'm the core maintainer now). Below is a link to an updated JSBin where everything appears to be working just fine. The old version of Mockjax that you were running was created before jQuery 2.0 existed, and thus does not support it (1.6.2 does).
http://jsbin.com/qucudeleve/1/
So... update your Mockjax version to use Bower, npm, or just Rawgit (https://rawgit.com/jakerella/jquery-mockjax/master/jquery.mockjax.js) from the primary account (mine) versus your own fork which is extremely out of date!
Good luck.
I'm about to implement a Login using Google OAuth. I followed the official Google docs
The client does get a token from the Google server. But whenever I try to send it back to my server to store it, I do not seem to get data from the AJAX call. Here is my code:
function signInCallback(authResult) { //called when client has confirmed the Login dialog
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
console.log("signinCallback. Send code to server:")
console.log("Code = "+ authResult['code']);
console.log("performing AJAX call now...\n\n")
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://localhost:9000/storeauthcode',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
console.log("AJAX call --> success");
console.log(result)
},
processData: false,
data: authResult['code']
});
} else {
//There was an error.
console.log("AJAX call failed.")
}
I created a line in my routes file:
POST /storeauthcode controllers.Application.storeAuthCode
The method on the server:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.rawQueryString)
}
The following is a console output of my Chrome browser:
hello.js:2 Welcome to your Play application's JavaScript!
(index):67 signinCallback. Send code to server:
(index):68 Code = <token deleted for privacy reasons>
(index):69 performing AJAX call now...
(index):77 AJAX call --> success
(index):78 storeauthcode called with queryString =
So although my browser gets a token back, I cannot store it on the server, because I don't get any data back.
Ok("storeauthcode called with queryString = "+request.body.asJson)
is also empty.
This one here also delivers an empty result:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.getQueryString("data"))
}
I have gone through the introduction part at Rx CodePlex page. I have watched the video of the guy with CascadiaJS. I have discovered how the RxJS library is used. I have a question about how is it going to help me with my existing Ajax application and what do I have to change on server side as well as client-side to make the most of RxJS.
Scenario
I have a REST service written using ASP.NET Web API. The service currently has one method, it takes an array of coordinates and return another array of coordinates. So the call is very simple, it goes like this.
$.ajax({
url: "http://www.myservice.com/service1/",
type: "POST",
data: JSON.stringify(params),
contentType: "application/json;charset=utf-8",
success: handle_success,
error: handle_failure,
OPTIONS: null,
});
Now the above call simply calls a REST service and takes appropriate action on how the results come out.
With Rx, I heard the mantra of "Push" instead of Pull. How are we going to fit "Push" into the sample above ? Am I going to change my REST service to be a Listening TCP Socket which my webpage will stay connected (or make a Keep-Alive connection) and new values will be "Pushed". Or this would just be a service call as above, but the success/error will just be "channeled" through Observable and once the call is finished, the job of that Observable is finished ?
Even without worrying about changing your server to push to the client, RxJs can help you compose your asynchronous actions on the client.
For example, if you model your ajax call as an observable:
// each time you subscribe to service, it will execute the ajax call and send back the result
var service = Rx.Observable.defer(function () {
return $.ajax({
url: "http://www.myservice.com/service1/",
type: "POST",
data: JSON.stringify(params),
contentType: "application/json;charset=utf-8"
});
});
// Now fun with Rx
// just call the service like in your OP example:
service.subscribe(handle_success, handle_failure);
// poll the service every 5 seconds
var pollInterval = Rx.Observable.empty().delay(5000);
service
.concat(pollInterval)
.repeat()
.subscribe(success, failure);
// run the service whenever user clicks Refresh
$('#refresh')
.onAsObservable('click')
.flatMap(function () { return service; })
.subscribe(success, failure);
// same as above, but ignore it when user clicks too fast (e.g. faster than 1 second)
$("#refresh")
.onAsObservable('click')
.debounce(1000)
.flatMap(function () { return service; })
.subscribe(success, failure);
How to be confirmed whether a backbonejs .save() is sending PUT request ?? I checked my server side, which is working good, there is no problem in server side. But my .save() is not working.
Here is my model of backbone
define(['underscore','backbone'],function(_,Backbone)
{
var my_model = Backbone.Model.extend(
{
urlRoot: "http://localhost/back/server_file.php/number"
});
return my_model;
});
Here is how I am using .save()
var my_data = {
id: data.id,
code: data.code
};
var My_model = new my_model();
My_model.save(my_data,
{
success: function(response)
{
alert('Yes');
},
error: function(response)
{
alert('No');
}
});
I think my .save() is sending POST request to server.
UPDATE
I think I could find out my problem. I am describing that here.
What I would like to do
I would like to send 2 parameters from backbonejs model to server side script (I am using PHP SLIM Framework). Based on those 2 parameters server side script update a record's(2 field of this record match with those 2 parameters ) another field with a static parameter at database.
What backbonejs provide (As I think )
Backbonejs has a model with id as JSON format. Backbonejs sends PUT request to server side script. Server side script just dump (update) the data(which was as JSON format,like a bundle) to the database with matching id. Serer side script would not like to look inside the data.
I am getting (from network tab of firebug) my PUT request URL is like http://localhost/back/server_file.php/number/1 (This is the id) . On the other hand I would like to get URL is like http://localhost/back/server_file.php/number/1 (id the first parameter)/456 (Second parameter).
If I am right, anyone could say how can I implement my plan??
This should work,
My_model.set(my_data);
My_model.save(null, {
wait : true,
url : "http://localhost/back/server_file.php/number/1/456",
success : function(response){
},
error : function(e){
}
});
You can debug the request being sent in network tab of Chrome Developer Tools or you can use a network tool like Fiddler to see all requests.
Refer the attached on where to see the request method being used.