0

How do I make a post request with curl without using a button, but instead calling the external API when a field is filled out

0

You need to create a custom controller and post data in that through ajax, then use curl in the controller:

  $curl_handle=curl_init();
  curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com');
  curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
  curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
  $buffer = curl_exec($curl_handle);
  curl_close($curl_handle);
  if (empty($buffer)){
      print "Nothing returned from url.<p>";
  }
  else{
      print $buffer;
  }
0

If you are working within Magento Try to use magento logic where possible rather than native php functions

/**
 * @var \Magento\Framework\HTTP\Client\Curl
 */
protected $_curl;

/**
 * @param Context                             $context
 * @param \Magento\Framework\HTTP\Client\Curl $curl
 */
public function __construct(
    Context $context,
    \Magento\Framework\HTTP\Client\Curl $curl
) {
    $this->_curl = $curl;
    parent::__construct($context);
}

public function execute()
{
    //if the method is get
    $this->_curl->get($url);
    //if the method is post
    $this->_curl->post($url, $params);
    //response will contain the output in form of JSON string
    $response = $this->_curl->getBody();
}

More can be found here

https://github.com/magento/magento2/blob/2.3/lib/internal/Magento/Framework/HTTP/Client/Curl.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.