How to set up a PHP Curl POST request which can trigger via a JavaScript onclick event?

1.7k Views Asked by At

I want to track the submit button click event at the form in javascript and send the submit button click event to curl PHP side and the url (https://trackcmp.net/event) in curl php file will send the event that I trigger and stored into the database(ActiveCampaign).

The form was created by ActiveCampaign and embedded into the Wordpress website.

Below are 2 files that I make, the 1st part is ajax file, and then 2nd part is PHP file.

May anyone help me please? Thank you.

(function($){
$("_form_44__submit").on('click', function () {
    // fire the AJAX request on button click
    $.ajax({
       type: "POST",
       url: 'curl.php',
       dataType: 'json',
       headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",},
       data: {actid: "actid",
    key: "key",
    event: "Click_Submit_Button_Event",
    visit: ["email"]
 },
    })
    .done(function (response) {
        console.log(response);
       // if you want to do something on success
    })
    .fail(function (xhr, status, error) {
        console.log('error');
       // if you want to do something on error
    });
  });
})
<?php


$actid = $_POST['actid'];
$key =  $_POST['key'];
$event =  $_POST['event'];
$visit =  $_POST['visit'];

$url = "https://trackcmp.net/event";

    $curl = curl_init(); //open connection /
    // changes the cURL session behavior with options POST
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POSTFIELDS, array(
        'actid' => $actid,
        'key' => $key,
        'event' => $event,
        'visit' => $visit,
));
    //execute
    $result = curl_exec($curl); //handle $curl_init
    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);
    }


?>

1

There are 1 best solutions below

3
On

I am assuming that the PHP curl works for you and that you have the data to populate the values in the ajax post so:

for the data to arrive to post PHP as $_POST you need to send it like this for example the $.ajax code:

$.ajax({
    type: "post",
    url: "curl.php",
    data: "actid=actid&key=somekey&event=Click_Submit_Button_Event&[email protected]",
    success: function (data) {
        console.log('Submission was successful.');
        console.log(data);
    },
    error: function (data) {
        console.log('An error occurred.');
        console.log(data);
    },
});

Look at the way the data: is built... you can ofcourse do : "actid="+actid+"&key="+key+ ... etc

This way your PHP file will be able to read the form data.

If you'll print your $_POST it will look something like:

Array
(
    [actid] => actid
    [key] => somekey
    [event] => Click_Submit_Button_Event
    [visit] => [email protected]
)

Edit here is a complete version with a form click and inputs :

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<html>
    <body>
        <form id="contactForm1" action="curl.php" method="post">
            Actid <input type="text" name="actid" /><br>
            Key <input type="text" name="key" /><br>
            Event <input type="text" name="event" /><br>
            Visit <input type="text" name="visit" /><br>
            <input type="submit" />
            <!-- Form input fields here (do not forget your name attributes). -->
        </form>
    </body>
</html>



<script type="text/javascript">
    var frm = $('#contactForm1');

    frm.submit(function (e) {

        e.preventDefault();
        console.log(frm.serialize()); /*show the data being sent from the form*/
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                console.log('Submission was successful.');
                console.log(data);
            },
            error: function (data) {
                console.log('An error occurred.');
                console.log(data);
            },
        });
    });
</script>

for you PHP I think you are mistaken with the array sending data ... you should try something like this: curl.php: the post data will become a json which I suspect is what you need to send to your endpoint... it will look something like this:

{"actid":"actid","key":"key","event":"Click_Submit_Button_Event","visit":"[email protected]"}

<?php
$post = json_encode($_POST);
print_r($post);

$url = "https://trackcmp.net/event";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = json_decode(curl_exec($ch),true);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

echo '<pre>';
print_r($result);