Synchronous XMLHttpRequest on the main thread is deprecated / AJAX & API - php

I am looking to create an ajax function with the MailChimp list API however I am facing the following error 'Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects '. PHP code works fine but when I try to introduce ajax it all goes wrong.
Honestly, I don't know where to start with this as have little experience in using ajax with API.
Could someone please be kind enough to review the below code and give me their thoughts?
$(document).ready(function() {
$("#subCard").submit(function(event) {
event.preventDefault();
var emailSub = $("#emailSub").val();
var fNameSub = $("#fNameSub").val();
var lNameSub = $("#lNameSub").val();
var subSubmit = $("#subSubmit").val();
$(".form-message").load("action.php", {
emailSub: emailSub,
fNameSub: fNameSub,
lNameSub: lNameSub,
subSubmit: subSubmit
});
});
});
<?php
session_start();
if(isset($_POST['subSubmit'])){
$emailSub = $_POST['emailSub'];
$fNameSub = $_POST['fNameSub'];
$lNameSub = $_POST['lNameSub'];
if(!empty($emailSub) && !filter_var($emailSub, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = 'user API key';
$listID = 'user list ID';
// MailChimp API URL
$memberID = md5(strtolower($emailSub));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $emailSub,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $fNameSub,
'LNAME' => $lNameSub
]
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #ffffff">You have successfully subscribed to AquaCodeStudio.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Sorry a problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
}else{
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter a valid email address.</p>';
}
}
// redirect to homepage
header('location:about.php');
?>

.load in itself is synchronous, unless something else is specified in the global jQuery AJAX settings.
The redirect to the about.php page after processing the form data seems to be the culprit here.
It actually redirects the AJAX request in the background - so first the data is send to load.php and processed there, and then the browser makes another (GET) request for about.php. What is then inserted into your original document is the content of the latter. Not sure how exactly this causes the “Synchronous…” warning, but maybe that page itself contains code that makes AJAX requests again, or something like that. (.load, when executed without a suffixed selector expression, executes <script> elements contained in the loaded HTML automatically.)

Related

get Full message from telegram bot

I want to get the full message sent by the person's ID in telegram bot , including all the attached files, such as a photo , audio, image, or a caption and photo ... , and send it to another person's ID. I don't want it to be forward , I want to be sent!
I receive all updates this way:
$data=json_decode(file_get_contents("php://input"));
my code :
<?php
const apiKey='112';
$channels=[
'1'=>'-1001233909561',
'2'=>'-1001198102700',
];
const admin='668400001';
//-------------------------------------------------------- End Channels and ADMIN Info
$data=json_decode(file_get_contents("php://input"));
$json_data=json_encode($data);
file_put_contents('data.json', $json_data);
function bot($method, $datas = [])
{
$url = "https://api.telegram.org/bot" . apiKey . "/" . $method;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datas));
$res = curl_exec($ch);
if (curl_error($ch))
{
var_dump(curl_error($ch));
}
else
{
return json_decode($res);
}
}
function forwardMessage($messageId)
{
bot('forwardMessage',[
'chat_id'=>backupChannelId,
'from_chat_id'=>firstChannelId,
'message_id'=>$messageId,
]);
}
function sendMessage($toChannel,$message)
{
}
?>
If I understand correctly, you want to get the text and all the attachments of all messages sent to the bot. For example, the text of the message is in update->message-> text.
$text = $data['message']['text'];
$audio = $data['message']['audio'];
The easiest way to send the exact same massage to another chat is by forwarding it, otherwise you have to search for all the possible attachments in the message object and, if present, send them to the other chat with the corrisponding method (sendPhoto, sendAudio etc.).
Tip:
use
$data = json_decode(file_get_contents("php://input"), true);
instead of
$data = json_decode(file_get_contents("php://input"));
More details here

How to verify hCaptcha response and ensure it is filled?

