Cant receive callback for google hangout button - javascript

I have following hangout button js code, I expect callback when user clicks on hangout button. Its not working, is anything wrong ?
gapi.hangout.render('hangout-button', {
'render': 'createhangout',
'topic': 'hangout_test',
'invites': "[{'id': 'xxx#gmail.com', 'invite_type': 'EMAIL'}]",
'initial_apps': [{
'app_id': "google_app_id",
'app_type': 'ROOM_APP',
'start_data': {
"user_id": "user_id",
"user_email": "user_email",
"token": "token",
"callback_url": "abc.com/hooks/hangout",
"host": "abc.com",
"callback_data": "user_data"
}
}],
'hangout_type': "normal",
'widget_size': 130
});

You need to listen for the onApiReady event from Hanogut and then call getHangoutUrl on gapi.hangout. As explained in their documention here:
https://developers.google.com/+/hangouts/api/gapi.hangout.html#gapi.hangout.ApiReadyEvent
Adding the same code below:
gapi.hangout.onApiReady.add(function(eventObj) {
var hangoutUrl = gapi.hangout.getHangoutUrl();
// After saving the url to a variable, pass it using an Ajax call
$.ajax({
type: "POST",
url: callbackUrl,
success: successFunc,
dataType: 'json',
data: JSON.stringify({
"hangoutUrl": hangoutUrl,
})
});
});
Reference: https://stackoverflow.com/a/30609147/2545197

Related

How to access data returned from an API using jQuery

