How to track event for Event Tracking Activecampaign - php

may I ask how to track the specific event with the event tracking ActiveCampaign code?`
For example, if I want to track button clicks on my own website, how do I add on in this php sample code here.
Thank you.
<?php
// initializes a cURL session
$curl = curl_init();
// changes the cURL session behavior with options
curl_setopt($curl, CURLOPT_URL, "https://trackcmp.net/event");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
"actid" => "Actid",
"key" => "Key",
"event" => "EVENT NAME",
"eventdata" => "Button click login",
"visit" => json_encode(array(
// If you have an email address, assign it here.
"email" => "",
)),
));
//execute
$result = curl_exec($curl);
if ($result !== false) {
$result = json_decode($result);
if ($result->success) {
echo 'Success! ';
} else {
echo 'Error! ';
}
echo $result->message;
} else {
echo 'cURL failed to run: ', curl_error($curl);
}
};
?>`

You will have to use AJAX and send a request to execute this segment of code on all the buttons you want to track the click event.
$(".tracked-button").on('click', function () {
// fire the AJAX request on button click
$.ajax({
type: "POST",
url: 'YOUR URL',
dataType: 'json',
headers: {},
data: {}
})
.done(function (response) {
// if you want to do something on success
})
.fail(function (xhr, status, error) {
// if you want to do something on error
});
});

Related

How to handle error from php handler file