I have followed the tutorial here.
hCaptcha appears on my site, but the form can be submitted without attempting it. How can I make it a required field?
I have tried the following to make it required.
<?php
$data = array(
'secret' => "my-secret (should start with 0x..)",
'response' => $_POST['h-captcha-response']
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, "https://hcaptcha.com/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($verify);
var_dump($response);
?>
And also
<?php
if(isset($_POST['h-captcha-response']) && !empty($_POST['h-captcha-response']))
{
$secret = 'your_secret_key';
$verifyResponse = file_get_contents('https://hcaptcha.com/siteverify?secret='.$secret.'&response='.$_POST['h-captcha-response'].'&remoteip='.$_SERVER['REMOTE_ADDR']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
{
$succMsg = 'Your request have submitted successfully.';
}
else
{
$errMsg = 'Robot verification failed, please try again.';
}
}
?>
But I get a Notice: Undefined Index: error. I tried to hide the error by editing php.ini and also by adding
<?php error_reporting (E_ALL ^ E_NOTICE); ?> at the top of my file, but it doesn't work.
When I try to make it required, I get an unexpected end to file error-
$("form").submit(function(event) {
var hcaptchaVal = $('[name=h-captcha-response]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
There is a hidden field in the DOM that holds the response from the hCaptcha challenge.
Use this code to get the response:
$('[name=h-captcha-response]').val();
$() transforms an elem in a jQuery object and val() is a function from jQuery. jQuery doesn't have value property.

Search FB Messenger Message for Specific Word in PHP

So I'm trying to create a Facebook Messenger Chatbot, a very simple one. I have it working with a hardcoded response, but I want it to be able to read the senders message and respond in a specific way if it finds that word - like how chatbots should. I' trying to do so by using preg_match() but when I use my current code, the bot doesn't reply at all. Here's my code:
<?php
/**
* Webhook for Facebook Messenger Bot
*/
$access_token = "{mytoken}";
$verify_token = "{mytoken2}";
$hub_verify_token = null;
if (isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token == $verify_token) {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
// perform a case-Insensitive search for the word "time"
if (preg_match('[hi|hello|sup]', $message)) {
$answer = "Hiya!";
}
else {
$answer = "IDK.";
}
// send the response back to sender
// 'text': 'Hiya!'
$jsonData = "{
'recipient': {
'id': $sender
},
'message': {
'text': $answer
}
}";
// initiate cURL.
$ch = curl_init("https://graph.facebook.com/v2.6/me/messages?access_token=$access_token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
curl_exec($ch);
}
Do you know whether you actually receive messages from the Messenger Platform? Your webhook verification ends in an echo, where in fact you need to respond to the platform with a status code 200. You can also check your Facebook Apps dashboard to figure out whether your webhook is verified and being sent messages.
Documentation: https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup
Once you know that your webhook is verified and you are receiving messages, start with a fixed reply and then work towards dynamic responses. As #Toto suggested, adding logging will be very helpful to debug your code.

Facebook PHP Messenger Bot - receive two messages

I would like to write messenger bot based on this script:
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
// Set this Verify Token Value on your Facebook App
if ($verify_token === 'testtoken') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
// Get the Senders Graph ID
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
// Get the returned message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//API Url and Access Token, generate this token value on your Facebook App Page
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<ACCESS-TOKEN-VALUE>';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"The message you want to return"
}
}';
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request but first check if the message is not empty.
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>
All works correctly but i receive two responses to variable $message, for example:
Send "Hello";
$message = "Hello";
Receive message: "Hi";
$message = "Hi";
I would like to skip 3 and 4 points and receive only "Hello" message because i have to check if $message is my question or answer. Is it possible?
Greetings
You should skip any read and delivery messages, like this:
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
// Skipping delivery messages
if (!empty($message['delivery'])) {
continue;
}
// Skipping read messages
if (!empty($message['read'])) {
continue;
}
}
}
Or, you can deselect message_reads & message_deliveries checkboxes in Page Subscription section of your Facebook Page Settings/Webhooks.

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

Categories