I'm doing an AJAX GET request to an API that returns all stores in my area that offer express delivery. I need to check over the data to see if any store in the area offer express delivery but can't access the data properly to perform any check's and don't understand why.
A stripped back version of the data returned from the API is here:
{
"data": {
"service_eligibility": [
{
"accesspoint_list": [
{
"current_time": null,
"currency": null,
"accesspoint_id": "3242342-6dc1-43d8-b3d0-234234234234",
"service_info": {
"fulfillment_type": "DELIVERY",
"reservation_type": "SLOTS",
"dispense_type": "DELIVERY",
"priority": 0,
"carrier": "Owned",
"fulfillment_option": "DELIVERY",
"location_type": "Home",
"service_time": 0,
"is_recurring_slot": false,
"enable_express": false,
"is_unattended_slot": true,
"is_flex_slot": false
},
{
"current_time": null,
"currency": null,
"accesspoint_id": "234234242-3387-4e1d-9eaa-234234242",
"service_info": {
"fulfillment_type": "INSTORE_PICKUP",
"reservation_type": "SLOTS",
"dispense_type": "PICKUP_INSTORE",
"priority": 0,
"carrier": "NA",
"fulfillment_option": "PICKUP",
"location_type": "Store",
"service_time": 0,
"is_recurring_slot": false,
"enable_express": true,
"is_unattended_slot": false,
"is_flex_slot": false
},
"current_time": "2021-06-07T11:24:39Z",
"currency": "GBP"
},
"status_code": 200,
"status_message": "Requested input executed successfully."
}
The call I use to get my data:
$.ajax({
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(data)
{
//Check for express delivery
if(data.status_code == 200) {
console.log(data);
}
},
error: function(data)
{
//Check for API error
if(data.status == 400){
console.log(data.responseJSON.errors[0].message);
}
}
})
So far the data is being logged to the console. But when I try to access it or parts I want to use I get console errors.
I have tried copying the property path from the console and using it in the console.log:
console.log(data.service_eligibility[0].accesspoint_list)
but get the error message:
Cannot read property '0' of undefined
I have tried just data.service_eligibility but this just give me the error of undefined
In fact even if I just try to access data.currency I get undefined
Why can I not access the data being returned from the API?
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(data)
{
//Check for express delivery
if(data.status_code == 200) {
console.log(response.data.ervice_eligibility[0].accesspoint_list);
}
}
Looking at the above piece of code you have provided, it looks like, the data object that you are receiving in the success handler does not directly refer to the data object inside your received response. Given the names are same, it can be confusing.
I think if you try accessing the property inside the data object using data.data.service_eligibility, you will be able to access it. For some more clarity, see the code below:
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(response)
{
//Check for express delivery
if(response.status_code == 200) {
console.log(response.data.service_eligibility[0].accesspoint_list);
}
}
Just think about it, if your data is available inside the success handler, it means that the asynchronous action of fetching the data from the api has successfully completed. You can just debug the structure of your data object and find out what's missing or what's wrong in the way you are accessing a value. People can behave differently, code can never! :)

MethodNotAllowedHttpException when trying to post data to controller via ajax in laravel

I'm trying to send dynamically generated data to controller via ajax in laravel. When user select an option from the dropdown then along with selected option and other data should be sent to controller.
I've tried to send data to controller when an option from dropdown is selected. But every time i try this error,
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
and in the error
REQUEST_METHOD is GET
This is the where i call the ajax function
$(document).on('change', '.route-code-selector', function() {
var selectorID = $(this).attr('id');
addRoutePlanDetails(selectorID);
});
AJAX function
function addRoutePlanDetails(selectorID) {
var routePlanCode = document.getElementById("routeplanno").value;
var driver = $("#selectDriver").val().split('|');
var salesman = $("#selectSalesman").val().split('|');
var router_01 = $("#selectRouter01").val().split('|');
var router_02 = $("#selectRouter02").val().split('|');
var vehicle_no = document.getElementById("enterVehicleNo").value;
var route_code = document.getElementById(selectorID).value;
var date = document.getElementById("date").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: 'addNewRoute',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
}
Route
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get ('route-plan', 'RoutePlanController#index');
Route::get ('excludePorterRes', 'RoutePlanController#excludePorterRes');
Route::get ('retreiveRouteData', 'RoutePlanController#retrieveRouteCodeData');
Route::get ('retreiveUserData', 'RoutePlanController#retreiveUserData');
Route::get ('retreiveNewRouteData', 'RoutePlanController#retreiveNewRouteData');
Route::post('addNewRoute', [
'uses' => 'RoutePlanController#insertNewRoute',
'as' => 'addNewRoute'
]);
});
controller
public function insertNewRoute(){
$routeplan = new Routeplan;
$user_email = auth()->user()->email;
$routeplan->RouteplanCode = Input::get('routePlanCode');
$routeplan->RouteCode = Input::get('route_code');
$routeplan->DriverID = Input::get('driver');
$routeplan->SalesmanID = Input::get('salesman');
$routeplan->Routercode1 = Input::get('router_01');
$routeplan->Routercode2 = Input::get('router_02');
$routeplan->VehicleNo = Input::get('vehicle_no');
$routeplan->Date = Input::get('date');
$routeplan->Createuser = $user_email;
$routeplan->Status = 'TEMP';
$routeplan->save();
}
when user select an option all the data should be stored in the db.
Try it once
url: '{{ route('addNewRoute') }}',
The issue is here:
url: 'addNewRoute',
here you are calling the route in a wrong manner, use it like:
url: '{{ url('admin/addNewRoute') }}',
you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin, so you have to append that to while calling it.
If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. (before .js file is loaded);
Example var url = '{{ route('addNewRoute') }}'
$.ajax({
url: url',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
If you using ajax in the blade, you can use directly route as ajax request url.
$.ajax({
url: "{{ route('addNewRoute') }}",
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
You forgot / in your routes.
Route::group(['prefix' => 'admin'], function () {
Add / in admin/
Route::group(['prefix' => 'admin/'], function () {
Then you can try this in your ajax
url: '{{ url('admin/addNewRoute') }}',
or
url: 'admin/addNewRoute',
Try if this will work.
You have used prefix for your routes. So all your route in group will be prefix/uri.
So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type
$.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
In ajax for specifying HTTP Verb use type not method.
if your script is in blade file then use route() to set url in ajax:
$.ajax({
url: '{{route('addNewRoute')}}',
method: 'POST',
dataType: 'json',
...
});
Try this:
Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'.
As many of you said.. I changed method to type.. And it still didn't work. But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. And that's why it still gave me the 500 error. After I changed the syntax and do the corrections. It worked !! Anyways thanks for helping guys! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone.

Rails nested attributes passing with jQuery

I have the following definition:
params.require(:sets).permit(:name, zones_attributes: [:latitude, :longitude])
And i would like to send them by ajax with jQuery, thing is I think i'm constructing it wrong because I keep getting this error:
Unpermitted parameters: 0, 1
This is what I'm sending:
{
"sets"=>{
"name"=>"America",
"zones_attributes"=>{
"0"=>[
"49.95121990866204",
"-117.861328125"
],
"1"=>[
"-33.578014746143985",
"-55.986328125"
]
}
},
"action"=>"create",
"controller"=>"sets"
}
I think the problem is the "key" value being added before the latitude/longitude value.
This is how I'm adding those values:
this.zones.push([marker.position.lat(), marker.position.lng()]);
Is there a way to add them without the keys? Or am I going through the wrong way?
UPDATE
ajax code:
$.ajax({
type: "POST",
url: '/zone_sets',
data: { zone_sets: { name: map.markerListName ,zones_attributes: map.zones } },
success: function (data) { $("input[name=zone_set]").append(data) },
});
Change your current ajax code to:
$.ajax({
type: "POST",
dataType: 'json',
headers: {
'Content-Type': 'application/json'
},
url: '/zone_sets',
data: JSON.stringify({ zone_sets: { name: map.markerListName ,zones_attributes: map.zones } }),
success: function (data) { $("input[name=zone_set]").append(data) },
});
As you can see the actual problem is how the Rails handle and parse a request.
You should be adding them like this:
this.zones.push({'latitude': marker.position.lat(), 'longitude': marker.position.lng()});
Yes, the "key" looks like it's the problem.
params.require(:sets).permit(:name, zones_attributes: [:latitude, :longitude]) is expecting your request to be in the format:
{
"sets"=>{
"name"=>"America",
"zones_attributes"=>[
{
"latitude": "49.95121990866204",
"longitude": "-117.861328125"
},
{
"latitude": "-33.578014746143985",
"longitude": "-55.986328125"
}
]
},
"action"=>"create",
"controller"=>"sets"
}
i.e. the "0" and "1" the error is referring to are like array indices.

How can I get response from webservice in jquery?

I want to get the data response from my login webservice. Here is my web service
http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a
(for testing). Here is my code:
$("#login").click(function () {
var url = "http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a";
$.ajax({
url: url,
type: 'Get',
success: function (data) {
alert(data.Medical_id);
},
});
});
The alert() shows me undefined. Please advise on what the problem could be.
The result is an array, so in order to get that field you have to iterate the result or get the first item:
for (var i in data) {
console.log(d[i].Medical_id);
}
Or you can simply get the first result:
$.ajax({
url: 'http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a',
type: 'Get',
success: function (data) {
alert(data[0].Medical_id);
}
});
The JSON result you are getting is :
[{"$id":"1","id":8,"Medical_id":"a","Password":"a","Name":null,"Email":null,"gender":null,"Type":null}]
use for each to iterate through the results or
instead of this you can check the result like this :
var data = [{ "$id": "1", "id": 8, "Medical_id": "a", "Password": "a", "Name": null, "Email": null, "gender": null, "Type": null }]
alert(data[0].Medical_id);
If you develop application in localhost then refer this questions also.
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
If you are using chrome, then use this link to use CORS enable plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US
hope this will help

Ajax submission on page load

I'm trying to create a test script for a small little website I'm doing, and it requires a lot of troubleshooting with this particular form. In order to get a response, I need to fill out 5 step form wizard and then wait for the results. I've been trying to create a small little script I can use on a seperate page to test my php functions in a heartbeat. Here is what I have so far, and it doesn't seem to even post to the page.
<div id="response"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var data = {
console: "playstation",
game: "FIFA14",
coinamount: "10000",
team: "Some Team Name",
league: "Some League Name",
player: "Some Player Name",
quality: "Silver",
chemistry: "Basic",
position: "CAM",
customername: "Joey Small",
customeremail: "jsmall#email.com",
customerphonenumber: "23454343534",
payment: "pp"
}
$.ajax({
type: "POST",
url: "order.php",
data: data,
cache: false,
contentType: false,
processData: false,
success: function(data){
$("#response").html(data);
}
});
});
</script>
I'm inspecting the network data in my browser, and it is not sending to order.php. I don't have much love for javascript, especially Jquery, so any help would be greatly appreciated.
first thing you should do is close the script tag on your Jquery include at the top
Ok, so the additional options added on to the end are what is making the script not submit.
$.ajax({
type: "POST",
url: "order.php",
data: data,
success: function(data){
//alert("---"+data);
$("#response").html(data);
}
});
That works correctly. Daedalus's comment got me to thinking about the additional tags, and how they are not needed.

Categories