2

I've very new to PHP and am trying to get API (REST) to work with a site I'm currently working on. It works if I submit a form using AJAX but I want it to work without using AJAX. The code I'm using is:

<?php

$postContactUrl = 'https://apiconnector.com/v2/contacts/';
$data = array(
    'Email' => $_POST['email'],
    'EmailType' => 'Html',
    'dataFields' => array(
        array(
            'Key' => 'FULLNAME',
            'Value' => $_POST['name_first'] . " " . $_POST['name_last']
        ),
    )
);
$contact = execute_post($postContactUrl, $data);

$addContactToAddressBookUrl = 'https://apiconnector.com/v2/address-books/' . '123456' . '/contacts';
$book = execute_post($addContactToAddressBookUrl, $contact);

function execute_post($url, $data)
{
    $requestBody = json_encode($data, true);

    $ch = curl_init();

    curl_setopt($ch, CURLAUTH_BASIC, CURLAUTH_DIGEST);
    curl_setopt($ch, CURLOPT_USERPWD, 'username' . ':' . 'password');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: ' . 'application/json', 'Content-Type: application/json'));

    $responseBody = json_decode(curl_exec($ch));

    curl_close($ch);

    return $responseBody;
}

but when I try to add that to the page the form is on I get this error:

PHP Fatal error: Call to undefined function execute_post()

I've tried to fix it but nothing I do seems to work. I don't understand why it works with AJAX but not any other way.

1 Answer 1

2

your function should be before your calling function method

function execute_post(){
}

    $contact = execute_post($postContactUrl, $data);
Sign up to request clarification or add additional context in comments.

4 Comments

In PHP, you can call a function before defining it. That should not be the problem here.
it is same for all language echo lib(); anthen you cannot write function function should be installed before calling. you can test it by yoursef wirte a function in another php file call the function and include below the calling function
I did try that and although it then didn't throw any errors it didn't work either.
Does anybody have any suggestions? I'm desperate to get this to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.