If there is an error in the js/send_to_telegram.php file, then the error script will work. How to do it?
jQuery("form").submit(function () {
var form_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "js/send_to_telegram.php",
data: form_data,
success: function (result) {
donemodal.style.display = "block";
},
error: function (jqXHR, exception) {
errormodal.style.display = "block";
}
});
});
in js/send_to_telegram.php the following code:
$token = "5306003979:AAEPK2NhlxW";
$chat_id = "497358";
$txt = htmlspecialchars($_POST["text"]);
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");
Now, even if you enter the wrong token in $sendToTelegram, it returns success. How to get error if token is wrong?
Short answer: It doesn't use API response status code unless you tell him does that. What if we sent multiple HTTP requests and got different status codes? Which of them should be used?
Solution: This is what you need:
<?php
function post($url, $fields = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if (is_array($fields) && count($fields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$response = post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $chat_id,
'text' => $txt,
]);
if ($response->ok) {
echo '{"message": "ok"}';
} else {
http_response_code(500);
echo '{"message": "Something went wrong"}';
}

can not get cUrl response to .ajax() for redirect

I have a php cURL request which is run when .ajax() is run on form submit:
// A sample PHP Script to POST data using cURL
$headers = array(
'Access-Control-Allow-Headers: Authorization',
'x-api-key: xxxxx',
'Content-Type: application/json',
);
$post_data = '{
"user_email": "'.stripslashes($_POST['email']).'",
"user_firstname": "'.stripslashes($_POST['personName']).'",
}';
// Prepare new cURL resource
$crl = curl_init('https://api.examplesite.com/api/site');
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLINFO_HEADER_OUT, true);
curl_setopt($crl, CURLOPT_POST, true);
curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);
// Set HTTP Header for POST request
curl_setopt($crl, CURLOPT_HTTPHEADER, $headers);
// Submit the POST request
$result = curl_exec($crl);
if(curl_exec($crl) === false) {
echo 'Curl error: ' . curl_error($crl);
} else {
$output = json_decode($result, true);
echo json_encode($output);
}
// close the request
curl_close($crl);
And here's the .ajax() post:
$.ajax({
type: "POST",
url: location.href,
dataType: "json",
data: {
ajaxRequest: 1,
sendDemoEmail: sendDemoEmail,
email: email.val(),
personName: name.length != 0 ? name.val() : 'no_name',
},
success: function (data) { // CANT RETRIEVE SUCCESS
console.log('yes result', data);
$('#result').html(data);
},
error: function (data) { // RUNS ERROR
console.log('no result', data);
$('#result').html(data); // EMPTY
},
The result from cUrl is as follows:
{"errors":[],"messages":[],"site_url":"https:\/\/www.site.com\/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2ZXJpZmljYXRpb25fY29kZSI6IiQyeSQxMCQzWXQwWlE1d0FGd0ZWaHNFdnZwdm0uQnl4WVNyS29EejlKVTZEQ0xzNnBtUFd1VFA2MFwvSE8iLCJuZXdfdHJpYWxfZ"}
User flow:
submit form with email with .ajax() POST
send data with cUrl to API
retrieve data from API response in cUrl json_decode
use the cUrl API response in my .ajax() POST to redirect to the site_url in the reponse.
I am unable to get a success from the .ajax() POST (it return error) and also unable to also access the site_url in the .ajax() for a redirect after a success. What am I doing wrong here?
Needed to add a exit(); to the PHP cUrl after the curl_close so my JSON response would not include site HTML
// close the request
curl_close($crl);
exit();

PHP Curl and json post error false

I'm a newbie when it comes to using PHP curl and ajax
I've been asked to do the following (an image is attached for your consideration).. there are the requirements
initially I tried sending request with jquery ajax but it was not working here is the code:
function sendAPI(){
$.ajax({
url: "https://someurl.com/api/page/index",
headers: {
'x-api-key':"[API KEY GIVEN BY THE COMPANY]",
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'jsonp',
data: {
id: "7001345730",
recordNo: "1000000000",
recordDate: "2017-12-12",
phone: "+966555555555",
extension: "1234",
email: "feras#test.com",
managerName: "Amjad",
managerPhone: "+966555555555",
managerMobile: "+966555555555"
},
success: function(data){
console.log('lllk');
console.log('succes: ' + data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("textStatus: ", textStatus);
console.log("errorThrown: ", errorThrown);
}
});
}
sendAPI();
I get the following error message displayed on my console
Please note: I tried both json and jsonp dataType but same result
textStatus: error
errorThrown: error
Afterwards I tried php curl but I am getting the error on that too.
here is php curl code:
$id ="7001345730";
$recordNo = "1000000000" ;
$recordIssueDate = "2017-12-12" ;
$phone = "+966555555555" ;
$extension = "1234" ;
$email = "feras#test.com" ;
$managerName = "Adeel Essa" ;
$managerPhone = "+966555555555" ;
$managerMobile = "+966555555555";
$data = array(
"id" => $id,
"recordNo" => $recordNo,
"recordIssueDate" => $recordIssueDate,
"phone" => $phone,
"extension" => $extension,
"email" => $email,
"managerName" => $managerName,
"managerPhone" => $managerPhone,
"managerMobile" => $managerMobile,
);
$ch = curl_init('https://someurl.com/api/page/index');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"x-api-key: 56DAAC8KAD-SFOL9267B-B97E1A9E"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch); //get return String
echo json_encode($result);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch);
if (isset($error_msg)) {
print_r($error_msg);
}
When I execute the above code I get the following error:
false
Failed to connect to wasl.elm.sa port 443: Timed out
In the end my only question is:
If I am doing right or there is something is missing in my code.
On both JQuery and PHP CURL codes.
If so what do I need to change.
Requirements are also mentioned in the above image
Please Help

How to pass variable from view to controller using ajax

I am trying to pass the variable from view file to include_player_id in controller file using ajax and execute the function. Here is what I have in hand.
Please help me on this. I spent days to make it but I am not successful in ajax.
View.php
<p><?php echo $ticket->last_name ?></p>
<input type="submit" class="btn-primary" value="<?php echo lang("ctn_474") ?>">
Controller.php
function sendMessage(){
$content = array(
"en" => 'Message'
);
$fields = array(
'app_id' => "XXXXX-XXXXX-XXXXX-XXXXX",
'include_player_ids' => array("XXXXXXXX-XXXXXXXX-XXXXXXXXXX"),
'data' => array("foo" => "bar"),
'large_icon' =>"ic_launcher_round.png",
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
I believe I need something like that
<script>
$(document).ready(function($){
$(".btn-primary").click(function(){
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/application/controllers/Ticket.php",
data: {
'data':<?php echo $ticket->last_name ?>
},
contentType:'Text',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
Thanks for edition your post and providing the needed information. Let's assume you have a working HTTP Endpoint (GET) under BASE_URL+"/application/controllers/Ticket.php" (you can verify that it's working if you call the given URL in your browser).
Let's also assume that your sendMessage() function works like expected and does not contains bugs. I'd suggest you alter your Controller.php to something like this for testing purpose:
// static values, so we can be sure we get a predictable result for testing
$response = array['test1', 'test2'];
// rename the variable, return is a keyword and could cause problems
$result["allresponses"] = $response;
$json_result = json_encode( $result);
// comment this line, it will break the JSON.parse
// print("\n\nJSON received:\n");
// echo is just fine
echo $json_result;
// comment this line, it's not necessary
// print("\n");
Now try to call your controller under the given URI in your browser. If everything works fine you should see something like this:
{"allresponses": ["test1", "test2"]}
as result in your browser.
Let's come to the HTML, JS part.
Your button should look like this :
// make this a button not submit - submit is for sending forms
// give the button an ID
<input type="button" class="btn-primary" id="myCoolButton" value="Click me"></input>
And your script could look like:
<script>
$(document).ready(function($){
// bind the function to the ID, otherwise all primary buttons would perform this function
$("#myCoolButton").click(function(){
$.ajax({
// it's a GET endpoint as far as I understand your code, POST if creating new ressources
type: "GET",
datatype:"json",
// enter your working endpoint URL here (the one you tested in your browser)
url: BASE_URL+"/application/controllers/Ticket.php",
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
HTH

cURL Equivalent to xhrFields: {withCredentials: true}

Goal:
Log into processor's site using their API and store the success response into COOKIEs and SESSIONs on my site.
What almost works:
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: 'Email={email}&GuestSessionToken={token}&Password={pass}&Format=JSON&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('success'); },
error: function (jqXHR, textStatus, ex) {
console.log('error');
}
});
});
Why it doesn't work:
I'm unable to store the response to COOKIEs and SESSIONs.
What I would like to work:
$url = {url-to-api};
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
Why it doesn't work:
This will return a success response that I can use to set the COOKIEs and SESSIONs, but it will not log the user into the processor's site.
Why I think it doesn't work:
The ajax call wouldn't sign the user in until I added the xhrFields part. I think if I could find a cURL equivalent for the xhrFields part, I would be all set.
Thanks in advance!
My duct tape fix.
<?php
// If signin form is submitted and signin cURL was successful.
echo (isset($fields['signin_script'])) ? $fields['signin_script'] : "";
function processor_signin(&$fields, &$errors) {
$url = '{url-to-api-call}';
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
// Duct tape fix
$fields['signin_script'] = "
<script>
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: '
Email=".$fields['user_email']."
&GuestSessionToken=".$_COOKIE['SessionToken']."
&Password=".$fields['user_pass']."
&Format=JSON
&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('signin success'); },
error: function (jqXHR, textStatus, ex) {
console.log('signin error');
}
});
});
</script>
";
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
}
?>
Maybe you are logged in but you are not storing the cookies.
So you need to parse the headers and in the end store all cookies. In proceeding requests you need to send back all cookies that you retrieved before.
Here is an example how to retrieve the cookies and other headers from the server:
public function sendRequest(HttpRequest $request)
{
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, 'fetchHeader']);
...
$content = curl_exec($ch);
...
}
/**
* #param resource $ch - curl handle
* #param string $header
*
* #return int
*/
private function fetchHeader($ch, $header)
{
$headerParts = explode(': ', $header, 2);
if (2 === count($headerParts)) {
$headerName = strtolower($headerParts[0]);
if ('set-cookie' === $headerName) {
$this->responseHeaders[$headerName][] = trim($headerParts[1]);
return strlen($header);
}
$this->responseHeaders[$headerName] = trim($headerParts[1]);
}
return strlen($header);
}

Categories